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 "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 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 } // end anonymous namespace 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw___float128: 112 case tok::kw_wchar_t: 113 case tok::kw_bool: 114 case tok::kw___underlying_type: 115 case tok::kw___auto_type: 116 return true; 117 118 case tok::annot_typename: 119 case tok::kw_char16_t: 120 case tok::kw_char32_t: 121 case tok::kw_typeof: 122 case tok::annot_decltype: 123 case tok::kw_decltype: 124 return getLangOpts().CPlusPlus; 125 126 default: 127 break; 128 } 129 130 return false; 131 } 132 133 namespace { 134 enum class UnqualifiedTypeNameLookupResult { 135 NotFound, 136 FoundNonType, 137 FoundType 138 }; 139 } // end anonymous namespace 140 141 /// \brief Tries to perform unqualified lookup of the type decls in bases for 142 /// dependent class. 143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 144 /// type decl, \a FoundType if only type decls are found. 145 static UnqualifiedTypeNameLookupResult 146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 147 SourceLocation NameLoc, 148 const CXXRecordDecl *RD) { 149 if (!RD->hasDefinition()) 150 return UnqualifiedTypeNameLookupResult::NotFound; 151 // Look for type decls in base classes. 152 UnqualifiedTypeNameLookupResult FoundTypeDecl = 153 UnqualifiedTypeNameLookupResult::NotFound; 154 for (const auto &Base : RD->bases()) { 155 const CXXRecordDecl *BaseRD = nullptr; 156 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 157 BaseRD = BaseTT->getAsCXXRecordDecl(); 158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 159 // Look for type decls in dependent base classes that have known primary 160 // templates. 161 if (!TST || !TST->isDependentType()) 162 continue; 163 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 164 if (!TD) 165 continue; 166 if (auto *BasePrimaryTemplate = 167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 169 BaseRD = BasePrimaryTemplate; 170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 171 if (const ClassTemplatePartialSpecializationDecl *PS = 172 CTD->findPartialSpecialization(Base.getType())) 173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 174 BaseRD = PS; 175 } 176 } 177 } 178 if (BaseRD) { 179 for (NamedDecl *ND : BaseRD->lookup(&II)) { 180 if (!isa<TypeDecl>(ND)) 181 return UnqualifiedTypeNameLookupResult::FoundNonType; 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 } 184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 186 case UnqualifiedTypeNameLookupResult::FoundNonType: 187 return UnqualifiedTypeNameLookupResult::FoundNonType; 188 case UnqualifiedTypeNameLookupResult::FoundType: 189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 190 break; 191 case UnqualifiedTypeNameLookupResult::NotFound: 192 break; 193 } 194 } 195 } 196 } 197 198 return FoundTypeDecl; 199 } 200 201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 202 const IdentifierInfo &II, 203 SourceLocation NameLoc) { 204 // Lookup in the parent class template context, if any. 205 const CXXRecordDecl *RD = nullptr; 206 UnqualifiedTypeNameLookupResult FoundTypeDecl = 207 UnqualifiedTypeNameLookupResult::NotFound; 208 for (DeclContext *DC = S.CurContext; 209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 210 DC = DC->getParent()) { 211 // Look for type decls in dependent base classes that have known primary 212 // templates. 213 RD = dyn_cast<CXXRecordDecl>(DC); 214 if (RD && RD->getDescribedClassTemplate()) 215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 216 } 217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 218 return nullptr; 219 220 // We found some types in dependent base classes. Recover as if the user 221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 222 // lookup during template instantiation. 223 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 224 225 ASTContext &Context = S.Context; 226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 227 cast<Type>(Context.getRecordType(RD))); 228 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 229 230 CXXScopeSpec SS; 231 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 233 TypeLocBuilder Builder; 234 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 235 DepTL.setNameLoc(NameLoc); 236 DepTL.setElaboratedKeywordLoc(SourceLocation()); 237 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 238 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 239 } 240 241 /// \brief If the identifier refers to a type name within this scope, 242 /// return the declaration of that type. 243 /// 244 /// This routine performs ordinary name lookup of the identifier II 245 /// within the given scope, with optional C++ scope specifier SS, to 246 /// determine whether the name refers to a type. If so, returns an 247 /// opaque pointer (actually a QualType) corresponding to that 248 /// type. Otherwise, returns NULL. 249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 250 Scope *S, CXXScopeSpec *SS, 251 bool isClassName, bool HasTrailingDot, 252 ParsedType ObjectTypePtr, 253 bool IsCtorOrDtorName, 254 bool WantNontrivialTypeSourceInfo, 255 IdentifierInfo **CorrectedII) { 256 // Determine where we will perform name lookup. 257 DeclContext *LookupCtx = nullptr; 258 if (ObjectTypePtr) { 259 QualType ObjectType = ObjectTypePtr.get(); 260 if (ObjectType->isRecordType()) 261 LookupCtx = computeDeclContext(ObjectType); 262 } else if (SS && SS->isNotEmpty()) { 263 LookupCtx = computeDeclContext(*SS, false); 264 265 if (!LookupCtx) { 266 if (isDependentScopeSpecifier(*SS)) { 267 // C++ [temp.res]p3: 268 // A qualified-id that refers to a type and in which the 269 // nested-name-specifier depends on a template-parameter (14.6.2) 270 // shall be prefixed by the keyword typename to indicate that the 271 // qualified-id denotes a type, forming an 272 // elaborated-type-specifier (7.1.5.3). 273 // 274 // We therefore do not perform any name lookup if the result would 275 // refer to a member of an unknown specialization. 276 if (!isClassName && !IsCtorOrDtorName) 277 return nullptr; 278 279 // We know from the grammar that this name refers to a type, 280 // so build a dependent node to describe the type. 281 if (WantNontrivialTypeSourceInfo) 282 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 283 284 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 285 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 286 II, NameLoc); 287 return ParsedType::make(T); 288 } 289 290 return nullptr; 291 } 292 293 if (!LookupCtx->isDependentContext() && 294 RequireCompleteDeclContext(*SS, LookupCtx)) 295 return nullptr; 296 } 297 298 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 299 // lookup for class-names. 300 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 301 LookupOrdinaryName; 302 LookupResult Result(*this, &II, NameLoc, Kind); 303 if (LookupCtx) { 304 // Perform "qualified" name lookup into the declaration context we 305 // computed, which is either the type of the base of a member access 306 // expression or the declaration context associated with a prior 307 // nested-name-specifier. 308 LookupQualifiedName(Result, LookupCtx); 309 310 if (ObjectTypePtr && Result.empty()) { 311 // C++ [basic.lookup.classref]p3: 312 // If the unqualified-id is ~type-name, the type-name is looked up 313 // in the context of the entire postfix-expression. If the type T of 314 // the object expression is of a class type C, the type-name is also 315 // looked up in the scope of class C. At least one of the lookups shall 316 // find a name that refers to (possibly cv-qualified) T. 317 LookupName(Result, S); 318 } 319 } else { 320 // Perform unqualified name lookup. 321 LookupName(Result, S); 322 323 // For unqualified lookup in a class template in MSVC mode, look into 324 // dependent base classes where the primary class template is known. 325 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 326 if (ParsedType TypeInBase = 327 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 328 return TypeInBase; 329 } 330 } 331 332 NamedDecl *IIDecl = nullptr; 333 switch (Result.getResultKind()) { 334 case LookupResult::NotFound: 335 case LookupResult::NotFoundInCurrentInstantiation: 336 if (CorrectedII) { 337 TypoCorrection Correction = CorrectTypo( 338 Result.getLookupNameInfo(), Kind, S, SS, 339 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 340 CTK_ErrorRecovery); 341 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 342 TemplateTy Template; 343 bool MemberOfUnknownSpecialization; 344 UnqualifiedId TemplateName; 345 TemplateName.setIdentifier(NewII, NameLoc); 346 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 347 CXXScopeSpec NewSS, *NewSSPtr = SS; 348 if (SS && NNS) { 349 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 350 NewSSPtr = &NewSS; 351 } 352 if (Correction && (NNS || NewII != &II) && 353 // Ignore a correction to a template type as the to-be-corrected 354 // identifier is not a template (typo correction for template names 355 // is handled elsewhere). 356 !(getLangOpts().CPlusPlus && NewSSPtr && 357 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 358 Template, MemberOfUnknownSpecialization))) { 359 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 360 isClassName, HasTrailingDot, ObjectTypePtr, 361 IsCtorOrDtorName, 362 WantNontrivialTypeSourceInfo); 363 if (Ty) { 364 diagnoseTypo(Correction, 365 PDiag(diag::err_unknown_type_or_class_name_suggest) 366 << Result.getLookupName() << isClassName); 367 if (SS && NNS) 368 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 369 *CorrectedII = NewII; 370 return Ty; 371 } 372 } 373 } 374 // If typo correction failed or was not performed, fall through 375 case LookupResult::FoundOverloaded: 376 case LookupResult::FoundUnresolvedValue: 377 Result.suppressDiagnostics(); 378 return nullptr; 379 380 case LookupResult::Ambiguous: 381 // Recover from type-hiding ambiguities by hiding the type. We'll 382 // do the lookup again when looking for an object, and we can 383 // diagnose the error then. If we don't do this, then the error 384 // about hiding the type will be immediately followed by an error 385 // that only makes sense if the identifier was treated like a type. 386 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 387 Result.suppressDiagnostics(); 388 return nullptr; 389 } 390 391 // Look to see if we have a type anywhere in the list of results. 392 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 393 Res != ResEnd; ++Res) { 394 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 395 if (!IIDecl || 396 (*Res)->getLocation().getRawEncoding() < 397 IIDecl->getLocation().getRawEncoding()) 398 IIDecl = *Res; 399 } 400 } 401 402 if (!IIDecl) { 403 // None of the entities we found is a type, so there is no way 404 // to even assume that the result is a type. In this case, don't 405 // complain about the ambiguity. The parser will either try to 406 // perform this lookup again (e.g., as an object name), which 407 // will produce the ambiguity, or will complain that it expected 408 // a type name. 409 Result.suppressDiagnostics(); 410 return nullptr; 411 } 412 413 // We found a type within the ambiguous lookup; diagnose the 414 // ambiguity and then return that type. This might be the right 415 // answer, or it might not be, but it suppresses any attempt to 416 // perform the name lookup again. 417 break; 418 419 case LookupResult::Found: 420 IIDecl = Result.getFoundDecl(); 421 break; 422 } 423 424 assert(IIDecl && "Didn't find decl"); 425 426 QualType T; 427 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 428 DiagnoseUseOfDecl(IIDecl, NameLoc); 429 430 T = Context.getTypeDeclType(TD); 431 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 432 433 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 434 // constructor or destructor name (in such a case, the scope specifier 435 // will be attached to the enclosing Expr or Decl node). 436 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 437 if (WantNontrivialTypeSourceInfo) { 438 // Construct a type with type-source information. 439 TypeLocBuilder Builder; 440 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 441 442 T = getElaboratedType(ETK_None, *SS, T); 443 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 444 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 445 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 446 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 447 } else { 448 T = getElaboratedType(ETK_None, *SS, T); 449 } 450 } 451 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 452 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 453 if (!HasTrailingDot) 454 T = Context.getObjCInterfaceType(IDecl); 455 } 456 457 if (T.isNull()) { 458 // If it's not plausibly a type, suppress diagnostics. 459 Result.suppressDiagnostics(); 460 return nullptr; 461 } 462 return ParsedType::make(T); 463 } 464 465 // Builds a fake NNS for the given decl context. 466 static NestedNameSpecifier * 467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 468 for (;; DC = DC->getLookupParent()) { 469 DC = DC->getPrimaryContext(); 470 auto *ND = dyn_cast<NamespaceDecl>(DC); 471 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 472 return NestedNameSpecifier::Create(Context, nullptr, ND); 473 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 474 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 475 RD->getTypeForDecl()); 476 else if (isa<TranslationUnitDecl>(DC)) 477 return NestedNameSpecifier::GlobalSpecifier(Context); 478 } 479 llvm_unreachable("something isn't in TU scope?"); 480 } 481 482 /// Find the parent class with dependent bases of the innermost enclosing method 483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 484 /// up allowing unqualified dependent type names at class-level, which MSVC 485 /// correctly rejects. 486 static const CXXRecordDecl * 487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 488 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 489 DC = DC->getPrimaryContext(); 490 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 491 if (MD->getParent()->hasAnyDependentBases()) 492 return MD->getParent(); 493 } 494 return nullptr; 495 } 496 497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 498 SourceLocation NameLoc, 499 bool IsTemplateTypeArg) { 500 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 501 502 NestedNameSpecifier *NNS = nullptr; 503 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 504 // If we weren't able to parse a default template argument, delay lookup 505 // until instantiation time by making a non-dependent DependentTypeName. We 506 // pretend we saw a NestedNameSpecifier referring to the current scope, and 507 // lookup is retried. 508 // FIXME: This hurts our diagnostic quality, since we get errors like "no 509 // type named 'Foo' in 'current_namespace'" when the user didn't write any 510 // name specifiers. 511 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 512 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 513 } else if (const CXXRecordDecl *RD = 514 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 515 // Build a DependentNameType that will perform lookup into RD at 516 // instantiation time. 517 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 518 RD->getTypeForDecl()); 519 520 // Diagnose that this identifier was undeclared, and retry the lookup during 521 // template instantiation. 522 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 523 << RD; 524 } else { 525 // This is not a situation that we should recover from. 526 return ParsedType(); 527 } 528 529 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 530 531 // Build type location information. We synthesized the qualifier, so we have 532 // to build a fake NestedNameSpecifierLoc. 533 NestedNameSpecifierLocBuilder NNSLocBuilder; 534 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 535 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 536 537 TypeLocBuilder Builder; 538 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 539 DepTL.setNameLoc(NameLoc); 540 DepTL.setElaboratedKeywordLoc(SourceLocation()); 541 DepTL.setQualifierLoc(QualifierLoc); 542 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 543 } 544 545 /// isTagName() - This method is called *for error recovery purposes only* 546 /// to determine if the specified name is a valid tag name ("struct foo"). If 547 /// so, this returns the TST for the tag corresponding to it (TST_enum, 548 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 549 /// cases in C where the user forgot to specify the tag. 550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 551 // Do a tag name lookup in this scope. 552 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 553 LookupName(R, S, false); 554 R.suppressDiagnostics(); 555 if (R.getResultKind() == LookupResult::Found) 556 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 557 switch (TD->getTagKind()) { 558 case TTK_Struct: return DeclSpec::TST_struct; 559 case TTK_Interface: return DeclSpec::TST_interface; 560 case TTK_Union: return DeclSpec::TST_union; 561 case TTK_Class: return DeclSpec::TST_class; 562 case TTK_Enum: return DeclSpec::TST_enum; 563 } 564 } 565 566 return DeclSpec::TST_unspecified; 567 } 568 569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 571 /// then downgrade the missing typename error to a warning. 572 /// This is needed for MSVC compatibility; Example: 573 /// @code 574 /// template<class T> class A { 575 /// public: 576 /// typedef int TYPE; 577 /// }; 578 /// template<class T> class B : public A<T> { 579 /// public: 580 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 581 /// }; 582 /// @endcode 583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 584 if (CurContext->isRecord()) { 585 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 586 return true; 587 588 const Type *Ty = SS->getScopeRep()->getAsType(); 589 590 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 591 for (const auto &Base : RD->bases()) 592 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 593 return true; 594 return S->isFunctionPrototypeScope(); 595 } 596 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 597 } 598 599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 600 SourceLocation IILoc, 601 Scope *S, 602 CXXScopeSpec *SS, 603 ParsedType &SuggestedType, 604 bool AllowClassTemplates) { 605 // We don't have anything to suggest (yet). 606 SuggestedType = nullptr; 607 608 // There may have been a typo in the name of the type. Look up typo 609 // results, in case we have something that we can suggest. 610 if (TypoCorrection Corrected = 611 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 612 llvm::make_unique<TypeNameValidatorCCC>( 613 false, false, AllowClassTemplates), 614 CTK_ErrorRecovery)) { 615 if (Corrected.isKeyword()) { 616 // We corrected to a keyword. 617 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 618 II = Corrected.getCorrectionAsIdentifierInfo(); 619 } else { 620 // We found a similarly-named type or interface; suggest that. 621 if (!SS || !SS->isSet()) { 622 diagnoseTypo(Corrected, 623 PDiag(diag::err_unknown_typename_suggest) << II); 624 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 625 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 626 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 627 II->getName().equals(CorrectedStr); 628 diagnoseTypo(Corrected, 629 PDiag(diag::err_unknown_nested_typename_suggest) 630 << II << DC << DroppedSpecifier << SS->getRange()); 631 } else { 632 llvm_unreachable("could not have corrected a typo here"); 633 } 634 635 CXXScopeSpec tmpSS; 636 if (Corrected.getCorrectionSpecifier()) 637 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 638 SourceRange(IILoc)); 639 SuggestedType = 640 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 641 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 642 /*IsCtorOrDtorName=*/false, 643 /*NonTrivialTypeSourceInfo=*/true); 644 } 645 return; 646 } 647 648 if (getLangOpts().CPlusPlus) { 649 // See if II is a class template that the user forgot to pass arguments to. 650 UnqualifiedId Name; 651 Name.setIdentifier(II, IILoc); 652 CXXScopeSpec EmptySS; 653 TemplateTy TemplateResult; 654 bool MemberOfUnknownSpecialization; 655 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 656 Name, nullptr, true, TemplateResult, 657 MemberOfUnknownSpecialization) == TNK_Type_template) { 658 TemplateName TplName = TemplateResult.get(); 659 Diag(IILoc, diag::err_template_missing_args) << TplName; 660 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 661 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 662 << TplDecl->getTemplateParameters()->getSourceRange(); 663 } 664 return; 665 } 666 } 667 668 // FIXME: Should we move the logic that tries to recover from a missing tag 669 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 670 671 if (!SS || (!SS->isSet() && !SS->isInvalid())) 672 Diag(IILoc, diag::err_unknown_typename) << II; 673 else if (DeclContext *DC = computeDeclContext(*SS, false)) 674 Diag(IILoc, diag::err_typename_nested_not_found) 675 << II << DC << SS->getRange(); 676 else if (isDependentScopeSpecifier(*SS)) { 677 unsigned DiagID = diag::err_typename_missing; 678 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 679 DiagID = diag::ext_typename_missing; 680 681 Diag(SS->getRange().getBegin(), DiagID) 682 << SS->getScopeRep() << II->getName() 683 << SourceRange(SS->getRange().getBegin(), IILoc) 684 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 685 SuggestedType = ActOnTypenameType(S, SourceLocation(), 686 *SS, *II, IILoc).get(); 687 } else { 688 assert(SS && SS->isInvalid() && 689 "Invalid scope specifier has already been diagnosed"); 690 } 691 } 692 693 /// \brief Determine whether the given result set contains either a type name 694 /// or 695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 696 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 697 NextToken.is(tok::less); 698 699 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 700 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 701 return true; 702 703 if (CheckTemplate && isa<TemplateDecl>(*I)) 704 return true; 705 } 706 707 return false; 708 } 709 710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 711 Scope *S, CXXScopeSpec &SS, 712 IdentifierInfo *&Name, 713 SourceLocation NameLoc) { 714 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 715 SemaRef.LookupParsedName(R, S, &SS); 716 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 717 StringRef FixItTagName; 718 switch (Tag->getTagKind()) { 719 case TTK_Class: 720 FixItTagName = "class "; 721 break; 722 723 case TTK_Enum: 724 FixItTagName = "enum "; 725 break; 726 727 case TTK_Struct: 728 FixItTagName = "struct "; 729 break; 730 731 case TTK_Interface: 732 FixItTagName = "__interface "; 733 break; 734 735 case TTK_Union: 736 FixItTagName = "union "; 737 break; 738 } 739 740 StringRef TagName = FixItTagName.drop_back(); 741 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 742 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 743 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 744 745 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 746 I != IEnd; ++I) 747 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 748 << Name << TagName; 749 750 // Replace lookup results with just the tag decl. 751 Result.clear(Sema::LookupTagName); 752 SemaRef.LookupParsedName(Result, S, &SS); 753 return true; 754 } 755 756 return false; 757 } 758 759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 761 QualType T, SourceLocation NameLoc) { 762 ASTContext &Context = S.Context; 763 764 TypeLocBuilder Builder; 765 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 766 767 T = S.getElaboratedType(ETK_None, SS, T); 768 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 769 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 770 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 771 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 772 } 773 774 Sema::NameClassification 775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 776 SourceLocation NameLoc, const Token &NextToken, 777 bool IsAddressOfOperand, 778 std::unique_ptr<CorrectionCandidateCallback> CCC) { 779 DeclarationNameInfo NameInfo(Name, NameLoc); 780 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 781 782 if (NextToken.is(tok::coloncolon)) { 783 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 784 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 785 } 786 787 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 788 LookupParsedName(Result, S, &SS, !CurMethod); 789 790 // For unqualified lookup in a class template in MSVC mode, look into 791 // dependent base classes where the primary class template is known. 792 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 793 if (ParsedType TypeInBase = 794 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 795 return TypeInBase; 796 } 797 798 // Perform lookup for Objective-C instance variables (including automatically 799 // synthesized instance variables), if we're in an Objective-C method. 800 // FIXME: This lookup really, really needs to be folded in to the normal 801 // unqualified lookup mechanism. 802 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 803 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 804 if (E.get() || E.isInvalid()) 805 return E; 806 } 807 808 bool SecondTry = false; 809 bool IsFilteredTemplateName = false; 810 811 Corrected: 812 switch (Result.getResultKind()) { 813 case LookupResult::NotFound: 814 // If an unqualified-id is followed by a '(', then we have a function 815 // call. 816 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 817 // In C++, this is an ADL-only call. 818 // FIXME: Reference? 819 if (getLangOpts().CPlusPlus) 820 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 821 822 // C90 6.3.2.2: 823 // If the expression that precedes the parenthesized argument list in a 824 // function call consists solely of an identifier, and if no 825 // declaration is visible for this identifier, the identifier is 826 // implicitly declared exactly as if, in the innermost block containing 827 // the function call, the declaration 828 // 829 // extern int identifier (); 830 // 831 // appeared. 832 // 833 // We also allow this in C99 as an extension. 834 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 835 Result.addDecl(D); 836 Result.resolveKind(); 837 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 838 } 839 } 840 841 // In C, we first see whether there is a tag type by the same name, in 842 // which case it's likely that the user just forgot to write "enum", 843 // "struct", or "union". 844 if (!getLangOpts().CPlusPlus && !SecondTry && 845 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 846 break; 847 } 848 849 // Perform typo correction to determine if there is another name that is 850 // close to this name. 851 if (!SecondTry && CCC) { 852 SecondTry = true; 853 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 854 Result.getLookupKind(), S, 855 &SS, std::move(CCC), 856 CTK_ErrorRecovery)) { 857 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 858 unsigned QualifiedDiag = diag::err_no_member_suggest; 859 860 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 861 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 862 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 863 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 864 UnqualifiedDiag = diag::err_no_template_suggest; 865 QualifiedDiag = diag::err_no_member_template_suggest; 866 } else if (UnderlyingFirstDecl && 867 (isa<TypeDecl>(UnderlyingFirstDecl) || 868 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 869 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 870 UnqualifiedDiag = diag::err_unknown_typename_suggest; 871 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 872 } 873 874 if (SS.isEmpty()) { 875 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 876 } else {// FIXME: is this even reachable? Test it. 877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 878 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 879 Name->getName().equals(CorrectedStr); 880 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 881 << Name << computeDeclContext(SS, false) 882 << DroppedSpecifier << SS.getRange()); 883 } 884 885 // Update the name, so that the caller has the new name. 886 Name = Corrected.getCorrectionAsIdentifierInfo(); 887 888 // Typo correction corrected to a keyword. 889 if (Corrected.isKeyword()) 890 return Name; 891 892 // Also update the LookupResult... 893 // FIXME: This should probably go away at some point 894 Result.clear(); 895 Result.setLookupName(Corrected.getCorrection()); 896 if (FirstDecl) 897 Result.addDecl(FirstDecl); 898 899 // If we found an Objective-C instance variable, let 900 // LookupInObjCMethod build the appropriate expression to 901 // reference the ivar. 902 // FIXME: This is a gross hack. 903 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 904 Result.clear(); 905 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 906 return E; 907 } 908 909 goto Corrected; 910 } 911 } 912 913 // We failed to correct; just fall through and let the parser deal with it. 914 Result.suppressDiagnostics(); 915 return NameClassification::Unknown(); 916 917 case LookupResult::NotFoundInCurrentInstantiation: { 918 // We performed name lookup into the current instantiation, and there were 919 // dependent bases, so we treat this result the same way as any other 920 // dependent nested-name-specifier. 921 922 // C++ [temp.res]p2: 923 // A name used in a template declaration or definition and that is 924 // dependent on a template-parameter is assumed not to name a type 925 // unless the applicable name lookup finds a type name or the name is 926 // qualified by the keyword typename. 927 // 928 // FIXME: If the next token is '<', we might want to ask the parser to 929 // perform some heroics to see if we actually have a 930 // template-argument-list, which would indicate a missing 'template' 931 // keyword here. 932 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 933 NameInfo, IsAddressOfOperand, 934 /*TemplateArgs=*/nullptr); 935 } 936 937 case LookupResult::Found: 938 case LookupResult::FoundOverloaded: 939 case LookupResult::FoundUnresolvedValue: 940 break; 941 942 case LookupResult::Ambiguous: 943 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 944 hasAnyAcceptableTemplateNames(Result)) { 945 // C++ [temp.local]p3: 946 // A lookup that finds an injected-class-name (10.2) can result in an 947 // ambiguity in certain cases (for example, if it is found in more than 948 // one base class). If all of the injected-class-names that are found 949 // refer to specializations of the same class template, and if the name 950 // is followed by a template-argument-list, the reference refers to the 951 // class template itself and not a specialization thereof, and is not 952 // ambiguous. 953 // 954 // This filtering can make an ambiguous result into an unambiguous one, 955 // so try again after filtering out template names. 956 FilterAcceptableTemplateNames(Result); 957 if (!Result.isAmbiguous()) { 958 IsFilteredTemplateName = true; 959 break; 960 } 961 } 962 963 // Diagnose the ambiguity and return an error. 964 return NameClassification::Error(); 965 } 966 967 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 968 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 969 // C++ [temp.names]p3: 970 // After name lookup (3.4) finds that a name is a template-name or that 971 // an operator-function-id or a literal- operator-id refers to a set of 972 // overloaded functions any member of which is a function template if 973 // this is followed by a <, the < is always taken as the delimiter of a 974 // template-argument-list and never as the less-than operator. 975 if (!IsFilteredTemplateName) 976 FilterAcceptableTemplateNames(Result); 977 978 if (!Result.empty()) { 979 bool IsFunctionTemplate; 980 bool IsVarTemplate; 981 TemplateName Template; 982 if (Result.end() - Result.begin() > 1) { 983 IsFunctionTemplate = true; 984 Template = Context.getOverloadedTemplateName(Result.begin(), 985 Result.end()); 986 } else { 987 TemplateDecl *TD 988 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 989 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 990 IsVarTemplate = isa<VarTemplateDecl>(TD); 991 992 if (SS.isSet() && !SS.isInvalid()) 993 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 994 /*TemplateKeyword=*/false, 995 TD); 996 else 997 Template = TemplateName(TD); 998 } 999 1000 if (IsFunctionTemplate) { 1001 // Function templates always go through overload resolution, at which 1002 // point we'll perform the various checks (e.g., accessibility) we need 1003 // to based on which function we selected. 1004 Result.suppressDiagnostics(); 1005 1006 return NameClassification::FunctionTemplate(Template); 1007 } 1008 1009 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1010 : NameClassification::TypeTemplate(Template); 1011 } 1012 } 1013 1014 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1015 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1018 QualType T = Context.getTypeDeclType(Type); 1019 if (SS.isNotEmpty()) 1020 return buildNestedType(*this, SS, T, NameLoc); 1021 return ParsedType::make(T); 1022 } 1023 1024 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1025 if (!Class) { 1026 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1027 if (ObjCCompatibleAliasDecl *Alias = 1028 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1029 Class = Alias->getClassInterface(); 1030 } 1031 1032 if (Class) { 1033 DiagnoseUseOfDecl(Class, NameLoc); 1034 1035 if (NextToken.is(tok::period)) { 1036 // Interface. <something> is parsed as a property reference expression. 1037 // Just return "unknown" as a fall-through for now. 1038 Result.suppressDiagnostics(); 1039 return NameClassification::Unknown(); 1040 } 1041 1042 QualType T = Context.getObjCInterfaceType(Class); 1043 return ParsedType::make(T); 1044 } 1045 1046 // We can have a type template here if we're classifying a template argument. 1047 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1048 return NameClassification::TypeTemplate( 1049 TemplateName(cast<TemplateDecl>(FirstDecl))); 1050 1051 // Check for a tag type hidden by a non-type decl in a few cases where it 1052 // seems likely a type is wanted instead of the non-type that was found. 1053 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1054 if ((NextToken.is(tok::identifier) || 1055 (NextIsOp && 1056 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1057 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1058 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1059 DiagnoseUseOfDecl(Type, NameLoc); 1060 QualType T = Context.getTypeDeclType(Type); 1061 if (SS.isNotEmpty()) 1062 return buildNestedType(*this, SS, T, NameLoc); 1063 return ParsedType::make(T); 1064 } 1065 1066 if (FirstDecl->isCXXClassMember()) 1067 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1068 nullptr, S); 1069 1070 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1071 return BuildDeclarationNameExpr(SS, Result, ADL); 1072 } 1073 1074 // Determines the context to return to after temporarily entering a 1075 // context. This depends in an unnecessarily complicated way on the 1076 // exact ordering of callbacks from the parser. 1077 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1078 1079 // Functions defined inline within classes aren't parsed until we've 1080 // finished parsing the top-level class, so the top-level class is 1081 // the context we'll need to return to. 1082 // A Lambda call operator whose parent is a class must not be treated 1083 // as an inline member function. A Lambda can be used legally 1084 // either as an in-class member initializer or a default argument. These 1085 // are parsed once the class has been marked complete and so the containing 1086 // context would be the nested class (when the lambda is defined in one); 1087 // If the class is not complete, then the lambda is being used in an 1088 // ill-formed fashion (such as to specify the width of a bit-field, or 1089 // in an array-bound) - in which case we still want to return the 1090 // lexically containing DC (which could be a nested class). 1091 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1092 DC = DC->getLexicalParent(); 1093 1094 // A function not defined within a class will always return to its 1095 // lexical context. 1096 if (!isa<CXXRecordDecl>(DC)) 1097 return DC; 1098 1099 // A C++ inline method/friend is parsed *after* the topmost class 1100 // it was declared in is fully parsed ("complete"); the topmost 1101 // class is the context we need to return to. 1102 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1103 DC = RD; 1104 1105 // Return the declaration context of the topmost class the inline method is 1106 // declared in. 1107 return DC; 1108 } 1109 1110 return DC->getLexicalParent(); 1111 } 1112 1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1114 assert(getContainingDC(DC) == CurContext && 1115 "The next DeclContext should be lexically contained in the current one."); 1116 CurContext = DC; 1117 S->setEntity(DC); 1118 } 1119 1120 void Sema::PopDeclContext() { 1121 assert(CurContext && "DeclContext imbalance!"); 1122 1123 CurContext = getContainingDC(CurContext); 1124 assert(CurContext && "Popped translation unit!"); 1125 } 1126 1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1128 Decl *D) { 1129 // Unlike PushDeclContext, the context to which we return is not necessarily 1130 // the containing DC of TD, because the new context will be some pre-existing 1131 // TagDecl definition instead of a fresh one. 1132 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1133 CurContext = cast<TagDecl>(D)->getDefinition(); 1134 assert(CurContext && "skipping definition of undefined tag"); 1135 // Start lookups from the parent of the current context; we don't want to look 1136 // into the pre-existing complete definition. 1137 S->setEntity(CurContext->getLookupParent()); 1138 return Result; 1139 } 1140 1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1142 CurContext = static_cast<decltype(CurContext)>(Context); 1143 } 1144 1145 /// EnterDeclaratorContext - Used when we must lookup names in the context 1146 /// of a declarator's nested name specifier. 1147 /// 1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1149 // C++0x [basic.lookup.unqual]p13: 1150 // A name used in the definition of a static data member of class 1151 // X (after the qualified-id of the static member) is looked up as 1152 // if the name was used in a member function of X. 1153 // C++0x [basic.lookup.unqual]p14: 1154 // If a variable member of a namespace is defined outside of the 1155 // scope of its namespace then any name used in the definition of 1156 // the variable member (after the declarator-id) is looked up as 1157 // if the definition of the variable member occurred in its 1158 // namespace. 1159 // Both of these imply that we should push a scope whose context 1160 // is the semantic context of the declaration. We can't use 1161 // PushDeclContext here because that context is not necessarily 1162 // lexically contained in the current context. Fortunately, 1163 // the containing scope should have the appropriate information. 1164 1165 assert(!S->getEntity() && "scope already has entity"); 1166 1167 #ifndef NDEBUG 1168 Scope *Ancestor = S->getParent(); 1169 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1170 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1171 #endif 1172 1173 CurContext = DC; 1174 S->setEntity(DC); 1175 } 1176 1177 void Sema::ExitDeclaratorContext(Scope *S) { 1178 assert(S->getEntity() == CurContext && "Context imbalance!"); 1179 1180 // Switch back to the lexical context. The safety of this is 1181 // enforced by an assert in EnterDeclaratorContext. 1182 Scope *Ancestor = S->getParent(); 1183 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1184 CurContext = Ancestor->getEntity(); 1185 1186 // We don't need to do anything with the scope, which is going to 1187 // disappear. 1188 } 1189 1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1191 // We assume that the caller has already called 1192 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1193 FunctionDecl *FD = D->getAsFunction(); 1194 if (!FD) 1195 return; 1196 1197 // Same implementation as PushDeclContext, but enters the context 1198 // from the lexical parent, rather than the top-level class. 1199 assert(CurContext == FD->getLexicalParent() && 1200 "The next DeclContext should be lexically contained in the current one."); 1201 CurContext = FD; 1202 S->setEntity(CurContext); 1203 1204 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1205 ParmVarDecl *Param = FD->getParamDecl(P); 1206 // If the parameter has an identifier, then add it to the scope 1207 if (Param->getIdentifier()) { 1208 S->AddDecl(Param); 1209 IdResolver.AddDecl(Param); 1210 } 1211 } 1212 } 1213 1214 void Sema::ActOnExitFunctionContext() { 1215 // Same implementation as PopDeclContext, but returns to the lexical parent, 1216 // rather than the top-level class. 1217 assert(CurContext && "DeclContext imbalance!"); 1218 CurContext = CurContext->getLexicalParent(); 1219 assert(CurContext && "Popped translation unit!"); 1220 } 1221 1222 /// \brief Determine whether we allow overloading of the function 1223 /// PrevDecl with another declaration. 1224 /// 1225 /// This routine determines whether overloading is possible, not 1226 /// whether some new function is actually an overload. It will return 1227 /// true in C++ (where we can always provide overloads) or, as an 1228 /// extension, in C when the previous function is already an 1229 /// overloaded function declaration or has the "overloadable" 1230 /// attribute. 1231 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1232 ASTContext &Context) { 1233 if (Context.getLangOpts().CPlusPlus) 1234 return true; 1235 1236 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1237 return true; 1238 1239 return (Previous.getResultKind() == LookupResult::Found 1240 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1241 } 1242 1243 /// Add this decl to the scope shadowed decl chains. 1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1245 // Move up the scope chain until we find the nearest enclosing 1246 // non-transparent context. The declaration will be introduced into this 1247 // scope. 1248 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1249 S = S->getParent(); 1250 1251 // Add scoped declarations into their context, so that they can be 1252 // found later. Declarations without a context won't be inserted 1253 // into any context. 1254 if (AddToContext) 1255 CurContext->addDecl(D); 1256 1257 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1258 // are function-local declarations. 1259 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1260 !D->getDeclContext()->getRedeclContext()->Equals( 1261 D->getLexicalDeclContext()->getRedeclContext()) && 1262 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1263 return; 1264 1265 // Template instantiations should also not be pushed into scope. 1266 if (isa<FunctionDecl>(D) && 1267 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1268 return; 1269 1270 // If this replaces anything in the current scope, 1271 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1272 IEnd = IdResolver.end(); 1273 for (; I != IEnd; ++I) { 1274 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1275 S->RemoveDecl(*I); 1276 IdResolver.RemoveDecl(*I); 1277 1278 // Should only need to replace one decl. 1279 break; 1280 } 1281 } 1282 1283 S->AddDecl(D); 1284 1285 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1286 // Implicitly-generated labels may end up getting generated in an order that 1287 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1288 // the label at the appropriate place in the identifier chain. 1289 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1290 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1291 if (IDC == CurContext) { 1292 if (!S->isDeclScope(*I)) 1293 continue; 1294 } else if (IDC->Encloses(CurContext)) 1295 break; 1296 } 1297 1298 IdResolver.InsertDeclAfter(I, D); 1299 } else { 1300 IdResolver.AddDecl(D); 1301 } 1302 } 1303 1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1305 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1306 TUScope->AddDecl(D); 1307 } 1308 1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1310 bool AllowInlineNamespace) { 1311 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1312 } 1313 1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1315 DeclContext *TargetDC = DC->getPrimaryContext(); 1316 do { 1317 if (DeclContext *ScopeDC = S->getEntity()) 1318 if (ScopeDC->getPrimaryContext() == TargetDC) 1319 return S; 1320 } while ((S = S->getParent())); 1321 1322 return nullptr; 1323 } 1324 1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1326 DeclContext*, 1327 ASTContext&); 1328 1329 /// Filters out lookup results that don't fall within the given scope 1330 /// as determined by isDeclInScope. 1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1332 bool ConsiderLinkage, 1333 bool AllowInlineNamespace) { 1334 LookupResult::Filter F = R.makeFilter(); 1335 while (F.hasNext()) { 1336 NamedDecl *D = F.next(); 1337 1338 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1339 continue; 1340 1341 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1342 continue; 1343 1344 F.erase(); 1345 } 1346 1347 F.done(); 1348 } 1349 1350 static bool isUsingDecl(NamedDecl *D) { 1351 return isa<UsingShadowDecl>(D) || 1352 isa<UnresolvedUsingTypenameDecl>(D) || 1353 isa<UnresolvedUsingValueDecl>(D); 1354 } 1355 1356 /// Removes using shadow declarations from the lookup results. 1357 static void RemoveUsingDecls(LookupResult &R) { 1358 LookupResult::Filter F = R.makeFilter(); 1359 while (F.hasNext()) 1360 if (isUsingDecl(F.next())) 1361 F.erase(); 1362 1363 F.done(); 1364 } 1365 1366 /// \brief Check for this common pattern: 1367 /// @code 1368 /// class S { 1369 /// S(const S&); // DO NOT IMPLEMENT 1370 /// void operator=(const S&); // DO NOT IMPLEMENT 1371 /// }; 1372 /// @endcode 1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1374 // FIXME: Should check for private access too but access is set after we get 1375 // the decl here. 1376 if (D->doesThisDeclarationHaveABody()) 1377 return false; 1378 1379 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1380 return CD->isCopyConstructor(); 1381 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1382 return Method->isCopyAssignmentOperator(); 1383 return false; 1384 } 1385 1386 // We need this to handle 1387 // 1388 // typedef struct { 1389 // void *foo() { return 0; } 1390 // } A; 1391 // 1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1393 // for example. If 'A', foo will have external linkage. If we have '*A', 1394 // foo will have no linkage. Since we can't know until we get to the end 1395 // of the typedef, this function finds out if D might have non-external linkage. 1396 // Callers should verify at the end of the TU if it D has external linkage or 1397 // not. 1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1399 const DeclContext *DC = D->getDeclContext(); 1400 while (!DC->isTranslationUnit()) { 1401 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1402 if (!RD->hasNameForLinkage()) 1403 return true; 1404 } 1405 DC = DC->getParent(); 1406 } 1407 1408 return !D->isExternallyVisible(); 1409 } 1410 1411 // FIXME: This needs to be refactored; some other isInMainFile users want 1412 // these semantics. 1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1414 if (S.TUKind != TU_Complete) 1415 return false; 1416 return S.SourceMgr.isInMainFile(Loc); 1417 } 1418 1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1420 assert(D); 1421 1422 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1423 return false; 1424 1425 // Ignore all entities declared within templates, and out-of-line definitions 1426 // of members of class templates. 1427 if (D->getDeclContext()->isDependentContext() || 1428 D->getLexicalDeclContext()->isDependentContext()) 1429 return false; 1430 1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1432 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1433 return false; 1434 1435 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1436 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1437 return false; 1438 } else { 1439 // 'static inline' functions are defined in headers; don't warn. 1440 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1441 return false; 1442 } 1443 1444 if (FD->doesThisDeclarationHaveABody() && 1445 Context.DeclMustBeEmitted(FD)) 1446 return false; 1447 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1448 // Constants and utility variables are defined in headers with internal 1449 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1450 // like "inline".) 1451 if (!isMainFileLoc(*this, VD->getLocation())) 1452 return false; 1453 1454 if (Context.DeclMustBeEmitted(VD)) 1455 return false; 1456 1457 if (VD->isStaticDataMember() && 1458 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1459 return false; 1460 1461 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1462 return false; 1463 } else { 1464 return false; 1465 } 1466 1467 // Only warn for unused decls internal to the translation unit. 1468 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1469 // for inline functions defined in the main source file, for instance. 1470 return mightHaveNonExternalLinkage(D); 1471 } 1472 1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1474 if (!D) 1475 return; 1476 1477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1478 const FunctionDecl *First = FD->getFirstDecl(); 1479 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1480 return; // First should already be in the vector. 1481 } 1482 1483 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1484 const VarDecl *First = VD->getFirstDecl(); 1485 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1486 return; // First should already be in the vector. 1487 } 1488 1489 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1490 UnusedFileScopedDecls.push_back(D); 1491 } 1492 1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1494 if (D->isInvalidDecl()) 1495 return false; 1496 1497 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1498 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1499 return false; 1500 1501 if (isa<LabelDecl>(D)) 1502 return true; 1503 1504 // Except for labels, we only care about unused decls that are local to 1505 // functions. 1506 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1507 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1508 // For dependent types, the diagnostic is deferred. 1509 WithinFunction = 1510 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1511 if (!WithinFunction) 1512 return false; 1513 1514 if (isa<TypedefNameDecl>(D)) 1515 return true; 1516 1517 // White-list anything that isn't a local variable. 1518 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1519 return false; 1520 1521 // Types of valid local variables should be complete, so this should succeed. 1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1523 1524 // White-list anything with an __attribute__((unused)) type. 1525 QualType Ty = VD->getType(); 1526 1527 // Only look at the outermost level of typedef. 1528 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1529 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1530 return false; 1531 } 1532 1533 // If we failed to complete the type for some reason, or if the type is 1534 // dependent, don't diagnose the variable. 1535 if (Ty->isIncompleteType() || Ty->isDependentType()) 1536 return false; 1537 1538 if (const TagType *TT = Ty->getAs<TagType>()) { 1539 const TagDecl *Tag = TT->getDecl(); 1540 if (Tag->hasAttr<UnusedAttr>()) 1541 return false; 1542 1543 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1544 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1545 return false; 1546 1547 if (const Expr *Init = VD->getInit()) { 1548 if (const ExprWithCleanups *Cleanups = 1549 dyn_cast<ExprWithCleanups>(Init)) 1550 Init = Cleanups->getSubExpr(); 1551 const CXXConstructExpr *Construct = 1552 dyn_cast<CXXConstructExpr>(Init); 1553 if (Construct && !Construct->isElidable()) { 1554 CXXConstructorDecl *CD = Construct->getConstructor(); 1555 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1556 return false; 1557 } 1558 } 1559 } 1560 } 1561 1562 // TODO: __attribute__((unused)) templates? 1563 } 1564 1565 return true; 1566 } 1567 1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1569 FixItHint &Hint) { 1570 if (isa<LabelDecl>(D)) { 1571 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1572 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1573 if (AfterColon.isInvalid()) 1574 return; 1575 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1576 getCharRange(D->getLocStart(), AfterColon)); 1577 } 1578 } 1579 1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1581 if (D->getTypeForDecl()->isDependentType()) 1582 return; 1583 1584 for (auto *TmpD : D->decls()) { 1585 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1586 DiagnoseUnusedDecl(T); 1587 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1588 DiagnoseUnusedNestedTypedefs(R); 1589 } 1590 } 1591 1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1593 /// unless they are marked attr(unused). 1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1595 if (!ShouldDiagnoseUnusedDecl(D)) 1596 return; 1597 1598 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1599 // typedefs can be referenced later on, so the diagnostics are emitted 1600 // at end-of-translation-unit. 1601 UnusedLocalTypedefNameCandidates.insert(TD); 1602 return; 1603 } 1604 1605 FixItHint Hint; 1606 GenerateFixForUnusedDecl(D, Context, Hint); 1607 1608 unsigned DiagID; 1609 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1610 DiagID = diag::warn_unused_exception_param; 1611 else if (isa<LabelDecl>(D)) 1612 DiagID = diag::warn_unused_label; 1613 else 1614 DiagID = diag::warn_unused_variable; 1615 1616 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1617 } 1618 1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1620 // Verify that we have no forward references left. If so, there was a goto 1621 // or address of a label taken, but no definition of it. Label fwd 1622 // definitions are indicated with a null substmt which is also not a resolved 1623 // MS inline assembly label name. 1624 bool Diagnose = false; 1625 if (L->isMSAsmLabel()) 1626 Diagnose = !L->isResolvedMSAsmLabel(); 1627 else 1628 Diagnose = L->getStmt() == nullptr; 1629 if (Diagnose) 1630 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1631 } 1632 1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1634 S->mergeNRVOIntoParent(); 1635 1636 if (S->decl_empty()) return; 1637 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1638 "Scope shouldn't contain decls!"); 1639 1640 for (auto *TmpD : S->decls()) { 1641 assert(TmpD && "This decl didn't get pushed??"); 1642 1643 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1644 NamedDecl *D = cast<NamedDecl>(TmpD); 1645 1646 if (!D->getDeclName()) continue; 1647 1648 // Diagnose unused variables in this scope. 1649 if (!S->hasUnrecoverableErrorOccurred()) { 1650 DiagnoseUnusedDecl(D); 1651 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1652 DiagnoseUnusedNestedTypedefs(RD); 1653 } 1654 1655 // If this was a forward reference to a label, verify it was defined. 1656 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1657 CheckPoppedLabel(LD, *this); 1658 1659 // Remove this name from our lexical scope, and warn on it if we haven't 1660 // already. 1661 IdResolver.RemoveDecl(D); 1662 auto ShadowI = ShadowingDecls.find(D); 1663 if (ShadowI != ShadowingDecls.end()) { 1664 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1665 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1666 << D << FD << FD->getParent(); 1667 Diag(FD->getLocation(), diag::note_previous_declaration); 1668 } 1669 ShadowingDecls.erase(ShadowI); 1670 } 1671 } 1672 } 1673 1674 /// \brief Look for an Objective-C class in the translation unit. 1675 /// 1676 /// \param Id The name of the Objective-C class we're looking for. If 1677 /// typo-correction fixes this name, the Id will be updated 1678 /// to the fixed name. 1679 /// 1680 /// \param IdLoc The location of the name in the translation unit. 1681 /// 1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1683 /// if there is no class with the given name. 1684 /// 1685 /// \returns The declaration of the named Objective-C class, or NULL if the 1686 /// class could not be found. 1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1688 SourceLocation IdLoc, 1689 bool DoTypoCorrection) { 1690 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1691 // creation from this context. 1692 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1693 1694 if (!IDecl && DoTypoCorrection) { 1695 // Perform typo correction at the given location, but only if we 1696 // find an Objective-C class name. 1697 if (TypoCorrection C = CorrectTypo( 1698 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1699 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1700 CTK_ErrorRecovery)) { 1701 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1702 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1703 Id = IDecl->getIdentifier(); 1704 } 1705 } 1706 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1707 // This routine must always return a class definition, if any. 1708 if (Def && Def->getDefinition()) 1709 Def = Def->getDefinition(); 1710 return Def; 1711 } 1712 1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1714 /// from S, where a non-field would be declared. This routine copes 1715 /// with the difference between C and C++ scoping rules in structs and 1716 /// unions. For example, the following code is well-formed in C but 1717 /// ill-formed in C++: 1718 /// @code 1719 /// struct S6 { 1720 /// enum { BAR } e; 1721 /// }; 1722 /// 1723 /// void test_S6() { 1724 /// struct S6 a; 1725 /// a.e = BAR; 1726 /// } 1727 /// @endcode 1728 /// For the declaration of BAR, this routine will return a different 1729 /// scope. The scope S will be the scope of the unnamed enumeration 1730 /// within S6. In C++, this routine will return the scope associated 1731 /// with S6, because the enumeration's scope is a transparent 1732 /// context but structures can contain non-field names. In C, this 1733 /// routine will return the translation unit scope, since the 1734 /// enumeration's scope is a transparent context and structures cannot 1735 /// contain non-field names. 1736 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1737 while (((S->getFlags() & Scope::DeclScope) == 0) || 1738 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1739 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1740 S = S->getParent(); 1741 return S; 1742 } 1743 1744 /// \brief Looks up the declaration of "struct objc_super" and 1745 /// saves it for later use in building builtin declaration of 1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1747 /// pre-existing declaration exists no action takes place. 1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1749 IdentifierInfo *II) { 1750 if (!II->isStr("objc_msgSendSuper")) 1751 return; 1752 ASTContext &Context = ThisSema.Context; 1753 1754 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1755 SourceLocation(), Sema::LookupTagName); 1756 ThisSema.LookupName(Result, S); 1757 if (Result.getResultKind() == LookupResult::Found) 1758 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1759 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1760 } 1761 1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1763 switch (Error) { 1764 case ASTContext::GE_None: 1765 return ""; 1766 case ASTContext::GE_Missing_stdio: 1767 return "stdio.h"; 1768 case ASTContext::GE_Missing_setjmp: 1769 return "setjmp.h"; 1770 case ASTContext::GE_Missing_ucontext: 1771 return "ucontext.h"; 1772 } 1773 llvm_unreachable("unhandled error kind"); 1774 } 1775 1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1777 /// file scope. lazily create a decl for it. ForRedeclaration is true 1778 /// if we're creating this built-in in anticipation of redeclaring the 1779 /// built-in. 1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1781 Scope *S, bool ForRedeclaration, 1782 SourceLocation Loc) { 1783 LookupPredefedObjCSuperType(*this, S, II); 1784 1785 ASTContext::GetBuiltinTypeError Error; 1786 QualType R = Context.GetBuiltinType(ID, Error); 1787 if (Error) { 1788 if (ForRedeclaration) 1789 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1790 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1791 return nullptr; 1792 } 1793 1794 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1795 Diag(Loc, diag::ext_implicit_lib_function_decl) 1796 << Context.BuiltinInfo.getName(ID) << R; 1797 if (Context.BuiltinInfo.getHeaderName(ID) && 1798 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1799 Diag(Loc, diag::note_include_header_or_declare) 1800 << Context.BuiltinInfo.getHeaderName(ID) 1801 << Context.BuiltinInfo.getName(ID); 1802 } 1803 1804 if (R.isNull()) 1805 return nullptr; 1806 1807 DeclContext *Parent = Context.getTranslationUnitDecl(); 1808 if (getLangOpts().CPlusPlus) { 1809 LinkageSpecDecl *CLinkageDecl = 1810 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1811 LinkageSpecDecl::lang_c, false); 1812 CLinkageDecl->setImplicit(); 1813 Parent->addDecl(CLinkageDecl); 1814 Parent = CLinkageDecl; 1815 } 1816 1817 FunctionDecl *New = FunctionDecl::Create(Context, 1818 Parent, 1819 Loc, Loc, II, R, /*TInfo=*/nullptr, 1820 SC_Extern, 1821 false, 1822 R->isFunctionProtoType()); 1823 New->setImplicit(); 1824 1825 // Create Decl objects for each parameter, adding them to the 1826 // FunctionDecl. 1827 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1828 SmallVector<ParmVarDecl*, 16> Params; 1829 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1830 ParmVarDecl *parm = 1831 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1832 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1833 SC_None, nullptr); 1834 parm->setScopeInfo(0, i); 1835 Params.push_back(parm); 1836 } 1837 New->setParams(Params); 1838 } 1839 1840 AddKnownFunctionAttributes(New); 1841 RegisterLocallyScopedExternCDecl(New, S); 1842 1843 // TUScope is the translation-unit scope to insert this function into. 1844 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1845 // relate Scopes to DeclContexts, and probably eliminate CurContext 1846 // entirely, but we're not there yet. 1847 DeclContext *SavedContext = CurContext; 1848 CurContext = Parent; 1849 PushOnScopeChains(New, TUScope); 1850 CurContext = SavedContext; 1851 return New; 1852 } 1853 1854 /// Typedef declarations don't have linkage, but they still denote the same 1855 /// entity if their types are the same. 1856 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1857 /// isSameEntity. 1858 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1859 TypedefNameDecl *Decl, 1860 LookupResult &Previous) { 1861 // This is only interesting when modules are enabled. 1862 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1863 return; 1864 1865 // Empty sets are uninteresting. 1866 if (Previous.empty()) 1867 return; 1868 1869 LookupResult::Filter Filter = Previous.makeFilter(); 1870 while (Filter.hasNext()) { 1871 NamedDecl *Old = Filter.next(); 1872 1873 // Non-hidden declarations are never ignored. 1874 if (S.isVisible(Old)) 1875 continue; 1876 1877 // Declarations of the same entity are not ignored, even if they have 1878 // different linkages. 1879 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1880 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1881 Decl->getUnderlyingType())) 1882 continue; 1883 1884 // If both declarations give a tag declaration a typedef name for linkage 1885 // purposes, then they declare the same entity. 1886 if (S.getLangOpts().CPlusPlus && 1887 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1888 Decl->getAnonDeclWithTypedefName()) 1889 continue; 1890 } 1891 1892 Filter.erase(); 1893 } 1894 1895 Filter.done(); 1896 } 1897 1898 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1899 QualType OldType; 1900 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1901 OldType = OldTypedef->getUnderlyingType(); 1902 else 1903 OldType = Context.getTypeDeclType(Old); 1904 QualType NewType = New->getUnderlyingType(); 1905 1906 if (NewType->isVariablyModifiedType()) { 1907 // Must not redefine a typedef with a variably-modified type. 1908 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1909 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1910 << Kind << NewType; 1911 if (Old->getLocation().isValid()) 1912 Diag(Old->getLocation(), diag::note_previous_definition); 1913 New->setInvalidDecl(); 1914 return true; 1915 } 1916 1917 if (OldType != NewType && 1918 !OldType->isDependentType() && 1919 !NewType->isDependentType() && 1920 !Context.hasSameType(OldType, NewType)) { 1921 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1922 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1923 << Kind << NewType << OldType; 1924 if (Old->getLocation().isValid()) 1925 Diag(Old->getLocation(), diag::note_previous_definition); 1926 New->setInvalidDecl(); 1927 return true; 1928 } 1929 return false; 1930 } 1931 1932 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1933 /// same name and scope as a previous declaration 'Old'. Figure out 1934 /// how to resolve this situation, merging decls or emitting 1935 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1936 /// 1937 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1938 LookupResult &OldDecls) { 1939 // If the new decl is known invalid already, don't bother doing any 1940 // merging checks. 1941 if (New->isInvalidDecl()) return; 1942 1943 // Allow multiple definitions for ObjC built-in typedefs. 1944 // FIXME: Verify the underlying types are equivalent! 1945 if (getLangOpts().ObjC1) { 1946 const IdentifierInfo *TypeID = New->getIdentifier(); 1947 switch (TypeID->getLength()) { 1948 default: break; 1949 case 2: 1950 { 1951 if (!TypeID->isStr("id")) 1952 break; 1953 QualType T = New->getUnderlyingType(); 1954 if (!T->isPointerType()) 1955 break; 1956 if (!T->isVoidPointerType()) { 1957 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1958 if (!PT->isStructureType()) 1959 break; 1960 } 1961 Context.setObjCIdRedefinitionType(T); 1962 // Install the built-in type for 'id', ignoring the current definition. 1963 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1964 return; 1965 } 1966 case 5: 1967 if (!TypeID->isStr("Class")) 1968 break; 1969 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1970 // Install the built-in type for 'Class', ignoring the current definition. 1971 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1972 return; 1973 case 3: 1974 if (!TypeID->isStr("SEL")) 1975 break; 1976 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1977 // Install the built-in type for 'SEL', ignoring the current definition. 1978 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1979 return; 1980 } 1981 // Fall through - the typedef name was not a builtin type. 1982 } 1983 1984 // Verify the old decl was also a type. 1985 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1986 if (!Old) { 1987 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1988 << New->getDeclName(); 1989 1990 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1991 if (OldD->getLocation().isValid()) 1992 Diag(OldD->getLocation(), diag::note_previous_definition); 1993 1994 return New->setInvalidDecl(); 1995 } 1996 1997 // If the old declaration is invalid, just give up here. 1998 if (Old->isInvalidDecl()) 1999 return New->setInvalidDecl(); 2000 2001 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2002 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2003 auto *NewTag = New->getAnonDeclWithTypedefName(); 2004 NamedDecl *Hidden = nullptr; 2005 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2006 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2007 !hasVisibleDefinition(OldTag, &Hidden)) { 2008 // There is a definition of this tag, but it is not visible. Use it 2009 // instead of our tag. 2010 New->setTypeForDecl(OldTD->getTypeForDecl()); 2011 if (OldTD->isModed()) 2012 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2013 OldTD->getUnderlyingType()); 2014 else 2015 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2016 2017 // Make the old tag definition visible. 2018 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2019 2020 // If this was an unscoped enumeration, yank all of its enumerators 2021 // out of the scope. 2022 if (isa<EnumDecl>(NewTag)) { 2023 Scope *EnumScope = getNonFieldDeclScope(S); 2024 for (auto *D : NewTag->decls()) { 2025 auto *ED = cast<EnumConstantDecl>(D); 2026 assert(EnumScope->isDeclScope(ED)); 2027 EnumScope->RemoveDecl(ED); 2028 IdResolver.RemoveDecl(ED); 2029 ED->getLexicalDeclContext()->removeDecl(ED); 2030 } 2031 } 2032 } 2033 } 2034 2035 // If the typedef types are not identical, reject them in all languages and 2036 // with any extensions enabled. 2037 if (isIncompatibleTypedef(Old, New)) 2038 return; 2039 2040 // The types match. Link up the redeclaration chain and merge attributes if 2041 // the old declaration was a typedef. 2042 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2043 New->setPreviousDecl(Typedef); 2044 mergeDeclAttributes(New, Old); 2045 } 2046 2047 if (getLangOpts().MicrosoftExt) 2048 return; 2049 2050 if (getLangOpts().CPlusPlus) { 2051 // C++ [dcl.typedef]p2: 2052 // In a given non-class scope, a typedef specifier can be used to 2053 // redefine the name of any type declared in that scope to refer 2054 // to the type to which it already refers. 2055 if (!isa<CXXRecordDecl>(CurContext)) 2056 return; 2057 2058 // C++0x [dcl.typedef]p4: 2059 // In a given class scope, a typedef specifier can be used to redefine 2060 // any class-name declared in that scope that is not also a typedef-name 2061 // to refer to the type to which it already refers. 2062 // 2063 // This wording came in via DR424, which was a correction to the 2064 // wording in DR56, which accidentally banned code like: 2065 // 2066 // struct S { 2067 // typedef struct A { } A; 2068 // }; 2069 // 2070 // in the C++03 standard. We implement the C++0x semantics, which 2071 // allow the above but disallow 2072 // 2073 // struct S { 2074 // typedef int I; 2075 // typedef int I; 2076 // }; 2077 // 2078 // since that was the intent of DR56. 2079 if (!isa<TypedefNameDecl>(Old)) 2080 return; 2081 2082 Diag(New->getLocation(), diag::err_redefinition) 2083 << New->getDeclName(); 2084 Diag(Old->getLocation(), diag::note_previous_definition); 2085 return New->setInvalidDecl(); 2086 } 2087 2088 // Modules always permit redefinition of typedefs, as does C11. 2089 if (getLangOpts().Modules || getLangOpts().C11) 2090 return; 2091 2092 // If we have a redefinition of a typedef in C, emit a warning. This warning 2093 // is normally mapped to an error, but can be controlled with 2094 // -Wtypedef-redefinition. If either the original or the redefinition is 2095 // in a system header, don't emit this for compatibility with GCC. 2096 if (getDiagnostics().getSuppressSystemWarnings() && 2097 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2098 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2099 return; 2100 2101 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2102 << New->getDeclName(); 2103 Diag(Old->getLocation(), diag::note_previous_definition); 2104 } 2105 2106 /// DeclhasAttr - returns true if decl Declaration already has the target 2107 /// attribute. 2108 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2109 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2110 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2111 for (const auto *i : D->attrs()) 2112 if (i->getKind() == A->getKind()) { 2113 if (Ann) { 2114 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2115 return true; 2116 continue; 2117 } 2118 // FIXME: Don't hardcode this check 2119 if (OA && isa<OwnershipAttr>(i)) 2120 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2121 return true; 2122 } 2123 2124 return false; 2125 } 2126 2127 static bool isAttributeTargetADefinition(Decl *D) { 2128 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2129 return VD->isThisDeclarationADefinition(); 2130 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2131 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2132 return true; 2133 } 2134 2135 /// Merge alignment attributes from \p Old to \p New, taking into account the 2136 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2137 /// 2138 /// \return \c true if any attributes were added to \p New. 2139 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2140 // Look for alignas attributes on Old, and pick out whichever attribute 2141 // specifies the strictest alignment requirement. 2142 AlignedAttr *OldAlignasAttr = nullptr; 2143 AlignedAttr *OldStrictestAlignAttr = nullptr; 2144 unsigned OldAlign = 0; 2145 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2146 // FIXME: We have no way of representing inherited dependent alignments 2147 // in a case like: 2148 // template<int A, int B> struct alignas(A) X; 2149 // template<int A, int B> struct alignas(B) X {}; 2150 // For now, we just ignore any alignas attributes which are not on the 2151 // definition in such a case. 2152 if (I->isAlignmentDependent()) 2153 return false; 2154 2155 if (I->isAlignas()) 2156 OldAlignasAttr = I; 2157 2158 unsigned Align = I->getAlignment(S.Context); 2159 if (Align > OldAlign) { 2160 OldAlign = Align; 2161 OldStrictestAlignAttr = I; 2162 } 2163 } 2164 2165 // Look for alignas attributes on New. 2166 AlignedAttr *NewAlignasAttr = nullptr; 2167 unsigned NewAlign = 0; 2168 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2169 if (I->isAlignmentDependent()) 2170 return false; 2171 2172 if (I->isAlignas()) 2173 NewAlignasAttr = I; 2174 2175 unsigned Align = I->getAlignment(S.Context); 2176 if (Align > NewAlign) 2177 NewAlign = Align; 2178 } 2179 2180 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2181 // Both declarations have 'alignas' attributes. We require them to match. 2182 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2183 // fall short. (If two declarations both have alignas, they must both match 2184 // every definition, and so must match each other if there is a definition.) 2185 2186 // If either declaration only contains 'alignas(0)' specifiers, then it 2187 // specifies the natural alignment for the type. 2188 if (OldAlign == 0 || NewAlign == 0) { 2189 QualType Ty; 2190 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2191 Ty = VD->getType(); 2192 else 2193 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2194 2195 if (OldAlign == 0) 2196 OldAlign = S.Context.getTypeAlign(Ty); 2197 if (NewAlign == 0) 2198 NewAlign = S.Context.getTypeAlign(Ty); 2199 } 2200 2201 if (OldAlign != NewAlign) { 2202 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2203 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2204 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2205 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2206 } 2207 } 2208 2209 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2210 // C++11 [dcl.align]p6: 2211 // if any declaration of an entity has an alignment-specifier, 2212 // every defining declaration of that entity shall specify an 2213 // equivalent alignment. 2214 // C11 6.7.5/7: 2215 // If the definition of an object does not have an alignment 2216 // specifier, any other declaration of that object shall also 2217 // have no alignment specifier. 2218 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2219 << OldAlignasAttr; 2220 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2221 << OldAlignasAttr; 2222 } 2223 2224 bool AnyAdded = false; 2225 2226 // Ensure we have an attribute representing the strictest alignment. 2227 if (OldAlign > NewAlign) { 2228 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2229 Clone->setInherited(true); 2230 New->addAttr(Clone); 2231 AnyAdded = true; 2232 } 2233 2234 // Ensure we have an alignas attribute if the old declaration had one. 2235 if (OldAlignasAttr && !NewAlignasAttr && 2236 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2237 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2238 Clone->setInherited(true); 2239 New->addAttr(Clone); 2240 AnyAdded = true; 2241 } 2242 2243 return AnyAdded; 2244 } 2245 2246 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2247 const InheritableAttr *Attr, 2248 Sema::AvailabilityMergeKind AMK) { 2249 // This function copies an attribute Attr from a previous declaration to the 2250 // new declaration D if the new declaration doesn't itself have that attribute 2251 // yet or if that attribute allows duplicates. 2252 // If you're adding a new attribute that requires logic different from 2253 // "use explicit attribute on decl if present, else use attribute from 2254 // previous decl", for example if the attribute needs to be consistent 2255 // between redeclarations, you need to call a custom merge function here. 2256 InheritableAttr *NewAttr = nullptr; 2257 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2258 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2259 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2260 AA->isImplicit(), AA->getIntroduced(), 2261 AA->getDeprecated(), 2262 AA->getObsoleted(), AA->getUnavailable(), 2263 AA->getMessage(), AA->getStrict(), 2264 AA->getReplacement(), AMK, 2265 AttrSpellingListIndex); 2266 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2267 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2268 AttrSpellingListIndex); 2269 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2270 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2271 AttrSpellingListIndex); 2272 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2273 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2274 AttrSpellingListIndex); 2275 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2276 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2277 AttrSpellingListIndex); 2278 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2279 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2280 FA->getFormatIdx(), FA->getFirstArg(), 2281 AttrSpellingListIndex); 2282 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2283 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2284 AttrSpellingListIndex); 2285 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2286 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2287 AttrSpellingListIndex, 2288 IA->getSemanticSpelling()); 2289 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2290 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2291 &S.Context.Idents.get(AA->getSpelling()), 2292 AttrSpellingListIndex); 2293 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2294 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2295 isa<CUDAGlobalAttr>(Attr))) { 2296 // CUDA target attributes are part of function signature for 2297 // overloading purposes and must not be merged. 2298 return false; 2299 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2300 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2301 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2302 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2303 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2304 NewAttr = S.mergeInternalLinkageAttr( 2305 D, InternalLinkageA->getRange(), 2306 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2307 AttrSpellingListIndex); 2308 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2309 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2310 &S.Context.Idents.get(CommonA->getSpelling()), 2311 AttrSpellingListIndex); 2312 else if (isa<AlignedAttr>(Attr)) 2313 // AlignedAttrs are handled separately, because we need to handle all 2314 // such attributes on a declaration at the same time. 2315 NewAttr = nullptr; 2316 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2317 (AMK == Sema::AMK_Override || 2318 AMK == Sema::AMK_ProtocolImplementation)) 2319 NewAttr = nullptr; 2320 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2321 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2322 UA->getGuid()); 2323 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2324 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2325 2326 if (NewAttr) { 2327 NewAttr->setInherited(true); 2328 D->addAttr(NewAttr); 2329 if (isa<MSInheritanceAttr>(NewAttr)) 2330 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2331 return true; 2332 } 2333 2334 return false; 2335 } 2336 2337 static const Decl *getDefinition(const Decl *D) { 2338 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2339 return TD->getDefinition(); 2340 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2341 const VarDecl *Def = VD->getDefinition(); 2342 if (Def) 2343 return Def; 2344 return VD->getActingDefinition(); 2345 } 2346 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2347 return FD->getDefinition(); 2348 return nullptr; 2349 } 2350 2351 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2352 for (const auto *Attribute : D->attrs()) 2353 if (Attribute->getKind() == Kind) 2354 return true; 2355 return false; 2356 } 2357 2358 /// checkNewAttributesAfterDef - If we already have a definition, check that 2359 /// there are no new attributes in this declaration. 2360 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2361 if (!New->hasAttrs()) 2362 return; 2363 2364 const Decl *Def = getDefinition(Old); 2365 if (!Def || Def == New) 2366 return; 2367 2368 AttrVec &NewAttributes = New->getAttrs(); 2369 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2370 const Attr *NewAttribute = NewAttributes[I]; 2371 2372 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2374 Sema::SkipBodyInfo SkipBody; 2375 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2376 2377 // If we're skipping this definition, drop the "alias" attribute. 2378 if (SkipBody.ShouldSkip) { 2379 NewAttributes.erase(NewAttributes.begin() + I); 2380 --E; 2381 continue; 2382 } 2383 } else { 2384 VarDecl *VD = cast<VarDecl>(New); 2385 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2386 VarDecl::TentativeDefinition 2387 ? diag::err_alias_after_tentative 2388 : diag::err_redefinition; 2389 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2390 S.Diag(Def->getLocation(), diag::note_previous_definition); 2391 VD->setInvalidDecl(); 2392 } 2393 ++I; 2394 continue; 2395 } 2396 2397 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2398 // Tentative definitions are only interesting for the alias check above. 2399 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2400 ++I; 2401 continue; 2402 } 2403 } 2404 2405 if (hasAttribute(Def, NewAttribute->getKind())) { 2406 ++I; 2407 continue; // regular attr merging will take care of validating this. 2408 } 2409 2410 if (isa<C11NoReturnAttr>(NewAttribute)) { 2411 // C's _Noreturn is allowed to be added to a function after it is defined. 2412 ++I; 2413 continue; 2414 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2415 if (AA->isAlignas()) { 2416 // C++11 [dcl.align]p6: 2417 // if any declaration of an entity has an alignment-specifier, 2418 // every defining declaration of that entity shall specify an 2419 // equivalent alignment. 2420 // C11 6.7.5/7: 2421 // If the definition of an object does not have an alignment 2422 // specifier, any other declaration of that object shall also 2423 // have no alignment specifier. 2424 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2425 << AA; 2426 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2427 << AA; 2428 NewAttributes.erase(NewAttributes.begin() + I); 2429 --E; 2430 continue; 2431 } 2432 } 2433 2434 S.Diag(NewAttribute->getLocation(), 2435 diag::warn_attribute_precede_definition); 2436 S.Diag(Def->getLocation(), diag::note_previous_definition); 2437 NewAttributes.erase(NewAttributes.begin() + I); 2438 --E; 2439 } 2440 } 2441 2442 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2443 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2444 AvailabilityMergeKind AMK) { 2445 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2446 UsedAttr *NewAttr = OldAttr->clone(Context); 2447 NewAttr->setInherited(true); 2448 New->addAttr(NewAttr); 2449 } 2450 2451 if (!Old->hasAttrs() && !New->hasAttrs()) 2452 return; 2453 2454 // Attributes declared post-definition are currently ignored. 2455 checkNewAttributesAfterDef(*this, New, Old); 2456 2457 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2458 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2459 if (OldA->getLabel() != NewA->getLabel()) { 2460 // This redeclaration changes __asm__ label. 2461 Diag(New->getLocation(), diag::err_different_asm_label); 2462 Diag(OldA->getLocation(), diag::note_previous_declaration); 2463 } 2464 } else if (Old->isUsed()) { 2465 // This redeclaration adds an __asm__ label to a declaration that has 2466 // already been ODR-used. 2467 Diag(New->getLocation(), diag::err_late_asm_label_name) 2468 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2469 } 2470 } 2471 2472 // Re-declaration cannot add abi_tag's. 2473 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2474 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2475 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2476 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2477 NewTag) == OldAbiTagAttr->tags_end()) { 2478 Diag(NewAbiTagAttr->getLocation(), 2479 diag::err_new_abi_tag_on_redeclaration) 2480 << NewTag; 2481 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2482 } 2483 } 2484 } else { 2485 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2486 Diag(Old->getLocation(), diag::note_previous_declaration); 2487 } 2488 } 2489 2490 if (!Old->hasAttrs()) 2491 return; 2492 2493 bool foundAny = New->hasAttrs(); 2494 2495 // Ensure that any moving of objects within the allocated map is done before 2496 // we process them. 2497 if (!foundAny) New->setAttrs(AttrVec()); 2498 2499 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2500 // Ignore deprecated/unavailable/availability attributes if requested. 2501 AvailabilityMergeKind LocalAMK = AMK_None; 2502 if (isa<DeprecatedAttr>(I) || 2503 isa<UnavailableAttr>(I) || 2504 isa<AvailabilityAttr>(I)) { 2505 switch (AMK) { 2506 case AMK_None: 2507 continue; 2508 2509 case AMK_Redeclaration: 2510 case AMK_Override: 2511 case AMK_ProtocolImplementation: 2512 LocalAMK = AMK; 2513 break; 2514 } 2515 } 2516 2517 // Already handled. 2518 if (isa<UsedAttr>(I)) 2519 continue; 2520 2521 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2522 foundAny = true; 2523 } 2524 2525 if (mergeAlignedAttrs(*this, New, Old)) 2526 foundAny = true; 2527 2528 if (!foundAny) New->dropAttrs(); 2529 } 2530 2531 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2532 /// to the new one. 2533 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2534 const ParmVarDecl *oldDecl, 2535 Sema &S) { 2536 // C++11 [dcl.attr.depend]p2: 2537 // The first declaration of a function shall specify the 2538 // carries_dependency attribute for its declarator-id if any declaration 2539 // of the function specifies the carries_dependency attribute. 2540 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2541 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2542 S.Diag(CDA->getLocation(), 2543 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2544 // Find the first declaration of the parameter. 2545 // FIXME: Should we build redeclaration chains for function parameters? 2546 const FunctionDecl *FirstFD = 2547 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2548 const ParmVarDecl *FirstVD = 2549 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2550 S.Diag(FirstVD->getLocation(), 2551 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2552 } 2553 2554 if (!oldDecl->hasAttrs()) 2555 return; 2556 2557 bool foundAny = newDecl->hasAttrs(); 2558 2559 // Ensure that any moving of objects within the allocated map is 2560 // done before we process them. 2561 if (!foundAny) newDecl->setAttrs(AttrVec()); 2562 2563 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2564 if (!DeclHasAttr(newDecl, I)) { 2565 InheritableAttr *newAttr = 2566 cast<InheritableParamAttr>(I->clone(S.Context)); 2567 newAttr->setInherited(true); 2568 newDecl->addAttr(newAttr); 2569 foundAny = true; 2570 } 2571 } 2572 2573 if (!foundAny) newDecl->dropAttrs(); 2574 } 2575 2576 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2577 const ParmVarDecl *OldParam, 2578 Sema &S) { 2579 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2580 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2581 if (*Oldnullability != *Newnullability) { 2582 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2583 << DiagNullabilityKind( 2584 *Newnullability, 2585 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2586 != 0)) 2587 << DiagNullabilityKind( 2588 *Oldnullability, 2589 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2590 != 0)); 2591 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2592 } 2593 } else { 2594 QualType NewT = NewParam->getType(); 2595 NewT = S.Context.getAttributedType( 2596 AttributedType::getNullabilityAttrKind(*Oldnullability), 2597 NewT, NewT); 2598 NewParam->setType(NewT); 2599 } 2600 } 2601 } 2602 2603 namespace { 2604 2605 /// Used in MergeFunctionDecl to keep track of function parameters in 2606 /// C. 2607 struct GNUCompatibleParamWarning { 2608 ParmVarDecl *OldParm; 2609 ParmVarDecl *NewParm; 2610 QualType PromotedType; 2611 }; 2612 2613 } // end anonymous namespace 2614 2615 /// getSpecialMember - get the special member enum for a method. 2616 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2617 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2618 if (Ctor->isDefaultConstructor()) 2619 return Sema::CXXDefaultConstructor; 2620 2621 if (Ctor->isCopyConstructor()) 2622 return Sema::CXXCopyConstructor; 2623 2624 if (Ctor->isMoveConstructor()) 2625 return Sema::CXXMoveConstructor; 2626 } else if (isa<CXXDestructorDecl>(MD)) { 2627 return Sema::CXXDestructor; 2628 } else if (MD->isCopyAssignmentOperator()) { 2629 return Sema::CXXCopyAssignment; 2630 } else if (MD->isMoveAssignmentOperator()) { 2631 return Sema::CXXMoveAssignment; 2632 } 2633 2634 return Sema::CXXInvalid; 2635 } 2636 2637 // Determine whether the previous declaration was a definition, implicit 2638 // declaration, or a declaration. 2639 template <typename T> 2640 static std::pair<diag::kind, SourceLocation> 2641 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2642 diag::kind PrevDiag; 2643 SourceLocation OldLocation = Old->getLocation(); 2644 if (Old->isThisDeclarationADefinition()) 2645 PrevDiag = diag::note_previous_definition; 2646 else if (Old->isImplicit()) { 2647 PrevDiag = diag::note_previous_implicit_declaration; 2648 if (OldLocation.isInvalid()) 2649 OldLocation = New->getLocation(); 2650 } else 2651 PrevDiag = diag::note_previous_declaration; 2652 return std::make_pair(PrevDiag, OldLocation); 2653 } 2654 2655 /// canRedefineFunction - checks if a function can be redefined. Currently, 2656 /// only extern inline functions can be redefined, and even then only in 2657 /// GNU89 mode. 2658 static bool canRedefineFunction(const FunctionDecl *FD, 2659 const LangOptions& LangOpts) { 2660 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2661 !LangOpts.CPlusPlus && 2662 FD->isInlineSpecified() && 2663 FD->getStorageClass() == SC_Extern); 2664 } 2665 2666 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2667 const AttributedType *AT = T->getAs<AttributedType>(); 2668 while (AT && !AT->isCallingConv()) 2669 AT = AT->getModifiedType()->getAs<AttributedType>(); 2670 return AT; 2671 } 2672 2673 template <typename T> 2674 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2675 const DeclContext *DC = Old->getDeclContext(); 2676 if (DC->isRecord()) 2677 return false; 2678 2679 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2680 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2681 return true; 2682 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2683 return true; 2684 return false; 2685 } 2686 2687 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2688 static bool isExternC(VarTemplateDecl *) { return false; } 2689 2690 /// \brief Check whether a redeclaration of an entity introduced by a 2691 /// using-declaration is valid, given that we know it's not an overload 2692 /// (nor a hidden tag declaration). 2693 template<typename ExpectedDecl> 2694 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2695 ExpectedDecl *New) { 2696 // C++11 [basic.scope.declarative]p4: 2697 // Given a set of declarations in a single declarative region, each of 2698 // which specifies the same unqualified name, 2699 // -- they shall all refer to the same entity, or all refer to functions 2700 // and function templates; or 2701 // -- exactly one declaration shall declare a class name or enumeration 2702 // name that is not a typedef name and the other declarations shall all 2703 // refer to the same variable or enumerator, or all refer to functions 2704 // and function templates; in this case the class name or enumeration 2705 // name is hidden (3.3.10). 2706 2707 // C++11 [namespace.udecl]p14: 2708 // If a function declaration in namespace scope or block scope has the 2709 // same name and the same parameter-type-list as a function introduced 2710 // by a using-declaration, and the declarations do not declare the same 2711 // function, the program is ill-formed. 2712 2713 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2714 if (Old && 2715 !Old->getDeclContext()->getRedeclContext()->Equals( 2716 New->getDeclContext()->getRedeclContext()) && 2717 !(isExternC(Old) && isExternC(New))) 2718 Old = nullptr; 2719 2720 if (!Old) { 2721 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2722 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2723 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2724 return true; 2725 } 2726 return false; 2727 } 2728 2729 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2730 const FunctionDecl *B) { 2731 assert(A->getNumParams() == B->getNumParams()); 2732 2733 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2734 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2735 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2736 if (AttrA == AttrB) 2737 return true; 2738 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2739 }; 2740 2741 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2742 } 2743 2744 /// MergeFunctionDecl - We just parsed a function 'New' from 2745 /// declarator D which has the same name and scope as a previous 2746 /// declaration 'Old'. Figure out how to resolve this situation, 2747 /// merging decls or emitting diagnostics as appropriate. 2748 /// 2749 /// In C++, New and Old must be declarations that are not 2750 /// overloaded. Use IsOverload to determine whether New and Old are 2751 /// overloaded, and to select the Old declaration that New should be 2752 /// merged with. 2753 /// 2754 /// Returns true if there was an error, false otherwise. 2755 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2756 Scope *S, bool MergeTypeWithOld) { 2757 // Verify the old decl was also a function. 2758 FunctionDecl *Old = OldD->getAsFunction(); 2759 if (!Old) { 2760 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2761 if (New->getFriendObjectKind()) { 2762 Diag(New->getLocation(), diag::err_using_decl_friend); 2763 Diag(Shadow->getTargetDecl()->getLocation(), 2764 diag::note_using_decl_target); 2765 Diag(Shadow->getUsingDecl()->getLocation(), 2766 diag::note_using_decl) << 0; 2767 return true; 2768 } 2769 2770 // Check whether the two declarations might declare the same function. 2771 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2772 return true; 2773 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2774 } else { 2775 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2776 << New->getDeclName(); 2777 Diag(OldD->getLocation(), diag::note_previous_definition); 2778 return true; 2779 } 2780 } 2781 2782 // If the old declaration is invalid, just give up here. 2783 if (Old->isInvalidDecl()) 2784 return true; 2785 2786 diag::kind PrevDiag; 2787 SourceLocation OldLocation; 2788 std::tie(PrevDiag, OldLocation) = 2789 getNoteDiagForInvalidRedeclaration(Old, New); 2790 2791 // Don't complain about this if we're in GNU89 mode and the old function 2792 // is an extern inline function. 2793 // Don't complain about specializations. They are not supposed to have 2794 // storage classes. 2795 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2796 New->getStorageClass() == SC_Static && 2797 Old->hasExternalFormalLinkage() && 2798 !New->getTemplateSpecializationInfo() && 2799 !canRedefineFunction(Old, getLangOpts())) { 2800 if (getLangOpts().MicrosoftExt) { 2801 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2802 Diag(OldLocation, PrevDiag); 2803 } else { 2804 Diag(New->getLocation(), diag::err_static_non_static) << New; 2805 Diag(OldLocation, PrevDiag); 2806 return true; 2807 } 2808 } 2809 2810 if (New->hasAttr<InternalLinkageAttr>() && 2811 !Old->hasAttr<InternalLinkageAttr>()) { 2812 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2813 << New->getDeclName(); 2814 Diag(Old->getLocation(), diag::note_previous_definition); 2815 New->dropAttr<InternalLinkageAttr>(); 2816 } 2817 2818 // If a function is first declared with a calling convention, but is later 2819 // declared or defined without one, all following decls assume the calling 2820 // convention of the first. 2821 // 2822 // It's OK if a function is first declared without a calling convention, 2823 // but is later declared or defined with the default calling convention. 2824 // 2825 // To test if either decl has an explicit calling convention, we look for 2826 // AttributedType sugar nodes on the type as written. If they are missing or 2827 // were canonicalized away, we assume the calling convention was implicit. 2828 // 2829 // Note also that we DO NOT return at this point, because we still have 2830 // other tests to run. 2831 QualType OldQType = Context.getCanonicalType(Old->getType()); 2832 QualType NewQType = Context.getCanonicalType(New->getType()); 2833 const FunctionType *OldType = cast<FunctionType>(OldQType); 2834 const FunctionType *NewType = cast<FunctionType>(NewQType); 2835 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2836 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2837 bool RequiresAdjustment = false; 2838 2839 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2840 FunctionDecl *First = Old->getFirstDecl(); 2841 const FunctionType *FT = 2842 First->getType().getCanonicalType()->castAs<FunctionType>(); 2843 FunctionType::ExtInfo FI = FT->getExtInfo(); 2844 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2845 if (!NewCCExplicit) { 2846 // Inherit the CC from the previous declaration if it was specified 2847 // there but not here. 2848 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2849 RequiresAdjustment = true; 2850 } else { 2851 // Calling conventions aren't compatible, so complain. 2852 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2853 Diag(New->getLocation(), diag::err_cconv_change) 2854 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2855 << !FirstCCExplicit 2856 << (!FirstCCExplicit ? "" : 2857 FunctionType::getNameForCallConv(FI.getCC())); 2858 2859 // Put the note on the first decl, since it is the one that matters. 2860 Diag(First->getLocation(), diag::note_previous_declaration); 2861 return true; 2862 } 2863 } 2864 2865 // FIXME: diagnose the other way around? 2866 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2867 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2868 RequiresAdjustment = true; 2869 } 2870 2871 // Merge regparm attribute. 2872 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2873 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2874 if (NewTypeInfo.getHasRegParm()) { 2875 Diag(New->getLocation(), diag::err_regparm_mismatch) 2876 << NewType->getRegParmType() 2877 << OldType->getRegParmType(); 2878 Diag(OldLocation, diag::note_previous_declaration); 2879 return true; 2880 } 2881 2882 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2883 RequiresAdjustment = true; 2884 } 2885 2886 // Merge ns_returns_retained attribute. 2887 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2888 if (NewTypeInfo.getProducesResult()) { 2889 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2890 Diag(OldLocation, diag::note_previous_declaration); 2891 return true; 2892 } 2893 2894 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2895 RequiresAdjustment = true; 2896 } 2897 2898 if (RequiresAdjustment) { 2899 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2900 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2901 New->setType(QualType(AdjustedType, 0)); 2902 NewQType = Context.getCanonicalType(New->getType()); 2903 NewType = cast<FunctionType>(NewQType); 2904 } 2905 2906 // If this redeclaration makes the function inline, we may need to add it to 2907 // UndefinedButUsed. 2908 if (!Old->isInlined() && New->isInlined() && 2909 !New->hasAttr<GNUInlineAttr>() && 2910 !getLangOpts().GNUInline && 2911 Old->isUsed(false) && 2912 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2913 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2914 SourceLocation())); 2915 2916 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2917 // about it. 2918 if (New->hasAttr<GNUInlineAttr>() && 2919 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2920 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2921 } 2922 2923 // If pass_object_size params don't match up perfectly, this isn't a valid 2924 // redeclaration. 2925 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2926 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2927 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2928 << New->getDeclName(); 2929 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2930 return true; 2931 } 2932 2933 if (getLangOpts().CPlusPlus) { 2934 // (C++98 13.1p2): 2935 // Certain function declarations cannot be overloaded: 2936 // -- Function declarations that differ only in the return type 2937 // cannot be overloaded. 2938 2939 // Go back to the type source info to compare the declared return types, 2940 // per C++1y [dcl.type.auto]p13: 2941 // Redeclarations or specializations of a function or function template 2942 // with a declared return type that uses a placeholder type shall also 2943 // use that placeholder, not a deduced type. 2944 QualType OldDeclaredReturnType = 2945 (Old->getTypeSourceInfo() 2946 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2947 : OldType)->getReturnType(); 2948 QualType NewDeclaredReturnType = 2949 (New->getTypeSourceInfo() 2950 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2951 : NewType)->getReturnType(); 2952 QualType ResQT; 2953 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2954 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2955 New->isLocalExternDecl())) { 2956 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2957 OldDeclaredReturnType->isObjCObjectPointerType()) 2958 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2959 if (ResQT.isNull()) { 2960 if (New->isCXXClassMember() && New->isOutOfLine()) 2961 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2962 << New << New->getReturnTypeSourceRange(); 2963 else 2964 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2965 << New->getReturnTypeSourceRange(); 2966 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2967 << Old->getReturnTypeSourceRange(); 2968 return true; 2969 } 2970 else 2971 NewQType = ResQT; 2972 } 2973 2974 QualType OldReturnType = OldType->getReturnType(); 2975 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2976 if (OldReturnType != NewReturnType) { 2977 // If this function has a deduced return type and has already been 2978 // defined, copy the deduced value from the old declaration. 2979 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2980 if (OldAT && OldAT->isDeduced()) { 2981 New->setType( 2982 SubstAutoType(New->getType(), 2983 OldAT->isDependentType() ? Context.DependentTy 2984 : OldAT->getDeducedType())); 2985 NewQType = Context.getCanonicalType( 2986 SubstAutoType(NewQType, 2987 OldAT->isDependentType() ? Context.DependentTy 2988 : OldAT->getDeducedType())); 2989 } 2990 } 2991 2992 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2993 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2994 if (OldMethod && NewMethod) { 2995 // Preserve triviality. 2996 NewMethod->setTrivial(OldMethod->isTrivial()); 2997 2998 // MSVC allows explicit template specialization at class scope: 2999 // 2 CXXMethodDecls referring to the same function will be injected. 3000 // We don't want a redeclaration error. 3001 bool IsClassScopeExplicitSpecialization = 3002 OldMethod->isFunctionTemplateSpecialization() && 3003 NewMethod->isFunctionTemplateSpecialization(); 3004 bool isFriend = NewMethod->getFriendObjectKind(); 3005 3006 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3007 !IsClassScopeExplicitSpecialization) { 3008 // -- Member function declarations with the same name and the 3009 // same parameter types cannot be overloaded if any of them 3010 // is a static member function declaration. 3011 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3012 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3013 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3014 return true; 3015 } 3016 3017 // C++ [class.mem]p1: 3018 // [...] A member shall not be declared twice in the 3019 // member-specification, except that a nested class or member 3020 // class template can be declared and then later defined. 3021 if (ActiveTemplateInstantiations.empty()) { 3022 unsigned NewDiag; 3023 if (isa<CXXConstructorDecl>(OldMethod)) 3024 NewDiag = diag::err_constructor_redeclared; 3025 else if (isa<CXXDestructorDecl>(NewMethod)) 3026 NewDiag = diag::err_destructor_redeclared; 3027 else if (isa<CXXConversionDecl>(NewMethod)) 3028 NewDiag = diag::err_conv_function_redeclared; 3029 else 3030 NewDiag = diag::err_member_redeclared; 3031 3032 Diag(New->getLocation(), NewDiag); 3033 } else { 3034 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3035 << New << New->getType(); 3036 } 3037 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3038 return true; 3039 3040 // Complain if this is an explicit declaration of a special 3041 // member that was initially declared implicitly. 3042 // 3043 // As an exception, it's okay to befriend such methods in order 3044 // to permit the implicit constructor/destructor/operator calls. 3045 } else if (OldMethod->isImplicit()) { 3046 if (isFriend) { 3047 NewMethod->setImplicit(); 3048 } else { 3049 Diag(NewMethod->getLocation(), 3050 diag::err_definition_of_implicitly_declared_member) 3051 << New << getSpecialMember(OldMethod); 3052 return true; 3053 } 3054 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3055 Diag(NewMethod->getLocation(), 3056 diag::err_definition_of_explicitly_defaulted_member) 3057 << getSpecialMember(OldMethod); 3058 return true; 3059 } 3060 } 3061 3062 // C++11 [dcl.attr.noreturn]p1: 3063 // The first declaration of a function shall specify the noreturn 3064 // attribute if any declaration of that function specifies the noreturn 3065 // attribute. 3066 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3067 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3068 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3069 Diag(Old->getFirstDecl()->getLocation(), 3070 diag::note_noreturn_missing_first_decl); 3071 } 3072 3073 // C++11 [dcl.attr.depend]p2: 3074 // The first declaration of a function shall specify the 3075 // carries_dependency attribute for its declarator-id if any declaration 3076 // of the function specifies the carries_dependency attribute. 3077 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3078 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3079 Diag(CDA->getLocation(), 3080 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3081 Diag(Old->getFirstDecl()->getLocation(), 3082 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3083 } 3084 3085 // (C++98 8.3.5p3): 3086 // All declarations for a function shall agree exactly in both the 3087 // return type and the parameter-type-list. 3088 // We also want to respect all the extended bits except noreturn. 3089 3090 // noreturn should now match unless the old type info didn't have it. 3091 QualType OldQTypeForComparison = OldQType; 3092 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3093 assert(OldQType == QualType(OldType, 0)); 3094 const FunctionType *OldTypeForComparison 3095 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3096 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3097 assert(OldQTypeForComparison.isCanonical()); 3098 } 3099 3100 if (haveIncompatibleLanguageLinkages(Old, New)) { 3101 // As a special case, retain the language linkage from previous 3102 // declarations of a friend function as an extension. 3103 // 3104 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3105 // and is useful because there's otherwise no way to specify language 3106 // linkage within class scope. 3107 // 3108 // Check cautiously as the friend object kind isn't yet complete. 3109 if (New->getFriendObjectKind() != Decl::FOK_None) { 3110 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3111 Diag(OldLocation, PrevDiag); 3112 } else { 3113 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3114 Diag(OldLocation, PrevDiag); 3115 return true; 3116 } 3117 } 3118 3119 if (OldQTypeForComparison == NewQType) 3120 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3121 3122 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3123 New->isLocalExternDecl()) { 3124 // It's OK if we couldn't merge types for a local function declaraton 3125 // if either the old or new type is dependent. We'll merge the types 3126 // when we instantiate the function. 3127 return false; 3128 } 3129 3130 // Fall through for conflicting redeclarations and redefinitions. 3131 } 3132 3133 // C: Function types need to be compatible, not identical. This handles 3134 // duplicate function decls like "void f(int); void f(enum X);" properly. 3135 if (!getLangOpts().CPlusPlus && 3136 Context.typesAreCompatible(OldQType, NewQType)) { 3137 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3138 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3139 const FunctionProtoType *OldProto = nullptr; 3140 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3141 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3142 // The old declaration provided a function prototype, but the 3143 // new declaration does not. Merge in the prototype. 3144 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3145 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3146 NewQType = 3147 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3148 OldProto->getExtProtoInfo()); 3149 New->setType(NewQType); 3150 New->setHasInheritedPrototype(); 3151 3152 // Synthesize parameters with the same types. 3153 SmallVector<ParmVarDecl*, 16> Params; 3154 for (const auto &ParamType : OldProto->param_types()) { 3155 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3156 SourceLocation(), nullptr, 3157 ParamType, /*TInfo=*/nullptr, 3158 SC_None, nullptr); 3159 Param->setScopeInfo(0, Params.size()); 3160 Param->setImplicit(); 3161 Params.push_back(Param); 3162 } 3163 3164 New->setParams(Params); 3165 } 3166 3167 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3168 } 3169 3170 // GNU C permits a K&R definition to follow a prototype declaration 3171 // if the declared types of the parameters in the K&R definition 3172 // match the types in the prototype declaration, even when the 3173 // promoted types of the parameters from the K&R definition differ 3174 // from the types in the prototype. GCC then keeps the types from 3175 // the prototype. 3176 // 3177 // If a variadic prototype is followed by a non-variadic K&R definition, 3178 // the K&R definition becomes variadic. This is sort of an edge case, but 3179 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3180 // C99 6.9.1p8. 3181 if (!getLangOpts().CPlusPlus && 3182 Old->hasPrototype() && !New->hasPrototype() && 3183 New->getType()->getAs<FunctionProtoType>() && 3184 Old->getNumParams() == New->getNumParams()) { 3185 SmallVector<QualType, 16> ArgTypes; 3186 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3187 const FunctionProtoType *OldProto 3188 = Old->getType()->getAs<FunctionProtoType>(); 3189 const FunctionProtoType *NewProto 3190 = New->getType()->getAs<FunctionProtoType>(); 3191 3192 // Determine whether this is the GNU C extension. 3193 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3194 NewProto->getReturnType()); 3195 bool LooseCompatible = !MergedReturn.isNull(); 3196 for (unsigned Idx = 0, End = Old->getNumParams(); 3197 LooseCompatible && Idx != End; ++Idx) { 3198 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3199 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3200 if (Context.typesAreCompatible(OldParm->getType(), 3201 NewProto->getParamType(Idx))) { 3202 ArgTypes.push_back(NewParm->getType()); 3203 } else if (Context.typesAreCompatible(OldParm->getType(), 3204 NewParm->getType(), 3205 /*CompareUnqualified=*/true)) { 3206 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3207 NewProto->getParamType(Idx) }; 3208 Warnings.push_back(Warn); 3209 ArgTypes.push_back(NewParm->getType()); 3210 } else 3211 LooseCompatible = false; 3212 } 3213 3214 if (LooseCompatible) { 3215 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3216 Diag(Warnings[Warn].NewParm->getLocation(), 3217 diag::ext_param_promoted_not_compatible_with_prototype) 3218 << Warnings[Warn].PromotedType 3219 << Warnings[Warn].OldParm->getType(); 3220 if (Warnings[Warn].OldParm->getLocation().isValid()) 3221 Diag(Warnings[Warn].OldParm->getLocation(), 3222 diag::note_previous_declaration); 3223 } 3224 3225 if (MergeTypeWithOld) 3226 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3227 OldProto->getExtProtoInfo())); 3228 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3229 } 3230 3231 // Fall through to diagnose conflicting types. 3232 } 3233 3234 // A function that has already been declared has been redeclared or 3235 // defined with a different type; show an appropriate diagnostic. 3236 3237 // If the previous declaration was an implicitly-generated builtin 3238 // declaration, then at the very least we should use a specialized note. 3239 unsigned BuiltinID; 3240 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3241 // If it's actually a library-defined builtin function like 'malloc' 3242 // or 'printf', just warn about the incompatible redeclaration. 3243 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3244 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3245 Diag(OldLocation, diag::note_previous_builtin_declaration) 3246 << Old << Old->getType(); 3247 3248 // If this is a global redeclaration, just forget hereafter 3249 // about the "builtin-ness" of the function. 3250 // 3251 // Doing this for local extern declarations is problematic. If 3252 // the builtin declaration remains visible, a second invalid 3253 // local declaration will produce a hard error; if it doesn't 3254 // remain visible, a single bogus local redeclaration (which is 3255 // actually only a warning) could break all the downstream code. 3256 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3257 New->getIdentifier()->revertBuiltin(); 3258 3259 return false; 3260 } 3261 3262 PrevDiag = diag::note_previous_builtin_declaration; 3263 } 3264 3265 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3266 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3267 return true; 3268 } 3269 3270 /// \brief Completes the merge of two function declarations that are 3271 /// known to be compatible. 3272 /// 3273 /// This routine handles the merging of attributes and other 3274 /// properties of function declarations from the old declaration to 3275 /// the new declaration, once we know that New is in fact a 3276 /// redeclaration of Old. 3277 /// 3278 /// \returns false 3279 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3280 Scope *S, bool MergeTypeWithOld) { 3281 // Merge the attributes 3282 mergeDeclAttributes(New, Old); 3283 3284 // Merge "pure" flag. 3285 if (Old->isPure()) 3286 New->setPure(); 3287 3288 // Merge "used" flag. 3289 if (Old->getMostRecentDecl()->isUsed(false)) 3290 New->setIsUsed(); 3291 3292 // Merge attributes from the parameters. These can mismatch with K&R 3293 // declarations. 3294 if (New->getNumParams() == Old->getNumParams()) 3295 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3296 ParmVarDecl *NewParam = New->getParamDecl(i); 3297 ParmVarDecl *OldParam = Old->getParamDecl(i); 3298 mergeParamDeclAttributes(NewParam, OldParam, *this); 3299 mergeParamDeclTypes(NewParam, OldParam, *this); 3300 } 3301 3302 if (getLangOpts().CPlusPlus) 3303 return MergeCXXFunctionDecl(New, Old, S); 3304 3305 // Merge the function types so the we get the composite types for the return 3306 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3307 // was visible. 3308 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3309 if (!Merged.isNull() && MergeTypeWithOld) 3310 New->setType(Merged); 3311 3312 return false; 3313 } 3314 3315 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3316 ObjCMethodDecl *oldMethod) { 3317 // Merge the attributes, including deprecated/unavailable 3318 AvailabilityMergeKind MergeKind = 3319 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3320 ? AMK_ProtocolImplementation 3321 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3322 : AMK_Override; 3323 3324 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3325 3326 // Merge attributes from the parameters. 3327 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3328 oe = oldMethod->param_end(); 3329 for (ObjCMethodDecl::param_iterator 3330 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3331 ni != ne && oi != oe; ++ni, ++oi) 3332 mergeParamDeclAttributes(*ni, *oi, *this); 3333 3334 CheckObjCMethodOverride(newMethod, oldMethod); 3335 } 3336 3337 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3338 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3339 3340 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3341 ? diag::err_redefinition_different_type 3342 : diag::err_redeclaration_different_type) 3343 << New->getDeclName() << New->getType() << Old->getType(); 3344 3345 diag::kind PrevDiag; 3346 SourceLocation OldLocation; 3347 std::tie(PrevDiag, OldLocation) 3348 = getNoteDiagForInvalidRedeclaration(Old, New); 3349 S.Diag(OldLocation, PrevDiag); 3350 New->setInvalidDecl(); 3351 } 3352 3353 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3354 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3355 /// emitting diagnostics as appropriate. 3356 /// 3357 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3358 /// to here in AddInitializerToDecl. We can't check them before the initializer 3359 /// is attached. 3360 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3361 bool MergeTypeWithOld) { 3362 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3363 return; 3364 3365 QualType MergedT; 3366 if (getLangOpts().CPlusPlus) { 3367 if (New->getType()->isUndeducedType()) { 3368 // We don't know what the new type is until the initializer is attached. 3369 return; 3370 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3371 // These could still be something that needs exception specs checked. 3372 return MergeVarDeclExceptionSpecs(New, Old); 3373 } 3374 // C++ [basic.link]p10: 3375 // [...] the types specified by all declarations referring to a given 3376 // object or function shall be identical, except that declarations for an 3377 // array object can specify array types that differ by the presence or 3378 // absence of a major array bound (8.3.4). 3379 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3380 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3381 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3382 3383 // We are merging a variable declaration New into Old. If it has an array 3384 // bound, and that bound differs from Old's bound, we should diagnose the 3385 // mismatch. 3386 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3387 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3388 PrevVD = PrevVD->getPreviousDecl()) { 3389 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3390 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3391 continue; 3392 3393 if (!Context.hasSameType(NewArray, PrevVDTy)) 3394 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3395 } 3396 } 3397 3398 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3399 if (Context.hasSameType(OldArray->getElementType(), 3400 NewArray->getElementType())) 3401 MergedT = New->getType(); 3402 } 3403 // FIXME: Check visibility. New is hidden but has a complete type. If New 3404 // has no array bound, it should not inherit one from Old, if Old is not 3405 // visible. 3406 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3407 if (Context.hasSameType(OldArray->getElementType(), 3408 NewArray->getElementType())) 3409 MergedT = Old->getType(); 3410 } 3411 } 3412 else if (New->getType()->isObjCObjectPointerType() && 3413 Old->getType()->isObjCObjectPointerType()) { 3414 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3415 Old->getType()); 3416 } 3417 } else { 3418 // C 6.2.7p2: 3419 // All declarations that refer to the same object or function shall have 3420 // compatible type. 3421 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3422 } 3423 if (MergedT.isNull()) { 3424 // It's OK if we couldn't merge types if either type is dependent, for a 3425 // block-scope variable. In other cases (static data members of class 3426 // templates, variable templates, ...), we require the types to be 3427 // equivalent. 3428 // FIXME: The C++ standard doesn't say anything about this. 3429 if ((New->getType()->isDependentType() || 3430 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3431 // If the old type was dependent, we can't merge with it, so the new type 3432 // becomes dependent for now. We'll reproduce the original type when we 3433 // instantiate the TypeSourceInfo for the variable. 3434 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3435 New->setType(Context.DependentTy); 3436 return; 3437 } 3438 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3439 } 3440 3441 // Don't actually update the type on the new declaration if the old 3442 // declaration was an extern declaration in a different scope. 3443 if (MergeTypeWithOld) 3444 New->setType(MergedT); 3445 } 3446 3447 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3448 LookupResult &Previous) { 3449 // C11 6.2.7p4: 3450 // For an identifier with internal or external linkage declared 3451 // in a scope in which a prior declaration of that identifier is 3452 // visible, if the prior declaration specifies internal or 3453 // external linkage, the type of the identifier at the later 3454 // declaration becomes the composite type. 3455 // 3456 // If the variable isn't visible, we do not merge with its type. 3457 if (Previous.isShadowed()) 3458 return false; 3459 3460 if (S.getLangOpts().CPlusPlus) { 3461 // C++11 [dcl.array]p3: 3462 // If there is a preceding declaration of the entity in the same 3463 // scope in which the bound was specified, an omitted array bound 3464 // is taken to be the same as in that earlier declaration. 3465 return NewVD->isPreviousDeclInSameBlockScope() || 3466 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3467 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3468 } else { 3469 // If the old declaration was function-local, don't merge with its 3470 // type unless we're in the same function. 3471 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3472 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3473 } 3474 } 3475 3476 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3477 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3478 /// situation, merging decls or emitting diagnostics as appropriate. 3479 /// 3480 /// Tentative definition rules (C99 6.9.2p2) are checked by 3481 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3482 /// definitions here, since the initializer hasn't been attached. 3483 /// 3484 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3485 // If the new decl is already invalid, don't do any other checking. 3486 if (New->isInvalidDecl()) 3487 return; 3488 3489 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3490 return; 3491 3492 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3493 3494 // Verify the old decl was also a variable or variable template. 3495 VarDecl *Old = nullptr; 3496 VarTemplateDecl *OldTemplate = nullptr; 3497 if (Previous.isSingleResult()) { 3498 if (NewTemplate) { 3499 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3500 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3501 3502 if (auto *Shadow = 3503 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3504 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3505 return New->setInvalidDecl(); 3506 } else { 3507 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3508 3509 if (auto *Shadow = 3510 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3511 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3512 return New->setInvalidDecl(); 3513 } 3514 } 3515 if (!Old) { 3516 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3517 << New->getDeclName(); 3518 Diag(Previous.getRepresentativeDecl()->getLocation(), 3519 diag::note_previous_definition); 3520 return New->setInvalidDecl(); 3521 } 3522 3523 // Ensure the template parameters are compatible. 3524 if (NewTemplate && 3525 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3526 OldTemplate->getTemplateParameters(), 3527 /*Complain=*/true, TPL_TemplateMatch)) 3528 return New->setInvalidDecl(); 3529 3530 // C++ [class.mem]p1: 3531 // A member shall not be declared twice in the member-specification [...] 3532 // 3533 // Here, we need only consider static data members. 3534 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3535 Diag(New->getLocation(), diag::err_duplicate_member) 3536 << New->getIdentifier(); 3537 Diag(Old->getLocation(), diag::note_previous_declaration); 3538 New->setInvalidDecl(); 3539 } 3540 3541 mergeDeclAttributes(New, Old); 3542 // Warn if an already-declared variable is made a weak_import in a subsequent 3543 // declaration 3544 if (New->hasAttr<WeakImportAttr>() && 3545 Old->getStorageClass() == SC_None && 3546 !Old->hasAttr<WeakImportAttr>()) { 3547 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3548 Diag(Old->getLocation(), diag::note_previous_definition); 3549 // Remove weak_import attribute on new declaration. 3550 New->dropAttr<WeakImportAttr>(); 3551 } 3552 3553 if (New->hasAttr<InternalLinkageAttr>() && 3554 !Old->hasAttr<InternalLinkageAttr>()) { 3555 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3556 << New->getDeclName(); 3557 Diag(Old->getLocation(), diag::note_previous_definition); 3558 New->dropAttr<InternalLinkageAttr>(); 3559 } 3560 3561 // Merge the types. 3562 VarDecl *MostRecent = Old->getMostRecentDecl(); 3563 if (MostRecent != Old) { 3564 MergeVarDeclTypes(New, MostRecent, 3565 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3566 if (New->isInvalidDecl()) 3567 return; 3568 } 3569 3570 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3571 if (New->isInvalidDecl()) 3572 return; 3573 3574 diag::kind PrevDiag; 3575 SourceLocation OldLocation; 3576 std::tie(PrevDiag, OldLocation) = 3577 getNoteDiagForInvalidRedeclaration(Old, New); 3578 3579 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3580 if (New->getStorageClass() == SC_Static && 3581 !New->isStaticDataMember() && 3582 Old->hasExternalFormalLinkage()) { 3583 if (getLangOpts().MicrosoftExt) { 3584 Diag(New->getLocation(), diag::ext_static_non_static) 3585 << New->getDeclName(); 3586 Diag(OldLocation, PrevDiag); 3587 } else { 3588 Diag(New->getLocation(), diag::err_static_non_static) 3589 << New->getDeclName(); 3590 Diag(OldLocation, PrevDiag); 3591 return New->setInvalidDecl(); 3592 } 3593 } 3594 // C99 6.2.2p4: 3595 // For an identifier declared with the storage-class specifier 3596 // extern in a scope in which a prior declaration of that 3597 // identifier is visible,23) if the prior declaration specifies 3598 // internal or external linkage, the linkage of the identifier at 3599 // the later declaration is the same as the linkage specified at 3600 // the prior declaration. If no prior declaration is visible, or 3601 // if the prior declaration specifies no linkage, then the 3602 // identifier has external linkage. 3603 if (New->hasExternalStorage() && Old->hasLinkage()) 3604 /* Okay */; 3605 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3606 !New->isStaticDataMember() && 3607 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3608 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3609 Diag(OldLocation, PrevDiag); 3610 return New->setInvalidDecl(); 3611 } 3612 3613 // Check if extern is followed by non-extern and vice-versa. 3614 if (New->hasExternalStorage() && 3615 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3616 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3617 Diag(OldLocation, PrevDiag); 3618 return New->setInvalidDecl(); 3619 } 3620 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3621 !New->hasExternalStorage()) { 3622 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3623 Diag(OldLocation, PrevDiag); 3624 return New->setInvalidDecl(); 3625 } 3626 3627 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3628 3629 // FIXME: The test for external storage here seems wrong? We still 3630 // need to check for mismatches. 3631 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3632 // Don't complain about out-of-line definitions of static members. 3633 !(Old->getLexicalDeclContext()->isRecord() && 3634 !New->getLexicalDeclContext()->isRecord())) { 3635 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3636 Diag(OldLocation, PrevDiag); 3637 return New->setInvalidDecl(); 3638 } 3639 3640 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3641 if (VarDecl *Def = Old->getDefinition()) { 3642 // C++1z [dcl.fcn.spec]p4: 3643 // If the definition of a variable appears in a translation unit before 3644 // its first declaration as inline, the program is ill-formed. 3645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3646 Diag(Def->getLocation(), diag::note_previous_definition); 3647 } 3648 } 3649 3650 // If this redeclaration makes the function inline, we may need to add it to 3651 // UndefinedButUsed. 3652 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3653 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3654 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3655 SourceLocation())); 3656 3657 if (New->getTLSKind() != Old->getTLSKind()) { 3658 if (!Old->getTLSKind()) { 3659 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3660 Diag(OldLocation, PrevDiag); 3661 } else if (!New->getTLSKind()) { 3662 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3663 Diag(OldLocation, PrevDiag); 3664 } else { 3665 // Do not allow redeclaration to change the variable between requiring 3666 // static and dynamic initialization. 3667 // FIXME: GCC allows this, but uses the TLS keyword on the first 3668 // declaration to determine the kind. Do we need to be compatible here? 3669 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3670 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3671 Diag(OldLocation, PrevDiag); 3672 } 3673 } 3674 3675 // C++ doesn't have tentative definitions, so go right ahead and check here. 3676 VarDecl *Def; 3677 if (getLangOpts().CPlusPlus && 3678 New->isThisDeclarationADefinition() == VarDecl::Definition && 3679 (Def = Old->getDefinition())) { 3680 NamedDecl *Hidden = nullptr; 3681 if (!hasVisibleDefinition(Def, &Hidden) && 3682 (New->getFormalLinkage() == InternalLinkage || 3683 New->getDescribedVarTemplate() || 3684 New->getNumTemplateParameterLists() || 3685 New->getDeclContext()->isDependentContext())) { 3686 // The previous definition is hidden, and multiple definitions are 3687 // permitted (in separate TUs). Form another definition of it. 3688 } else if (Old->isStaticDataMember() && 3689 Old->getCanonicalDecl()->isInline() && 3690 Old->getCanonicalDecl()->isConstexpr()) { 3691 // This definition won't be a definition any more once it's been merged. 3692 Diag(New->getLocation(), 3693 diag::warn_deprecated_redundant_constexpr_static_def); 3694 } else { 3695 Diag(New->getLocation(), diag::err_redefinition) << New; 3696 Diag(Def->getLocation(), diag::note_previous_definition); 3697 New->setInvalidDecl(); 3698 return; 3699 } 3700 } 3701 3702 if (haveIncompatibleLanguageLinkages(Old, New)) { 3703 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3704 Diag(OldLocation, PrevDiag); 3705 New->setInvalidDecl(); 3706 return; 3707 } 3708 3709 // Merge "used" flag. 3710 if (Old->getMostRecentDecl()->isUsed(false)) 3711 New->setIsUsed(); 3712 3713 // Keep a chain of previous declarations. 3714 New->setPreviousDecl(Old); 3715 if (NewTemplate) 3716 NewTemplate->setPreviousDecl(OldTemplate); 3717 3718 // Inherit access appropriately. 3719 New->setAccess(Old->getAccess()); 3720 if (NewTemplate) 3721 NewTemplate->setAccess(New->getAccess()); 3722 3723 if (Old->isInline()) 3724 New->setImplicitlyInline(); 3725 } 3726 3727 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3728 /// no declarator (e.g. "struct foo;") is parsed. 3729 Decl * 3730 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3731 RecordDecl *&AnonRecord) { 3732 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3733 AnonRecord); 3734 } 3735 3736 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3737 // disambiguate entities defined in different scopes. 3738 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3739 // compatibility. 3740 // We will pick our mangling number depending on which version of MSVC is being 3741 // targeted. 3742 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3743 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3744 ? S->getMSCurManglingNumber() 3745 : S->getMSLastManglingNumber(); 3746 } 3747 3748 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3749 if (!Context.getLangOpts().CPlusPlus) 3750 return; 3751 3752 if (isa<CXXRecordDecl>(Tag->getParent())) { 3753 // If this tag is the direct child of a class, number it if 3754 // it is anonymous. 3755 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3756 return; 3757 MangleNumberingContext &MCtx = 3758 Context.getManglingNumberContext(Tag->getParent()); 3759 Context.setManglingNumber( 3760 Tag, MCtx.getManglingNumber( 3761 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3762 return; 3763 } 3764 3765 // If this tag isn't a direct child of a class, number it if it is local. 3766 Decl *ManglingContextDecl; 3767 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3768 Tag->getDeclContext(), ManglingContextDecl)) { 3769 Context.setManglingNumber( 3770 Tag, MCtx->getManglingNumber( 3771 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3772 } 3773 } 3774 3775 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3776 TypedefNameDecl *NewTD) { 3777 if (TagFromDeclSpec->isInvalidDecl()) 3778 return; 3779 3780 // Do nothing if the tag already has a name for linkage purposes. 3781 if (TagFromDeclSpec->hasNameForLinkage()) 3782 return; 3783 3784 // A well-formed anonymous tag must always be a TUK_Definition. 3785 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3786 3787 // The type must match the tag exactly; no qualifiers allowed. 3788 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3789 Context.getTagDeclType(TagFromDeclSpec))) { 3790 if (getLangOpts().CPlusPlus) 3791 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3792 return; 3793 } 3794 3795 // If we've already computed linkage for the anonymous tag, then 3796 // adding a typedef name for the anonymous decl can change that 3797 // linkage, which might be a serious problem. Diagnose this as 3798 // unsupported and ignore the typedef name. TODO: we should 3799 // pursue this as a language defect and establish a formal rule 3800 // for how to handle it. 3801 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3802 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3803 3804 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3805 tagLoc = getLocForEndOfToken(tagLoc); 3806 3807 llvm::SmallString<40> textToInsert; 3808 textToInsert += ' '; 3809 textToInsert += NewTD->getIdentifier()->getName(); 3810 Diag(tagLoc, diag::note_typedef_changes_linkage) 3811 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3812 return; 3813 } 3814 3815 // Otherwise, set this is the anon-decl typedef for the tag. 3816 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3817 } 3818 3819 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3820 switch (T) { 3821 case DeclSpec::TST_class: 3822 return 0; 3823 case DeclSpec::TST_struct: 3824 return 1; 3825 case DeclSpec::TST_interface: 3826 return 2; 3827 case DeclSpec::TST_union: 3828 return 3; 3829 case DeclSpec::TST_enum: 3830 return 4; 3831 default: 3832 llvm_unreachable("unexpected type specifier"); 3833 } 3834 } 3835 3836 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3837 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3838 /// parameters to cope with template friend declarations. 3839 Decl * 3840 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3841 MultiTemplateParamsArg TemplateParams, 3842 bool IsExplicitInstantiation, 3843 RecordDecl *&AnonRecord) { 3844 Decl *TagD = nullptr; 3845 TagDecl *Tag = nullptr; 3846 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3847 DS.getTypeSpecType() == DeclSpec::TST_struct || 3848 DS.getTypeSpecType() == DeclSpec::TST_interface || 3849 DS.getTypeSpecType() == DeclSpec::TST_union || 3850 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3851 TagD = DS.getRepAsDecl(); 3852 3853 if (!TagD) // We probably had an error 3854 return nullptr; 3855 3856 // Note that the above type specs guarantee that the 3857 // type rep is a Decl, whereas in many of the others 3858 // it's a Type. 3859 if (isa<TagDecl>(TagD)) 3860 Tag = cast<TagDecl>(TagD); 3861 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3862 Tag = CTD->getTemplatedDecl(); 3863 } 3864 3865 if (Tag) { 3866 handleTagNumbering(Tag, S); 3867 Tag->setFreeStanding(); 3868 if (Tag->isInvalidDecl()) 3869 return Tag; 3870 } 3871 3872 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3873 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3874 // or incomplete types shall not be restrict-qualified." 3875 if (TypeQuals & DeclSpec::TQ_restrict) 3876 Diag(DS.getRestrictSpecLoc(), 3877 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3878 << DS.getSourceRange(); 3879 } 3880 3881 if (DS.isInlineSpecified()) 3882 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3883 << getLangOpts().CPlusPlus1z; 3884 3885 if (DS.isConstexprSpecified()) { 3886 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3887 // and definitions of functions and variables. 3888 if (Tag) 3889 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3890 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3891 else 3892 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3893 // Don't emit warnings after this error. 3894 return TagD; 3895 } 3896 3897 if (DS.isConceptSpecified()) { 3898 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3899 // either a function concept and its definition or a variable concept and 3900 // its initializer. 3901 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3902 return TagD; 3903 } 3904 3905 DiagnoseFunctionSpecifiers(DS); 3906 3907 if (DS.isFriendSpecified()) { 3908 // If we're dealing with a decl but not a TagDecl, assume that 3909 // whatever routines created it handled the friendship aspect. 3910 if (TagD && !Tag) 3911 return nullptr; 3912 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3913 } 3914 3915 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3916 bool IsExplicitSpecialization = 3917 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3918 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3919 !IsExplicitInstantiation && !IsExplicitSpecialization && 3920 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3921 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3922 // nested-name-specifier unless it is an explicit instantiation 3923 // or an explicit specialization. 3924 // 3925 // FIXME: We allow class template partial specializations here too, per the 3926 // obvious intent of DR1819. 3927 // 3928 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3929 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3930 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3931 return nullptr; 3932 } 3933 3934 // Track whether this decl-specifier declares anything. 3935 bool DeclaresAnything = true; 3936 3937 // Handle anonymous struct definitions. 3938 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3939 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3940 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3941 if (getLangOpts().CPlusPlus || 3942 Record->getDeclContext()->isRecord()) { 3943 // If CurContext is a DeclContext that can contain statements, 3944 // RecursiveASTVisitor won't visit the decls that 3945 // BuildAnonymousStructOrUnion() will put into CurContext. 3946 // Also store them here so that they can be part of the 3947 // DeclStmt that gets created in this case. 3948 // FIXME: Also return the IndirectFieldDecls created by 3949 // BuildAnonymousStructOr union, for the same reason? 3950 if (CurContext->isFunctionOrMethod()) 3951 AnonRecord = Record; 3952 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3953 Context.getPrintingPolicy()); 3954 } 3955 3956 DeclaresAnything = false; 3957 } 3958 } 3959 3960 // C11 6.7.2.1p2: 3961 // A struct-declaration that does not declare an anonymous structure or 3962 // anonymous union shall contain a struct-declarator-list. 3963 // 3964 // This rule also existed in C89 and C99; the grammar for struct-declaration 3965 // did not permit a struct-declaration without a struct-declarator-list. 3966 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3967 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3968 // Check for Microsoft C extension: anonymous struct/union member. 3969 // Handle 2 kinds of anonymous struct/union: 3970 // struct STRUCT; 3971 // union UNION; 3972 // and 3973 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3974 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3975 if ((Tag && Tag->getDeclName()) || 3976 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3977 RecordDecl *Record = nullptr; 3978 if (Tag) 3979 Record = dyn_cast<RecordDecl>(Tag); 3980 else if (const RecordType *RT = 3981 DS.getRepAsType().get()->getAsStructureType()) 3982 Record = RT->getDecl(); 3983 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3984 Record = UT->getDecl(); 3985 3986 if (Record && getLangOpts().MicrosoftExt) { 3987 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3988 << Record->isUnion() << DS.getSourceRange(); 3989 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3990 } 3991 3992 DeclaresAnything = false; 3993 } 3994 } 3995 3996 // Skip all the checks below if we have a type error. 3997 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3998 (TagD && TagD->isInvalidDecl())) 3999 return TagD; 4000 4001 if (getLangOpts().CPlusPlus && 4002 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4003 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4004 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4005 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4006 DeclaresAnything = false; 4007 4008 if (!DS.isMissingDeclaratorOk()) { 4009 // Customize diagnostic for a typedef missing a name. 4010 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4011 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4012 << DS.getSourceRange(); 4013 else 4014 DeclaresAnything = false; 4015 } 4016 4017 if (DS.isModulePrivateSpecified() && 4018 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4019 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4020 << Tag->getTagKind() 4021 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4022 4023 ActOnDocumentableDecl(TagD); 4024 4025 // C 6.7/2: 4026 // A declaration [...] shall declare at least a declarator [...], a tag, 4027 // or the members of an enumeration. 4028 // C++ [dcl.dcl]p3: 4029 // [If there are no declarators], and except for the declaration of an 4030 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4031 // names into the program, or shall redeclare a name introduced by a 4032 // previous declaration. 4033 if (!DeclaresAnything) { 4034 // In C, we allow this as a (popular) extension / bug. Don't bother 4035 // producing further diagnostics for redundant qualifiers after this. 4036 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4037 return TagD; 4038 } 4039 4040 // C++ [dcl.stc]p1: 4041 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4042 // init-declarator-list of the declaration shall not be empty. 4043 // C++ [dcl.fct.spec]p1: 4044 // If a cv-qualifier appears in a decl-specifier-seq, the 4045 // init-declarator-list of the declaration shall not be empty. 4046 // 4047 // Spurious qualifiers here appear to be valid in C. 4048 unsigned DiagID = diag::warn_standalone_specifier; 4049 if (getLangOpts().CPlusPlus) 4050 DiagID = diag::ext_standalone_specifier; 4051 4052 // Note that a linkage-specification sets a storage class, but 4053 // 'extern "C" struct foo;' is actually valid and not theoretically 4054 // useless. 4055 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4056 if (SCS == DeclSpec::SCS_mutable) 4057 // Since mutable is not a viable storage class specifier in C, there is 4058 // no reason to treat it as an extension. Instead, diagnose as an error. 4059 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4060 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4061 Diag(DS.getStorageClassSpecLoc(), DiagID) 4062 << DeclSpec::getSpecifierName(SCS); 4063 } 4064 4065 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4066 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4067 << DeclSpec::getSpecifierName(TSCS); 4068 if (DS.getTypeQualifiers()) { 4069 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4070 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4071 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4072 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4073 // Restrict is covered above. 4074 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4075 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4076 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4077 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4078 } 4079 4080 // Warn about ignored type attributes, for example: 4081 // __attribute__((aligned)) struct A; 4082 // Attributes should be placed after tag to apply to type declaration. 4083 if (!DS.getAttributes().empty()) { 4084 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4085 if (TypeSpecType == DeclSpec::TST_class || 4086 TypeSpecType == DeclSpec::TST_struct || 4087 TypeSpecType == DeclSpec::TST_interface || 4088 TypeSpecType == DeclSpec::TST_union || 4089 TypeSpecType == DeclSpec::TST_enum) { 4090 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4091 attrs = attrs->getNext()) 4092 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4093 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4094 } 4095 } 4096 4097 return TagD; 4098 } 4099 4100 /// We are trying to inject an anonymous member into the given scope; 4101 /// check if there's an existing declaration that can't be overloaded. 4102 /// 4103 /// \return true if this is a forbidden redeclaration 4104 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4105 Scope *S, 4106 DeclContext *Owner, 4107 DeclarationName Name, 4108 SourceLocation NameLoc, 4109 bool IsUnion) { 4110 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4111 Sema::ForRedeclaration); 4112 if (!SemaRef.LookupName(R, S)) return false; 4113 4114 // Pick a representative declaration. 4115 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4116 assert(PrevDecl && "Expected a non-null Decl"); 4117 4118 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4119 return false; 4120 4121 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4122 << IsUnion << Name; 4123 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4124 4125 return true; 4126 } 4127 4128 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4129 /// anonymous struct or union AnonRecord into the owning context Owner 4130 /// and scope S. This routine will be invoked just after we realize 4131 /// that an unnamed union or struct is actually an anonymous union or 4132 /// struct, e.g., 4133 /// 4134 /// @code 4135 /// union { 4136 /// int i; 4137 /// float f; 4138 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4139 /// // f into the surrounding scope.x 4140 /// @endcode 4141 /// 4142 /// This routine is recursive, injecting the names of nested anonymous 4143 /// structs/unions into the owning context and scope as well. 4144 static bool 4145 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4146 RecordDecl *AnonRecord, AccessSpecifier AS, 4147 SmallVectorImpl<NamedDecl *> &Chaining) { 4148 bool Invalid = false; 4149 4150 // Look every FieldDecl and IndirectFieldDecl with a name. 4151 for (auto *D : AnonRecord->decls()) { 4152 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4153 cast<NamedDecl>(D)->getDeclName()) { 4154 ValueDecl *VD = cast<ValueDecl>(D); 4155 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4156 VD->getLocation(), 4157 AnonRecord->isUnion())) { 4158 // C++ [class.union]p2: 4159 // The names of the members of an anonymous union shall be 4160 // distinct from the names of any other entity in the 4161 // scope in which the anonymous union is declared. 4162 Invalid = true; 4163 } else { 4164 // C++ [class.union]p2: 4165 // For the purpose of name lookup, after the anonymous union 4166 // definition, the members of the anonymous union are 4167 // considered to have been defined in the scope in which the 4168 // anonymous union is declared. 4169 unsigned OldChainingSize = Chaining.size(); 4170 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4171 Chaining.append(IF->chain_begin(), IF->chain_end()); 4172 else 4173 Chaining.push_back(VD); 4174 4175 assert(Chaining.size() >= 2); 4176 NamedDecl **NamedChain = 4177 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4178 for (unsigned i = 0; i < Chaining.size(); i++) 4179 NamedChain[i] = Chaining[i]; 4180 4181 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4182 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4183 VD->getType(), {NamedChain, Chaining.size()}); 4184 4185 for (const auto *Attr : VD->attrs()) 4186 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4187 4188 IndirectField->setAccess(AS); 4189 IndirectField->setImplicit(); 4190 SemaRef.PushOnScopeChains(IndirectField, S); 4191 4192 // That includes picking up the appropriate access specifier. 4193 if (AS != AS_none) IndirectField->setAccess(AS); 4194 4195 Chaining.resize(OldChainingSize); 4196 } 4197 } 4198 } 4199 4200 return Invalid; 4201 } 4202 4203 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4204 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4205 /// illegal input values are mapped to SC_None. 4206 static StorageClass 4207 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4208 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4209 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4210 "Parser allowed 'typedef' as storage class VarDecl."); 4211 switch (StorageClassSpec) { 4212 case DeclSpec::SCS_unspecified: return SC_None; 4213 case DeclSpec::SCS_extern: 4214 if (DS.isExternInLinkageSpec()) 4215 return SC_None; 4216 return SC_Extern; 4217 case DeclSpec::SCS_static: return SC_Static; 4218 case DeclSpec::SCS_auto: return SC_Auto; 4219 case DeclSpec::SCS_register: return SC_Register; 4220 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4221 // Illegal SCSs map to None: error reporting is up to the caller. 4222 case DeclSpec::SCS_mutable: // Fall through. 4223 case DeclSpec::SCS_typedef: return SC_None; 4224 } 4225 llvm_unreachable("unknown storage class specifier"); 4226 } 4227 4228 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4229 assert(Record->hasInClassInitializer()); 4230 4231 for (const auto *I : Record->decls()) { 4232 const auto *FD = dyn_cast<FieldDecl>(I); 4233 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4234 FD = IFD->getAnonField(); 4235 if (FD && FD->hasInClassInitializer()) 4236 return FD->getLocation(); 4237 } 4238 4239 llvm_unreachable("couldn't find in-class initializer"); 4240 } 4241 4242 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4243 SourceLocation DefaultInitLoc) { 4244 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4245 return; 4246 4247 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4248 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4249 } 4250 4251 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4252 CXXRecordDecl *AnonUnion) { 4253 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4254 return; 4255 4256 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4257 } 4258 4259 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4260 /// anonymous structure or union. Anonymous unions are a C++ feature 4261 /// (C++ [class.union]) and a C11 feature; anonymous structures 4262 /// are a C11 feature and GNU C++ extension. 4263 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4264 AccessSpecifier AS, 4265 RecordDecl *Record, 4266 const PrintingPolicy &Policy) { 4267 DeclContext *Owner = Record->getDeclContext(); 4268 4269 // Diagnose whether this anonymous struct/union is an extension. 4270 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4271 Diag(Record->getLocation(), diag::ext_anonymous_union); 4272 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4273 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4274 else if (!Record->isUnion() && !getLangOpts().C11) 4275 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4276 4277 // C and C++ require different kinds of checks for anonymous 4278 // structs/unions. 4279 bool Invalid = false; 4280 if (getLangOpts().CPlusPlus) { 4281 const char *PrevSpec = nullptr; 4282 unsigned DiagID; 4283 if (Record->isUnion()) { 4284 // C++ [class.union]p6: 4285 // Anonymous unions declared in a named namespace or in the 4286 // global namespace shall be declared static. 4287 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4288 (isa<TranslationUnitDecl>(Owner) || 4289 (isa<NamespaceDecl>(Owner) && 4290 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4291 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4292 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4293 4294 // Recover by adding 'static'. 4295 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4296 PrevSpec, DiagID, Policy); 4297 } 4298 // C++ [class.union]p6: 4299 // A storage class is not allowed in a declaration of an 4300 // anonymous union in a class scope. 4301 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4302 isa<RecordDecl>(Owner)) { 4303 Diag(DS.getStorageClassSpecLoc(), 4304 diag::err_anonymous_union_with_storage_spec) 4305 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4306 4307 // Recover by removing the storage specifier. 4308 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4309 SourceLocation(), 4310 PrevSpec, DiagID, Context.getPrintingPolicy()); 4311 } 4312 } 4313 4314 // Ignore const/volatile/restrict qualifiers. 4315 if (DS.getTypeQualifiers()) { 4316 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4317 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4318 << Record->isUnion() << "const" 4319 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4320 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4321 Diag(DS.getVolatileSpecLoc(), 4322 diag::ext_anonymous_struct_union_qualified) 4323 << Record->isUnion() << "volatile" 4324 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4325 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4326 Diag(DS.getRestrictSpecLoc(), 4327 diag::ext_anonymous_struct_union_qualified) 4328 << Record->isUnion() << "restrict" 4329 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4330 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4331 Diag(DS.getAtomicSpecLoc(), 4332 diag::ext_anonymous_struct_union_qualified) 4333 << Record->isUnion() << "_Atomic" 4334 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4335 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4336 Diag(DS.getUnalignedSpecLoc(), 4337 diag::ext_anonymous_struct_union_qualified) 4338 << Record->isUnion() << "__unaligned" 4339 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4340 4341 DS.ClearTypeQualifiers(); 4342 } 4343 4344 // C++ [class.union]p2: 4345 // The member-specification of an anonymous union shall only 4346 // define non-static data members. [Note: nested types and 4347 // functions cannot be declared within an anonymous union. ] 4348 for (auto *Mem : Record->decls()) { 4349 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4350 // C++ [class.union]p3: 4351 // An anonymous union shall not have private or protected 4352 // members (clause 11). 4353 assert(FD->getAccess() != AS_none); 4354 if (FD->getAccess() != AS_public) { 4355 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4356 << Record->isUnion() << (FD->getAccess() == AS_protected); 4357 Invalid = true; 4358 } 4359 4360 // C++ [class.union]p1 4361 // An object of a class with a non-trivial constructor, a non-trivial 4362 // copy constructor, a non-trivial destructor, or a non-trivial copy 4363 // assignment operator cannot be a member of a union, nor can an 4364 // array of such objects. 4365 if (CheckNontrivialField(FD)) 4366 Invalid = true; 4367 } else if (Mem->isImplicit()) { 4368 // Any implicit members are fine. 4369 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4370 // This is a type that showed up in an 4371 // elaborated-type-specifier inside the anonymous struct or 4372 // union, but which actually declares a type outside of the 4373 // anonymous struct or union. It's okay. 4374 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4375 if (!MemRecord->isAnonymousStructOrUnion() && 4376 MemRecord->getDeclName()) { 4377 // Visual C++ allows type definition in anonymous struct or union. 4378 if (getLangOpts().MicrosoftExt) 4379 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4380 << Record->isUnion(); 4381 else { 4382 // This is a nested type declaration. 4383 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4384 << Record->isUnion(); 4385 Invalid = true; 4386 } 4387 } else { 4388 // This is an anonymous type definition within another anonymous type. 4389 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4390 // not part of standard C++. 4391 Diag(MemRecord->getLocation(), 4392 diag::ext_anonymous_record_with_anonymous_type) 4393 << Record->isUnion(); 4394 } 4395 } else if (isa<AccessSpecDecl>(Mem)) { 4396 // Any access specifier is fine. 4397 } else if (isa<StaticAssertDecl>(Mem)) { 4398 // In C++1z, static_assert declarations are also fine. 4399 } else { 4400 // We have something that isn't a non-static data 4401 // member. Complain about it. 4402 unsigned DK = diag::err_anonymous_record_bad_member; 4403 if (isa<TypeDecl>(Mem)) 4404 DK = diag::err_anonymous_record_with_type; 4405 else if (isa<FunctionDecl>(Mem)) 4406 DK = diag::err_anonymous_record_with_function; 4407 else if (isa<VarDecl>(Mem)) 4408 DK = diag::err_anonymous_record_with_static; 4409 4410 // Visual C++ allows type definition in anonymous struct or union. 4411 if (getLangOpts().MicrosoftExt && 4412 DK == diag::err_anonymous_record_with_type) 4413 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4414 << Record->isUnion(); 4415 else { 4416 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4417 Invalid = true; 4418 } 4419 } 4420 } 4421 4422 // C++11 [class.union]p8 (DR1460): 4423 // At most one variant member of a union may have a 4424 // brace-or-equal-initializer. 4425 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4426 Owner->isRecord()) 4427 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4428 cast<CXXRecordDecl>(Record)); 4429 } 4430 4431 if (!Record->isUnion() && !Owner->isRecord()) { 4432 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4433 << getLangOpts().CPlusPlus; 4434 Invalid = true; 4435 } 4436 4437 // Mock up a declarator. 4438 Declarator Dc(DS, Declarator::MemberContext); 4439 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4440 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4441 4442 // Create a declaration for this anonymous struct/union. 4443 NamedDecl *Anon = nullptr; 4444 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4445 Anon = FieldDecl::Create(Context, OwningClass, 4446 DS.getLocStart(), 4447 Record->getLocation(), 4448 /*IdentifierInfo=*/nullptr, 4449 Context.getTypeDeclType(Record), 4450 TInfo, 4451 /*BitWidth=*/nullptr, /*Mutable=*/false, 4452 /*InitStyle=*/ICIS_NoInit); 4453 Anon->setAccess(AS); 4454 if (getLangOpts().CPlusPlus) 4455 FieldCollector->Add(cast<FieldDecl>(Anon)); 4456 } else { 4457 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4458 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4459 if (SCSpec == DeclSpec::SCS_mutable) { 4460 // mutable can only appear on non-static class members, so it's always 4461 // an error here 4462 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4463 Invalid = true; 4464 SC = SC_None; 4465 } 4466 4467 Anon = VarDecl::Create(Context, Owner, 4468 DS.getLocStart(), 4469 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4470 Context.getTypeDeclType(Record), 4471 TInfo, SC); 4472 4473 // Default-initialize the implicit variable. This initialization will be 4474 // trivial in almost all cases, except if a union member has an in-class 4475 // initializer: 4476 // union { int n = 0; }; 4477 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4478 } 4479 Anon->setImplicit(); 4480 4481 // Mark this as an anonymous struct/union type. 4482 Record->setAnonymousStructOrUnion(true); 4483 4484 // Add the anonymous struct/union object to the current 4485 // context. We'll be referencing this object when we refer to one of 4486 // its members. 4487 Owner->addDecl(Anon); 4488 4489 // Inject the members of the anonymous struct/union into the owning 4490 // context and into the identifier resolver chain for name lookup 4491 // purposes. 4492 SmallVector<NamedDecl*, 2> Chain; 4493 Chain.push_back(Anon); 4494 4495 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4496 Invalid = true; 4497 4498 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4499 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4500 Decl *ManglingContextDecl; 4501 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4502 NewVD->getDeclContext(), ManglingContextDecl)) { 4503 Context.setManglingNumber( 4504 NewVD, MCtx->getManglingNumber( 4505 NewVD, getMSManglingNumber(getLangOpts(), S))); 4506 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4507 } 4508 } 4509 } 4510 4511 if (Invalid) 4512 Anon->setInvalidDecl(); 4513 4514 return Anon; 4515 } 4516 4517 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4518 /// Microsoft C anonymous structure. 4519 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4520 /// Example: 4521 /// 4522 /// struct A { int a; }; 4523 /// struct B { struct A; int b; }; 4524 /// 4525 /// void foo() { 4526 /// B var; 4527 /// var.a = 3; 4528 /// } 4529 /// 4530 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4531 RecordDecl *Record) { 4532 assert(Record && "expected a record!"); 4533 4534 // Mock up a declarator. 4535 Declarator Dc(DS, Declarator::TypeNameContext); 4536 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4537 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4538 4539 auto *ParentDecl = cast<RecordDecl>(CurContext); 4540 QualType RecTy = Context.getTypeDeclType(Record); 4541 4542 // Create a declaration for this anonymous struct. 4543 NamedDecl *Anon = FieldDecl::Create(Context, 4544 ParentDecl, 4545 DS.getLocStart(), 4546 DS.getLocStart(), 4547 /*IdentifierInfo=*/nullptr, 4548 RecTy, 4549 TInfo, 4550 /*BitWidth=*/nullptr, /*Mutable=*/false, 4551 /*InitStyle=*/ICIS_NoInit); 4552 Anon->setImplicit(); 4553 4554 // Add the anonymous struct object to the current context. 4555 CurContext->addDecl(Anon); 4556 4557 // Inject the members of the anonymous struct into the current 4558 // context and into the identifier resolver chain for name lookup 4559 // purposes. 4560 SmallVector<NamedDecl*, 2> Chain; 4561 Chain.push_back(Anon); 4562 4563 RecordDecl *RecordDef = Record->getDefinition(); 4564 if (RequireCompleteType(Anon->getLocation(), RecTy, 4565 diag::err_field_incomplete) || 4566 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4567 AS_none, Chain)) { 4568 Anon->setInvalidDecl(); 4569 ParentDecl->setInvalidDecl(); 4570 } 4571 4572 return Anon; 4573 } 4574 4575 /// GetNameForDeclarator - Determine the full declaration name for the 4576 /// given Declarator. 4577 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4578 return GetNameFromUnqualifiedId(D.getName()); 4579 } 4580 4581 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4582 DeclarationNameInfo 4583 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4584 DeclarationNameInfo NameInfo; 4585 NameInfo.setLoc(Name.StartLocation); 4586 4587 switch (Name.getKind()) { 4588 4589 case UnqualifiedId::IK_ImplicitSelfParam: 4590 case UnqualifiedId::IK_Identifier: 4591 NameInfo.setName(Name.Identifier); 4592 NameInfo.setLoc(Name.StartLocation); 4593 return NameInfo; 4594 4595 case UnqualifiedId::IK_OperatorFunctionId: 4596 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4597 Name.OperatorFunctionId.Operator)); 4598 NameInfo.setLoc(Name.StartLocation); 4599 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4600 = Name.OperatorFunctionId.SymbolLocations[0]; 4601 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4602 = Name.EndLocation.getRawEncoding(); 4603 return NameInfo; 4604 4605 case UnqualifiedId::IK_LiteralOperatorId: 4606 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4607 Name.Identifier)); 4608 NameInfo.setLoc(Name.StartLocation); 4609 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4610 return NameInfo; 4611 4612 case UnqualifiedId::IK_ConversionFunctionId: { 4613 TypeSourceInfo *TInfo; 4614 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4615 if (Ty.isNull()) 4616 return DeclarationNameInfo(); 4617 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4618 Context.getCanonicalType(Ty))); 4619 NameInfo.setLoc(Name.StartLocation); 4620 NameInfo.setNamedTypeInfo(TInfo); 4621 return NameInfo; 4622 } 4623 4624 case UnqualifiedId::IK_ConstructorName: { 4625 TypeSourceInfo *TInfo; 4626 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4627 if (Ty.isNull()) 4628 return DeclarationNameInfo(); 4629 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4630 Context.getCanonicalType(Ty))); 4631 NameInfo.setLoc(Name.StartLocation); 4632 NameInfo.setNamedTypeInfo(TInfo); 4633 return NameInfo; 4634 } 4635 4636 case UnqualifiedId::IK_ConstructorTemplateId: { 4637 // In well-formed code, we can only have a constructor 4638 // template-id that refers to the current context, so go there 4639 // to find the actual type being constructed. 4640 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4641 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4642 return DeclarationNameInfo(); 4643 4644 // Determine the type of the class being constructed. 4645 QualType CurClassType = Context.getTypeDeclType(CurClass); 4646 4647 // FIXME: Check two things: that the template-id names the same type as 4648 // CurClassType, and that the template-id does not occur when the name 4649 // was qualified. 4650 4651 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4652 Context.getCanonicalType(CurClassType))); 4653 NameInfo.setLoc(Name.StartLocation); 4654 // FIXME: should we retrieve TypeSourceInfo? 4655 NameInfo.setNamedTypeInfo(nullptr); 4656 return NameInfo; 4657 } 4658 4659 case UnqualifiedId::IK_DestructorName: { 4660 TypeSourceInfo *TInfo; 4661 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4662 if (Ty.isNull()) 4663 return DeclarationNameInfo(); 4664 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4665 Context.getCanonicalType(Ty))); 4666 NameInfo.setLoc(Name.StartLocation); 4667 NameInfo.setNamedTypeInfo(TInfo); 4668 return NameInfo; 4669 } 4670 4671 case UnqualifiedId::IK_TemplateId: { 4672 TemplateName TName = Name.TemplateId->Template.get(); 4673 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4674 return Context.getNameForTemplate(TName, TNameLoc); 4675 } 4676 4677 } // switch (Name.getKind()) 4678 4679 llvm_unreachable("Unknown name kind"); 4680 } 4681 4682 static QualType getCoreType(QualType Ty) { 4683 do { 4684 if (Ty->isPointerType() || Ty->isReferenceType()) 4685 Ty = Ty->getPointeeType(); 4686 else if (Ty->isArrayType()) 4687 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4688 else 4689 return Ty.withoutLocalFastQualifiers(); 4690 } while (true); 4691 } 4692 4693 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4694 /// and Definition have "nearly" matching parameters. This heuristic is 4695 /// used to improve diagnostics in the case where an out-of-line function 4696 /// definition doesn't match any declaration within the class or namespace. 4697 /// Also sets Params to the list of indices to the parameters that differ 4698 /// between the declaration and the definition. If hasSimilarParameters 4699 /// returns true and Params is empty, then all of the parameters match. 4700 static bool hasSimilarParameters(ASTContext &Context, 4701 FunctionDecl *Declaration, 4702 FunctionDecl *Definition, 4703 SmallVectorImpl<unsigned> &Params) { 4704 Params.clear(); 4705 if (Declaration->param_size() != Definition->param_size()) 4706 return false; 4707 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4708 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4709 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4710 4711 // The parameter types are identical 4712 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4713 continue; 4714 4715 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4716 QualType DefParamBaseTy = getCoreType(DefParamTy); 4717 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4718 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4719 4720 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4721 (DeclTyName && DeclTyName == DefTyName)) 4722 Params.push_back(Idx); 4723 else // The two parameters aren't even close 4724 return false; 4725 } 4726 4727 return true; 4728 } 4729 4730 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4731 /// declarator needs to be rebuilt in the current instantiation. 4732 /// Any bits of declarator which appear before the name are valid for 4733 /// consideration here. That's specifically the type in the decl spec 4734 /// and the base type in any member-pointer chunks. 4735 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4736 DeclarationName Name) { 4737 // The types we specifically need to rebuild are: 4738 // - typenames, typeofs, and decltypes 4739 // - types which will become injected class names 4740 // Of course, we also need to rebuild any type referencing such a 4741 // type. It's safest to just say "dependent", but we call out a 4742 // few cases here. 4743 4744 DeclSpec &DS = D.getMutableDeclSpec(); 4745 switch (DS.getTypeSpecType()) { 4746 case DeclSpec::TST_typename: 4747 case DeclSpec::TST_typeofType: 4748 case DeclSpec::TST_underlyingType: 4749 case DeclSpec::TST_atomic: { 4750 // Grab the type from the parser. 4751 TypeSourceInfo *TSI = nullptr; 4752 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4753 if (T.isNull() || !T->isDependentType()) break; 4754 4755 // Make sure there's a type source info. This isn't really much 4756 // of a waste; most dependent types should have type source info 4757 // attached already. 4758 if (!TSI) 4759 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4760 4761 // Rebuild the type in the current instantiation. 4762 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4763 if (!TSI) return true; 4764 4765 // Store the new type back in the decl spec. 4766 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4767 DS.UpdateTypeRep(LocType); 4768 break; 4769 } 4770 4771 case DeclSpec::TST_decltype: 4772 case DeclSpec::TST_typeofExpr: { 4773 Expr *E = DS.getRepAsExpr(); 4774 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4775 if (Result.isInvalid()) return true; 4776 DS.UpdateExprRep(Result.get()); 4777 break; 4778 } 4779 4780 default: 4781 // Nothing to do for these decl specs. 4782 break; 4783 } 4784 4785 // It doesn't matter what order we do this in. 4786 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4787 DeclaratorChunk &Chunk = D.getTypeObject(I); 4788 4789 // The only type information in the declarator which can come 4790 // before the declaration name is the base type of a member 4791 // pointer. 4792 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4793 continue; 4794 4795 // Rebuild the scope specifier in-place. 4796 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4797 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4798 return true; 4799 } 4800 4801 return false; 4802 } 4803 4804 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4805 D.setFunctionDefinitionKind(FDK_Declaration); 4806 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4807 4808 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4809 Dcl && Dcl->getDeclContext()->isFileContext()) 4810 Dcl->setTopLevelDeclInObjCContainer(); 4811 4812 return Dcl; 4813 } 4814 4815 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4816 /// If T is the name of a class, then each of the following shall have a 4817 /// name different from T: 4818 /// - every static data member of class T; 4819 /// - every member function of class T 4820 /// - every member of class T that is itself a type; 4821 /// \returns true if the declaration name violates these rules. 4822 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4823 DeclarationNameInfo NameInfo) { 4824 DeclarationName Name = NameInfo.getName(); 4825 4826 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4827 while (Record && Record->isAnonymousStructOrUnion()) 4828 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4829 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4830 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4831 return true; 4832 } 4833 4834 return false; 4835 } 4836 4837 /// \brief Diagnose a declaration whose declarator-id has the given 4838 /// nested-name-specifier. 4839 /// 4840 /// \param SS The nested-name-specifier of the declarator-id. 4841 /// 4842 /// \param DC The declaration context to which the nested-name-specifier 4843 /// resolves. 4844 /// 4845 /// \param Name The name of the entity being declared. 4846 /// 4847 /// \param Loc The location of the name of the entity being declared. 4848 /// 4849 /// \returns true if we cannot safely recover from this error, false otherwise. 4850 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4851 DeclarationName Name, 4852 SourceLocation Loc) { 4853 DeclContext *Cur = CurContext; 4854 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4855 Cur = Cur->getParent(); 4856 4857 // If the user provided a superfluous scope specifier that refers back to the 4858 // class in which the entity is already declared, diagnose and ignore it. 4859 // 4860 // class X { 4861 // void X::f(); 4862 // }; 4863 // 4864 // Note, it was once ill-formed to give redundant qualification in all 4865 // contexts, but that rule was removed by DR482. 4866 if (Cur->Equals(DC)) { 4867 if (Cur->isRecord()) { 4868 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4869 : diag::err_member_extra_qualification) 4870 << Name << FixItHint::CreateRemoval(SS.getRange()); 4871 SS.clear(); 4872 } else { 4873 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4874 } 4875 return false; 4876 } 4877 4878 // Check whether the qualifying scope encloses the scope of the original 4879 // declaration. 4880 if (!Cur->Encloses(DC)) { 4881 if (Cur->isRecord()) 4882 Diag(Loc, diag::err_member_qualification) 4883 << Name << SS.getRange(); 4884 else if (isa<TranslationUnitDecl>(DC)) 4885 Diag(Loc, diag::err_invalid_declarator_global_scope) 4886 << Name << SS.getRange(); 4887 else if (isa<FunctionDecl>(Cur)) 4888 Diag(Loc, diag::err_invalid_declarator_in_function) 4889 << Name << SS.getRange(); 4890 else if (isa<BlockDecl>(Cur)) 4891 Diag(Loc, diag::err_invalid_declarator_in_block) 4892 << Name << SS.getRange(); 4893 else 4894 Diag(Loc, diag::err_invalid_declarator_scope) 4895 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4896 4897 return true; 4898 } 4899 4900 if (Cur->isRecord()) { 4901 // Cannot qualify members within a class. 4902 Diag(Loc, diag::err_member_qualification) 4903 << Name << SS.getRange(); 4904 SS.clear(); 4905 4906 // C++ constructors and destructors with incorrect scopes can break 4907 // our AST invariants by having the wrong underlying types. If 4908 // that's the case, then drop this declaration entirely. 4909 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4910 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4911 !Context.hasSameType(Name.getCXXNameType(), 4912 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4913 return true; 4914 4915 return false; 4916 } 4917 4918 // C++11 [dcl.meaning]p1: 4919 // [...] "The nested-name-specifier of the qualified declarator-id shall 4920 // not begin with a decltype-specifer" 4921 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4922 while (SpecLoc.getPrefix()) 4923 SpecLoc = SpecLoc.getPrefix(); 4924 if (dyn_cast_or_null<DecltypeType>( 4925 SpecLoc.getNestedNameSpecifier()->getAsType())) 4926 Diag(Loc, diag::err_decltype_in_declarator) 4927 << SpecLoc.getTypeLoc().getSourceRange(); 4928 4929 return false; 4930 } 4931 4932 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4933 MultiTemplateParamsArg TemplateParamLists) { 4934 // TODO: consider using NameInfo for diagnostic. 4935 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4936 DeclarationName Name = NameInfo.getName(); 4937 4938 // All of these full declarators require an identifier. If it doesn't have 4939 // one, the ParsedFreeStandingDeclSpec action should be used. 4940 if (D.isDecompositionDeclarator()) { 4941 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 4942 } else if (!Name) { 4943 if (!D.isInvalidType()) // Reject this if we think it is valid. 4944 Diag(D.getDeclSpec().getLocStart(), 4945 diag::err_declarator_need_ident) 4946 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4947 return nullptr; 4948 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4949 return nullptr; 4950 4951 // The scope passed in may not be a decl scope. Zip up the scope tree until 4952 // we find one that is. 4953 while ((S->getFlags() & Scope::DeclScope) == 0 || 4954 (S->getFlags() & Scope::TemplateParamScope) != 0) 4955 S = S->getParent(); 4956 4957 DeclContext *DC = CurContext; 4958 if (D.getCXXScopeSpec().isInvalid()) 4959 D.setInvalidType(); 4960 else if (D.getCXXScopeSpec().isSet()) { 4961 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4962 UPPC_DeclarationQualifier)) 4963 return nullptr; 4964 4965 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4966 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4967 if (!DC || isa<EnumDecl>(DC)) { 4968 // If we could not compute the declaration context, it's because the 4969 // declaration context is dependent but does not refer to a class, 4970 // class template, or class template partial specialization. Complain 4971 // and return early, to avoid the coming semantic disaster. 4972 Diag(D.getIdentifierLoc(), 4973 diag::err_template_qualified_declarator_no_match) 4974 << D.getCXXScopeSpec().getScopeRep() 4975 << D.getCXXScopeSpec().getRange(); 4976 return nullptr; 4977 } 4978 bool IsDependentContext = DC->isDependentContext(); 4979 4980 if (!IsDependentContext && 4981 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4982 return nullptr; 4983 4984 // If a class is incomplete, do not parse entities inside it. 4985 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4986 Diag(D.getIdentifierLoc(), 4987 diag::err_member_def_undefined_record) 4988 << Name << DC << D.getCXXScopeSpec().getRange(); 4989 return nullptr; 4990 } 4991 if (!D.getDeclSpec().isFriendSpecified()) { 4992 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4993 Name, D.getIdentifierLoc())) { 4994 if (DC->isRecord()) 4995 return nullptr; 4996 4997 D.setInvalidType(); 4998 } 4999 } 5000 5001 // Check whether we need to rebuild the type of the given 5002 // declaration in the current instantiation. 5003 if (EnteringContext && IsDependentContext && 5004 TemplateParamLists.size() != 0) { 5005 ContextRAII SavedContext(*this, DC); 5006 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5007 D.setInvalidType(); 5008 } 5009 } 5010 5011 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5012 QualType R = TInfo->getType(); 5013 5014 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5015 // If this is a typedef, we'll end up spewing multiple diagnostics. 5016 // Just return early; it's safer. If this is a function, let the 5017 // "constructor cannot have a return type" diagnostic handle it. 5018 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5019 return nullptr; 5020 5021 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5022 UPPC_DeclarationType)) 5023 D.setInvalidType(); 5024 5025 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5026 ForRedeclaration); 5027 5028 // See if this is a redefinition of a variable in the same scope. 5029 if (!D.getCXXScopeSpec().isSet()) { 5030 bool IsLinkageLookup = false; 5031 bool CreateBuiltins = false; 5032 5033 // If the declaration we're planning to build will be a function 5034 // or object with linkage, then look for another declaration with 5035 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5036 // 5037 // If the declaration we're planning to build will be declared with 5038 // external linkage in the translation unit, create any builtin with 5039 // the same name. 5040 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5041 /* Do nothing*/; 5042 else if (CurContext->isFunctionOrMethod() && 5043 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5044 R->isFunctionType())) { 5045 IsLinkageLookup = true; 5046 CreateBuiltins = 5047 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5048 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5049 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5050 CreateBuiltins = true; 5051 5052 if (IsLinkageLookup) 5053 Previous.clear(LookupRedeclarationWithLinkage); 5054 5055 LookupName(Previous, S, CreateBuiltins); 5056 } else { // Something like "int foo::x;" 5057 LookupQualifiedName(Previous, DC); 5058 5059 // C++ [dcl.meaning]p1: 5060 // When the declarator-id is qualified, the declaration shall refer to a 5061 // previously declared member of the class or namespace to which the 5062 // qualifier refers (or, in the case of a namespace, of an element of the 5063 // inline namespace set of that namespace (7.3.1)) or to a specialization 5064 // thereof; [...] 5065 // 5066 // Note that we already checked the context above, and that we do not have 5067 // enough information to make sure that Previous contains the declaration 5068 // we want to match. For example, given: 5069 // 5070 // class X { 5071 // void f(); 5072 // void f(float); 5073 // }; 5074 // 5075 // void X::f(int) { } // ill-formed 5076 // 5077 // In this case, Previous will point to the overload set 5078 // containing the two f's declared in X, but neither of them 5079 // matches. 5080 5081 // C++ [dcl.meaning]p1: 5082 // [...] the member shall not merely have been introduced by a 5083 // using-declaration in the scope of the class or namespace nominated by 5084 // the nested-name-specifier of the declarator-id. 5085 RemoveUsingDecls(Previous); 5086 } 5087 5088 if (Previous.isSingleResult() && 5089 Previous.getFoundDecl()->isTemplateParameter()) { 5090 // Maybe we will complain about the shadowed template parameter. 5091 if (!D.isInvalidType()) 5092 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5093 Previous.getFoundDecl()); 5094 5095 // Just pretend that we didn't see the previous declaration. 5096 Previous.clear(); 5097 } 5098 5099 // In C++, the previous declaration we find might be a tag type 5100 // (class or enum). In this case, the new declaration will hide the 5101 // tag type. Note that this does does not apply if we're declaring a 5102 // typedef (C++ [dcl.typedef]p4). 5103 if (Previous.isSingleTagDecl() && 5104 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5105 Previous.clear(); 5106 5107 // Check that there are no default arguments other than in the parameters 5108 // of a function declaration (C++ only). 5109 if (getLangOpts().CPlusPlus) 5110 CheckExtraCXXDefaultArguments(D); 5111 5112 if (D.getDeclSpec().isConceptSpecified()) { 5113 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5114 // applied only to the definition of a function template or variable 5115 // template, declared in namespace scope 5116 if (!TemplateParamLists.size()) { 5117 Diag(D.getDeclSpec().getConceptSpecLoc(), 5118 diag:: err_concept_wrong_decl_kind); 5119 return nullptr; 5120 } 5121 5122 if (!DC->getRedeclContext()->isFileContext()) { 5123 Diag(D.getIdentifierLoc(), 5124 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5125 return nullptr; 5126 } 5127 } 5128 5129 NamedDecl *New; 5130 5131 bool AddToScope = true; 5132 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5133 if (TemplateParamLists.size()) { 5134 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5135 return nullptr; 5136 } 5137 5138 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5139 } else if (R->isFunctionType()) { 5140 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5141 TemplateParamLists, 5142 AddToScope); 5143 } else { 5144 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5145 AddToScope); 5146 } 5147 5148 if (!New) 5149 return nullptr; 5150 5151 // If this has an identifier and is not a function template specialization, 5152 // add it to the scope stack. 5153 if (New->getDeclName() && AddToScope) { 5154 // Only make a locally-scoped extern declaration visible if it is the first 5155 // declaration of this entity. Qualified lookup for such an entity should 5156 // only find this declaration if there is no visible declaration of it. 5157 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5158 PushOnScopeChains(New, S, AddToContext); 5159 if (!AddToContext) 5160 CurContext->addHiddenDecl(New); 5161 } 5162 5163 if (isInOpenMPDeclareTargetContext()) 5164 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5165 5166 return New; 5167 } 5168 5169 /// Helper method to turn variable array types into constant array 5170 /// types in certain situations which would otherwise be errors (for 5171 /// GCC compatibility). 5172 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5173 ASTContext &Context, 5174 bool &SizeIsNegative, 5175 llvm::APSInt &Oversized) { 5176 // This method tries to turn a variable array into a constant 5177 // array even when the size isn't an ICE. This is necessary 5178 // for compatibility with code that depends on gcc's buggy 5179 // constant expression folding, like struct {char x[(int)(char*)2];} 5180 SizeIsNegative = false; 5181 Oversized = 0; 5182 5183 if (T->isDependentType()) 5184 return QualType(); 5185 5186 QualifierCollector Qs; 5187 const Type *Ty = Qs.strip(T); 5188 5189 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5190 QualType Pointee = PTy->getPointeeType(); 5191 QualType FixedType = 5192 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5193 Oversized); 5194 if (FixedType.isNull()) return FixedType; 5195 FixedType = Context.getPointerType(FixedType); 5196 return Qs.apply(Context, FixedType); 5197 } 5198 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5199 QualType Inner = PTy->getInnerType(); 5200 QualType FixedType = 5201 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5202 Oversized); 5203 if (FixedType.isNull()) return FixedType; 5204 FixedType = Context.getParenType(FixedType); 5205 return Qs.apply(Context, FixedType); 5206 } 5207 5208 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5209 if (!VLATy) 5210 return QualType(); 5211 // FIXME: We should probably handle this case 5212 if (VLATy->getElementType()->isVariablyModifiedType()) 5213 return QualType(); 5214 5215 llvm::APSInt Res; 5216 if (!VLATy->getSizeExpr() || 5217 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5218 return QualType(); 5219 5220 // Check whether the array size is negative. 5221 if (Res.isSigned() && Res.isNegative()) { 5222 SizeIsNegative = true; 5223 return QualType(); 5224 } 5225 5226 // Check whether the array is too large to be addressed. 5227 unsigned ActiveSizeBits 5228 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5229 Res); 5230 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5231 Oversized = Res; 5232 return QualType(); 5233 } 5234 5235 return Context.getConstantArrayType(VLATy->getElementType(), 5236 Res, ArrayType::Normal, 0); 5237 } 5238 5239 static void 5240 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5241 SrcTL = SrcTL.getUnqualifiedLoc(); 5242 DstTL = DstTL.getUnqualifiedLoc(); 5243 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5244 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5245 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5246 DstPTL.getPointeeLoc()); 5247 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5248 return; 5249 } 5250 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5251 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5252 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5253 DstPTL.getInnerLoc()); 5254 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5255 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5256 return; 5257 } 5258 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5259 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5260 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5261 TypeLoc DstElemTL = DstATL.getElementLoc(); 5262 DstElemTL.initializeFullCopy(SrcElemTL); 5263 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5264 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5265 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5266 } 5267 5268 /// Helper method to turn variable array types into constant array 5269 /// types in certain situations which would otherwise be errors (for 5270 /// GCC compatibility). 5271 static TypeSourceInfo* 5272 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5273 ASTContext &Context, 5274 bool &SizeIsNegative, 5275 llvm::APSInt &Oversized) { 5276 QualType FixedTy 5277 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5278 SizeIsNegative, Oversized); 5279 if (FixedTy.isNull()) 5280 return nullptr; 5281 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5282 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5283 FixedTInfo->getTypeLoc()); 5284 return FixedTInfo; 5285 } 5286 5287 /// \brief Register the given locally-scoped extern "C" declaration so 5288 /// that it can be found later for redeclarations. We include any extern "C" 5289 /// declaration that is not visible in the translation unit here, not just 5290 /// function-scope declarations. 5291 void 5292 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5293 if (!getLangOpts().CPlusPlus && 5294 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5295 // Don't need to track declarations in the TU in C. 5296 return; 5297 5298 // Note that we have a locally-scoped external with this name. 5299 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5300 } 5301 5302 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5303 // FIXME: We can have multiple results via __attribute__((overloadable)). 5304 auto Result = Context.getExternCContextDecl()->lookup(Name); 5305 return Result.empty() ? nullptr : *Result.begin(); 5306 } 5307 5308 /// \brief Diagnose function specifiers on a declaration of an identifier that 5309 /// does not identify a function. 5310 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5311 // FIXME: We should probably indicate the identifier in question to avoid 5312 // confusion for constructs like "virtual int a(), b;" 5313 if (DS.isVirtualSpecified()) 5314 Diag(DS.getVirtualSpecLoc(), 5315 diag::err_virtual_non_function); 5316 5317 if (DS.isExplicitSpecified()) 5318 Diag(DS.getExplicitSpecLoc(), 5319 diag::err_explicit_non_function); 5320 5321 if (DS.isNoreturnSpecified()) 5322 Diag(DS.getNoreturnSpecLoc(), 5323 diag::err_noreturn_non_function); 5324 } 5325 5326 NamedDecl* 5327 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5328 TypeSourceInfo *TInfo, LookupResult &Previous) { 5329 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5330 if (D.getCXXScopeSpec().isSet()) { 5331 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5332 << D.getCXXScopeSpec().getRange(); 5333 D.setInvalidType(); 5334 // Pretend we didn't see the scope specifier. 5335 DC = CurContext; 5336 Previous.clear(); 5337 } 5338 5339 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5340 5341 if (D.getDeclSpec().isInlineSpecified()) 5342 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5343 << getLangOpts().CPlusPlus1z; 5344 if (D.getDeclSpec().isConstexprSpecified()) 5345 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5346 << 1; 5347 if (D.getDeclSpec().isConceptSpecified()) 5348 Diag(D.getDeclSpec().getConceptSpecLoc(), 5349 diag::err_concept_wrong_decl_kind); 5350 5351 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5352 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5353 << D.getName().getSourceRange(); 5354 return nullptr; 5355 } 5356 5357 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5358 if (!NewTD) return nullptr; 5359 5360 // Handle attributes prior to checking for duplicates in MergeVarDecl 5361 ProcessDeclAttributes(S, NewTD, D); 5362 5363 CheckTypedefForVariablyModifiedType(S, NewTD); 5364 5365 bool Redeclaration = D.isRedeclaration(); 5366 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5367 D.setRedeclaration(Redeclaration); 5368 return ND; 5369 } 5370 5371 void 5372 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5373 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5374 // then it shall have block scope. 5375 // Note that variably modified types must be fixed before merging the decl so 5376 // that redeclarations will match. 5377 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5378 QualType T = TInfo->getType(); 5379 if (T->isVariablyModifiedType()) { 5380 getCurFunction()->setHasBranchProtectedScope(); 5381 5382 if (S->getFnParent() == nullptr) { 5383 bool SizeIsNegative; 5384 llvm::APSInt Oversized; 5385 TypeSourceInfo *FixedTInfo = 5386 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5387 SizeIsNegative, 5388 Oversized); 5389 if (FixedTInfo) { 5390 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5391 NewTD->setTypeSourceInfo(FixedTInfo); 5392 } else { 5393 if (SizeIsNegative) 5394 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5395 else if (T->isVariableArrayType()) 5396 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5397 else if (Oversized.getBoolValue()) 5398 Diag(NewTD->getLocation(), diag::err_array_too_large) 5399 << Oversized.toString(10); 5400 else 5401 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5402 NewTD->setInvalidDecl(); 5403 } 5404 } 5405 } 5406 } 5407 5408 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5409 /// declares a typedef-name, either using the 'typedef' type specifier or via 5410 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5411 NamedDecl* 5412 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5413 LookupResult &Previous, bool &Redeclaration) { 5414 // Merge the decl with the existing one if appropriate. If the decl is 5415 // in an outer scope, it isn't the same thing. 5416 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5417 /*AllowInlineNamespace*/false); 5418 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5419 if (!Previous.empty()) { 5420 Redeclaration = true; 5421 MergeTypedefNameDecl(S, NewTD, Previous); 5422 } 5423 5424 // If this is the C FILE type, notify the AST context. 5425 if (IdentifierInfo *II = NewTD->getIdentifier()) 5426 if (!NewTD->isInvalidDecl() && 5427 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5428 if (II->isStr("FILE")) 5429 Context.setFILEDecl(NewTD); 5430 else if (II->isStr("jmp_buf")) 5431 Context.setjmp_bufDecl(NewTD); 5432 else if (II->isStr("sigjmp_buf")) 5433 Context.setsigjmp_bufDecl(NewTD); 5434 else if (II->isStr("ucontext_t")) 5435 Context.setucontext_tDecl(NewTD); 5436 } 5437 5438 return NewTD; 5439 } 5440 5441 /// \brief Determines whether the given declaration is an out-of-scope 5442 /// previous declaration. 5443 /// 5444 /// This routine should be invoked when name lookup has found a 5445 /// previous declaration (PrevDecl) that is not in the scope where a 5446 /// new declaration by the same name is being introduced. If the new 5447 /// declaration occurs in a local scope, previous declarations with 5448 /// linkage may still be considered previous declarations (C99 5449 /// 6.2.2p4-5, C++ [basic.link]p6). 5450 /// 5451 /// \param PrevDecl the previous declaration found by name 5452 /// lookup 5453 /// 5454 /// \param DC the context in which the new declaration is being 5455 /// declared. 5456 /// 5457 /// \returns true if PrevDecl is an out-of-scope previous declaration 5458 /// for a new delcaration with the same name. 5459 static bool 5460 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5461 ASTContext &Context) { 5462 if (!PrevDecl) 5463 return false; 5464 5465 if (!PrevDecl->hasLinkage()) 5466 return false; 5467 5468 if (Context.getLangOpts().CPlusPlus) { 5469 // C++ [basic.link]p6: 5470 // If there is a visible declaration of an entity with linkage 5471 // having the same name and type, ignoring entities declared 5472 // outside the innermost enclosing namespace scope, the block 5473 // scope declaration declares that same entity and receives the 5474 // linkage of the previous declaration. 5475 DeclContext *OuterContext = DC->getRedeclContext(); 5476 if (!OuterContext->isFunctionOrMethod()) 5477 // This rule only applies to block-scope declarations. 5478 return false; 5479 5480 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5481 if (PrevOuterContext->isRecord()) 5482 // We found a member function: ignore it. 5483 return false; 5484 5485 // Find the innermost enclosing namespace for the new and 5486 // previous declarations. 5487 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5488 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5489 5490 // The previous declaration is in a different namespace, so it 5491 // isn't the same function. 5492 if (!OuterContext->Equals(PrevOuterContext)) 5493 return false; 5494 } 5495 5496 return true; 5497 } 5498 5499 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5500 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5501 if (!SS.isSet()) return; 5502 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5503 } 5504 5505 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5506 QualType type = decl->getType(); 5507 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5508 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5509 // Various kinds of declaration aren't allowed to be __autoreleasing. 5510 unsigned kind = -1U; 5511 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5512 if (var->hasAttr<BlocksAttr>()) 5513 kind = 0; // __block 5514 else if (!var->hasLocalStorage()) 5515 kind = 1; // global 5516 } else if (isa<ObjCIvarDecl>(decl)) { 5517 kind = 3; // ivar 5518 } else if (isa<FieldDecl>(decl)) { 5519 kind = 2; // field 5520 } 5521 5522 if (kind != -1U) { 5523 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5524 << kind; 5525 } 5526 } else if (lifetime == Qualifiers::OCL_None) { 5527 // Try to infer lifetime. 5528 if (!type->isObjCLifetimeType()) 5529 return false; 5530 5531 lifetime = type->getObjCARCImplicitLifetime(); 5532 type = Context.getLifetimeQualifiedType(type, lifetime); 5533 decl->setType(type); 5534 } 5535 5536 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5537 // Thread-local variables cannot have lifetime. 5538 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5539 var->getTLSKind()) { 5540 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5541 << var->getType(); 5542 return true; 5543 } 5544 } 5545 5546 return false; 5547 } 5548 5549 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5550 // Ensure that an auto decl is deduced otherwise the checks below might cache 5551 // the wrong linkage. 5552 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5553 5554 // 'weak' only applies to declarations with external linkage. 5555 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5556 if (!ND.isExternallyVisible()) { 5557 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5558 ND.dropAttr<WeakAttr>(); 5559 } 5560 } 5561 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5562 if (ND.isExternallyVisible()) { 5563 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5564 ND.dropAttr<WeakRefAttr>(); 5565 ND.dropAttr<AliasAttr>(); 5566 } 5567 } 5568 5569 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5570 if (VD->hasInit()) { 5571 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5572 assert(VD->isThisDeclarationADefinition() && 5573 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5574 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5575 VD->dropAttr<AliasAttr>(); 5576 } 5577 } 5578 } 5579 5580 // 'selectany' only applies to externally visible variable declarations. 5581 // It does not apply to functions. 5582 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5583 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5584 S.Diag(Attr->getLocation(), 5585 diag::err_attribute_selectany_non_extern_data); 5586 ND.dropAttr<SelectAnyAttr>(); 5587 } 5588 } 5589 5590 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5591 // dll attributes require external linkage. Static locals may have external 5592 // linkage but still cannot be explicitly imported or exported. 5593 auto *VD = dyn_cast<VarDecl>(&ND); 5594 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5595 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5596 << &ND << Attr; 5597 ND.setInvalidDecl(); 5598 } 5599 } 5600 5601 // Virtual functions cannot be marked as 'notail'. 5602 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5603 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5604 if (MD->isVirtual()) { 5605 S.Diag(ND.getLocation(), 5606 diag::err_invalid_attribute_on_virtual_function) 5607 << Attr; 5608 ND.dropAttr<NotTailCalledAttr>(); 5609 } 5610 } 5611 5612 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5613 NamedDecl *NewDecl, 5614 bool IsSpecialization, 5615 bool IsDefinition) { 5616 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5617 OldDecl = OldTD->getTemplatedDecl(); 5618 if (!IsSpecialization) 5619 IsDefinition = false; 5620 } 5621 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5622 NewDecl = NewTD->getTemplatedDecl(); 5623 5624 if (!OldDecl || !NewDecl) 5625 return; 5626 5627 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5628 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5629 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5630 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5631 5632 // dllimport and dllexport are inheritable attributes so we have to exclude 5633 // inherited attribute instances. 5634 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5635 (NewExportAttr && !NewExportAttr->isInherited()); 5636 5637 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5638 // the only exception being explicit specializations. 5639 // Implicitly generated declarations are also excluded for now because there 5640 // is no other way to switch these to use dllimport or dllexport. 5641 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5642 5643 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5644 // Allow with a warning for free functions and global variables. 5645 bool JustWarn = false; 5646 if (!OldDecl->isCXXClassMember()) { 5647 auto *VD = dyn_cast<VarDecl>(OldDecl); 5648 if (VD && !VD->getDescribedVarTemplate()) 5649 JustWarn = true; 5650 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5651 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5652 JustWarn = true; 5653 } 5654 5655 // We cannot change a declaration that's been used because IR has already 5656 // been emitted. Dllimported functions will still work though (modulo 5657 // address equality) as they can use the thunk. 5658 if (OldDecl->isUsed()) 5659 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5660 JustWarn = false; 5661 5662 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5663 : diag::err_attribute_dll_redeclaration; 5664 S.Diag(NewDecl->getLocation(), DiagID) 5665 << NewDecl 5666 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5667 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5668 if (!JustWarn) { 5669 NewDecl->setInvalidDecl(); 5670 return; 5671 } 5672 } 5673 5674 // A redeclaration is not allowed to drop a dllimport attribute, the only 5675 // exceptions being inline function definitions, local extern declarations, 5676 // qualified friend declarations or special MSVC extension: in the last case, 5677 // the declaration is treated as if it were marked dllexport. 5678 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5679 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5680 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5681 // Ignore static data because out-of-line definitions are diagnosed 5682 // separately. 5683 IsStaticDataMember = VD->isStaticDataMember(); 5684 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5685 VarDecl::DeclarationOnly; 5686 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5687 IsInline = FD->isInlined(); 5688 IsQualifiedFriend = FD->getQualifier() && 5689 FD->getFriendObjectKind() == Decl::FOK_Declared; 5690 } 5691 5692 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5693 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5694 if (IsMicrosoft && IsDefinition) { 5695 S.Diag(NewDecl->getLocation(), 5696 diag::warn_redeclaration_without_import_attribute) 5697 << NewDecl; 5698 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5699 NewDecl->dropAttr<DLLImportAttr>(); 5700 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5701 NewImportAttr->getRange(), S.Context, 5702 NewImportAttr->getSpellingListIndex())); 5703 } else { 5704 S.Diag(NewDecl->getLocation(), 5705 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5706 << NewDecl << OldImportAttr; 5707 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5708 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5709 OldDecl->dropAttr<DLLImportAttr>(); 5710 NewDecl->dropAttr<DLLImportAttr>(); 5711 } 5712 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5713 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5714 OldDecl->dropAttr<DLLImportAttr>(); 5715 NewDecl->dropAttr<DLLImportAttr>(); 5716 S.Diag(NewDecl->getLocation(), 5717 diag::warn_dllimport_dropped_from_inline_function) 5718 << NewDecl << OldImportAttr; 5719 } 5720 } 5721 5722 /// Given that we are within the definition of the given function, 5723 /// will that definition behave like C99's 'inline', where the 5724 /// definition is discarded except for optimization purposes? 5725 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5726 // Try to avoid calling GetGVALinkageForFunction. 5727 5728 // All cases of this require the 'inline' keyword. 5729 if (!FD->isInlined()) return false; 5730 5731 // This is only possible in C++ with the gnu_inline attribute. 5732 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5733 return false; 5734 5735 // Okay, go ahead and call the relatively-more-expensive function. 5736 5737 #ifndef NDEBUG 5738 // AST quite reasonably asserts that it's working on a function 5739 // definition. We don't really have a way to tell it that we're 5740 // currently defining the function, so just lie to it in +Asserts 5741 // builds. This is an awful hack. 5742 FD->setLazyBody(1); 5743 #endif 5744 5745 bool isC99Inline = 5746 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5747 5748 #ifndef NDEBUG 5749 FD->setLazyBody(0); 5750 #endif 5751 5752 return isC99Inline; 5753 } 5754 5755 /// Determine whether a variable is extern "C" prior to attaching 5756 /// an initializer. We can't just call isExternC() here, because that 5757 /// will also compute and cache whether the declaration is externally 5758 /// visible, which might change when we attach the initializer. 5759 /// 5760 /// This can only be used if the declaration is known to not be a 5761 /// redeclaration of an internal linkage declaration. 5762 /// 5763 /// For instance: 5764 /// 5765 /// auto x = []{}; 5766 /// 5767 /// Attaching the initializer here makes this declaration not externally 5768 /// visible, because its type has internal linkage. 5769 /// 5770 /// FIXME: This is a hack. 5771 template<typename T> 5772 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5773 if (S.getLangOpts().CPlusPlus) { 5774 // In C++, the overloadable attribute negates the effects of extern "C". 5775 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5776 return false; 5777 5778 // So do CUDA's host/device attributes. 5779 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5780 D->template hasAttr<CUDAHostAttr>())) 5781 return false; 5782 } 5783 return D->isExternC(); 5784 } 5785 5786 static bool shouldConsiderLinkage(const VarDecl *VD) { 5787 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5788 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5789 return VD->hasExternalStorage(); 5790 if (DC->isFileContext()) 5791 return true; 5792 if (DC->isRecord()) 5793 return false; 5794 llvm_unreachable("Unexpected context"); 5795 } 5796 5797 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5798 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5799 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5800 isa<OMPDeclareReductionDecl>(DC)) 5801 return true; 5802 if (DC->isRecord()) 5803 return false; 5804 llvm_unreachable("Unexpected context"); 5805 } 5806 5807 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5808 AttributeList::Kind Kind) { 5809 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5810 if (L->getKind() == Kind) 5811 return true; 5812 return false; 5813 } 5814 5815 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5816 AttributeList::Kind Kind) { 5817 // Check decl attributes on the DeclSpec. 5818 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5819 return true; 5820 5821 // Walk the declarator structure, checking decl attributes that were in a type 5822 // position to the decl itself. 5823 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5824 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5825 return true; 5826 } 5827 5828 // Finally, check attributes on the decl itself. 5829 return hasParsedAttr(S, PD.getAttributes(), Kind); 5830 } 5831 5832 /// Adjust the \c DeclContext for a function or variable that might be a 5833 /// function-local external declaration. 5834 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5835 if (!DC->isFunctionOrMethod()) 5836 return false; 5837 5838 // If this is a local extern function or variable declared within a function 5839 // template, don't add it into the enclosing namespace scope until it is 5840 // instantiated; it might have a dependent type right now. 5841 if (DC->isDependentContext()) 5842 return true; 5843 5844 // C++11 [basic.link]p7: 5845 // When a block scope declaration of an entity with linkage is not found to 5846 // refer to some other declaration, then that entity is a member of the 5847 // innermost enclosing namespace. 5848 // 5849 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5850 // semantically-enclosing namespace, not a lexically-enclosing one. 5851 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5852 DC = DC->getParent(); 5853 return true; 5854 } 5855 5856 /// \brief Returns true if given declaration has external C language linkage. 5857 static bool isDeclExternC(const Decl *D) { 5858 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5859 return FD->isExternC(); 5860 if (const auto *VD = dyn_cast<VarDecl>(D)) 5861 return VD->isExternC(); 5862 5863 llvm_unreachable("Unknown type of decl!"); 5864 } 5865 5866 NamedDecl *Sema::ActOnVariableDeclarator( 5867 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5868 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5869 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5870 QualType R = TInfo->getType(); 5871 DeclarationName Name = GetNameForDeclarator(D).getName(); 5872 5873 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5874 5875 if (D.isDecompositionDeclarator()) { 5876 AddToScope = false; 5877 // Take the name of the first declarator as our name for diagnostic 5878 // purposes. 5879 auto &Decomp = D.getDecompositionDeclarator(); 5880 if (!Decomp.bindings().empty()) { 5881 II = Decomp.bindings()[0].Name; 5882 Name = II; 5883 } 5884 } else if (!II) { 5885 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5886 << Name; 5887 return nullptr; 5888 } 5889 5890 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5891 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5892 // argument. 5893 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5894 Diag(D.getIdentifierLoc(), 5895 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5896 << R; 5897 D.setInvalidType(); 5898 return nullptr; 5899 } 5900 5901 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5902 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5903 5904 // dllimport globals without explicit storage class are treated as extern. We 5905 // have to change the storage class this early to get the right DeclContext. 5906 if (SC == SC_None && !DC->isRecord() && 5907 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5908 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5909 SC = SC_Extern; 5910 5911 DeclContext *OriginalDC = DC; 5912 bool IsLocalExternDecl = SC == SC_Extern && 5913 adjustContextForLocalExternDecl(DC); 5914 5915 if (getLangOpts().OpenCL) { 5916 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5917 QualType NR = R; 5918 while (NR->isPointerType()) { 5919 if (NR->isFunctionPointerType()) { 5920 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5921 D.setInvalidType(); 5922 break; 5923 } 5924 NR = NR->getPointeeType(); 5925 } 5926 5927 if (!getOpenCLOptions().cl_khr_fp16) { 5928 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5929 // half array type (unless the cl_khr_fp16 extension is enabled). 5930 if (Context.getBaseElementType(R)->isHalfType()) { 5931 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5932 D.setInvalidType(); 5933 } 5934 } 5935 } 5936 5937 if (SCSpec == DeclSpec::SCS_mutable) { 5938 // mutable can only appear on non-static class members, so it's always 5939 // an error here 5940 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5941 D.setInvalidType(); 5942 SC = SC_None; 5943 } 5944 5945 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5946 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5947 D.getDeclSpec().getStorageClassSpecLoc())) { 5948 // In C++11, the 'register' storage class specifier is deprecated. 5949 // Suppress the warning in system macros, it's used in macros in some 5950 // popular C system headers, such as in glibc's htonl() macro. 5951 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5952 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5953 : diag::warn_deprecated_register) 5954 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5955 } 5956 5957 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5958 5959 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5960 // C99 6.9p2: The storage-class specifiers auto and register shall not 5961 // appear in the declaration specifiers in an external declaration. 5962 // Global Register+Asm is a GNU extension we support. 5963 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5964 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5965 D.setInvalidType(); 5966 } 5967 } 5968 5969 if (getLangOpts().OpenCL) { 5970 // OpenCL v1.2 s6.9.b p4: 5971 // The sampler type cannot be used with the __local and __global address 5972 // space qualifiers. 5973 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5974 R.getAddressSpace() == LangAS::opencl_global)) { 5975 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5976 } 5977 5978 // OpenCL 1.2 spec, p6.9 r: 5979 // The event type cannot be used to declare a program scope variable. 5980 // The event type cannot be used with the __local, __constant and __global 5981 // address space qualifiers. 5982 if (R->isEventT()) { 5983 if (S->getParent() == nullptr) { 5984 Diag(D.getLocStart(), diag::err_event_t_global_var); 5985 D.setInvalidType(); 5986 } 5987 5988 if (R.getAddressSpace()) { 5989 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5990 D.setInvalidType(); 5991 } 5992 } 5993 } 5994 5995 bool IsExplicitSpecialization = false; 5996 bool IsVariableTemplateSpecialization = false; 5997 bool IsPartialSpecialization = false; 5998 bool IsVariableTemplate = false; 5999 VarDecl *NewVD = nullptr; 6000 VarTemplateDecl *NewTemplate = nullptr; 6001 TemplateParameterList *TemplateParams = nullptr; 6002 if (!getLangOpts().CPlusPlus) { 6003 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6004 D.getIdentifierLoc(), II, 6005 R, TInfo, SC); 6006 6007 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6008 ParsingInitForAutoVars.insert(NewVD); 6009 6010 if (D.isInvalidType()) 6011 NewVD->setInvalidDecl(); 6012 } else { 6013 bool Invalid = false; 6014 6015 if (DC->isRecord() && !CurContext->isRecord()) { 6016 // This is an out-of-line definition of a static data member. 6017 switch (SC) { 6018 case SC_None: 6019 break; 6020 case SC_Static: 6021 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6022 diag::err_static_out_of_line) 6023 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6024 break; 6025 case SC_Auto: 6026 case SC_Register: 6027 case SC_Extern: 6028 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6029 // to names of variables declared in a block or to function parameters. 6030 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6031 // of class members 6032 6033 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6034 diag::err_storage_class_for_static_member) 6035 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6036 break; 6037 case SC_PrivateExtern: 6038 llvm_unreachable("C storage class in c++!"); 6039 } 6040 } 6041 6042 if (SC == SC_Static && CurContext->isRecord()) { 6043 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6044 if (RD->isLocalClass()) 6045 Diag(D.getIdentifierLoc(), 6046 diag::err_static_data_member_not_allowed_in_local_class) 6047 << Name << RD->getDeclName(); 6048 6049 // C++98 [class.union]p1: If a union contains a static data member, 6050 // the program is ill-formed. C++11 drops this restriction. 6051 if (RD->isUnion()) 6052 Diag(D.getIdentifierLoc(), 6053 getLangOpts().CPlusPlus11 6054 ? diag::warn_cxx98_compat_static_data_member_in_union 6055 : diag::ext_static_data_member_in_union) << Name; 6056 // We conservatively disallow static data members in anonymous structs. 6057 else if (!RD->getDeclName()) 6058 Diag(D.getIdentifierLoc(), 6059 diag::err_static_data_member_not_allowed_in_anon_struct) 6060 << Name << RD->isUnion(); 6061 } 6062 } 6063 6064 // Match up the template parameter lists with the scope specifier, then 6065 // determine whether we have a template or a template specialization. 6066 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6067 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6068 D.getCXXScopeSpec(), 6069 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6070 ? D.getName().TemplateId 6071 : nullptr, 6072 TemplateParamLists, 6073 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6074 6075 if (TemplateParams) { 6076 if (!TemplateParams->size() && 6077 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6078 // There is an extraneous 'template<>' for this variable. Complain 6079 // about it, but allow the declaration of the variable. 6080 Diag(TemplateParams->getTemplateLoc(), 6081 diag::err_template_variable_noparams) 6082 << II 6083 << SourceRange(TemplateParams->getTemplateLoc(), 6084 TemplateParams->getRAngleLoc()); 6085 TemplateParams = nullptr; 6086 } else { 6087 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6088 // This is an explicit specialization or a partial specialization. 6089 // FIXME: Check that we can declare a specialization here. 6090 IsVariableTemplateSpecialization = true; 6091 IsPartialSpecialization = TemplateParams->size() > 0; 6092 } else { // if (TemplateParams->size() > 0) 6093 // This is a template declaration. 6094 IsVariableTemplate = true; 6095 6096 // Check that we can declare a template here. 6097 if (CheckTemplateDeclScope(S, TemplateParams)) 6098 return nullptr; 6099 6100 // Only C++1y supports variable templates (N3651). 6101 Diag(D.getIdentifierLoc(), 6102 getLangOpts().CPlusPlus14 6103 ? diag::warn_cxx11_compat_variable_template 6104 : diag::ext_variable_template); 6105 } 6106 } 6107 } else { 6108 assert( 6109 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6110 "should have a 'template<>' for this decl"); 6111 } 6112 6113 if (IsVariableTemplateSpecialization) { 6114 SourceLocation TemplateKWLoc = 6115 TemplateParamLists.size() > 0 6116 ? TemplateParamLists[0]->getTemplateLoc() 6117 : SourceLocation(); 6118 DeclResult Res = ActOnVarTemplateSpecialization( 6119 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6120 IsPartialSpecialization); 6121 if (Res.isInvalid()) 6122 return nullptr; 6123 NewVD = cast<VarDecl>(Res.get()); 6124 AddToScope = false; 6125 } else if (D.isDecompositionDeclarator()) { 6126 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6127 D.getIdentifierLoc(), R, TInfo, SC, 6128 Bindings); 6129 } else 6130 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6131 D.getIdentifierLoc(), II, R, TInfo, SC); 6132 6133 // If this is supposed to be a variable template, create it as such. 6134 if (IsVariableTemplate) { 6135 NewTemplate = 6136 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6137 TemplateParams, NewVD); 6138 NewVD->setDescribedVarTemplate(NewTemplate); 6139 } 6140 6141 // If this decl has an auto type in need of deduction, make a note of the 6142 // Decl so we can diagnose uses of it in its own initializer. 6143 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6144 ParsingInitForAutoVars.insert(NewVD); 6145 6146 if (D.isInvalidType() || Invalid) { 6147 NewVD->setInvalidDecl(); 6148 if (NewTemplate) 6149 NewTemplate->setInvalidDecl(); 6150 } 6151 6152 SetNestedNameSpecifier(NewVD, D); 6153 6154 // If we have any template parameter lists that don't directly belong to 6155 // the variable (matching the scope specifier), store them. 6156 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6157 if (TemplateParamLists.size() > VDTemplateParamLists) 6158 NewVD->setTemplateParameterListsInfo( 6159 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6160 6161 if (D.getDeclSpec().isConstexprSpecified()) { 6162 NewVD->setConstexpr(true); 6163 // C++1z [dcl.spec.constexpr]p1: 6164 // A static data member declared with the constexpr specifier is 6165 // implicitly an inline variable. 6166 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6167 NewVD->setImplicitlyInline(); 6168 } 6169 6170 if (D.getDeclSpec().isConceptSpecified()) { 6171 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6172 VTD->setConcept(); 6173 6174 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6175 // be declared with the thread_local, inline, friend, or constexpr 6176 // specifiers, [...] 6177 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6178 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6179 diag::err_concept_decl_invalid_specifiers) 6180 << 0 << 0; 6181 NewVD->setInvalidDecl(true); 6182 } 6183 6184 if (D.getDeclSpec().isConstexprSpecified()) { 6185 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6186 diag::err_concept_decl_invalid_specifiers) 6187 << 0 << 3; 6188 NewVD->setInvalidDecl(true); 6189 } 6190 6191 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6192 // applied only to the definition of a function template or variable 6193 // template, declared in namespace scope. 6194 if (IsVariableTemplateSpecialization) { 6195 Diag(D.getDeclSpec().getConceptSpecLoc(), 6196 diag::err_concept_specified_specialization) 6197 << (IsPartialSpecialization ? 2 : 1); 6198 } 6199 6200 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6201 // following restrictions: 6202 // - The declared type shall have the type bool. 6203 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6204 !NewVD->isInvalidDecl()) { 6205 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6206 NewVD->setInvalidDecl(true); 6207 } 6208 } 6209 } 6210 6211 if (D.getDeclSpec().isInlineSpecified()) { 6212 if (!getLangOpts().CPlusPlus) { 6213 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6214 << 0; 6215 } else if (CurContext->isFunctionOrMethod()) { 6216 // 'inline' is not allowed on block scope variable declaration. 6217 Diag(D.getDeclSpec().getInlineSpecLoc(), 6218 diag::err_inline_declaration_block_scope) << Name 6219 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6220 } else { 6221 Diag(D.getDeclSpec().getInlineSpecLoc(), 6222 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6223 : diag::ext_inline_variable); 6224 NewVD->setInlineSpecified(); 6225 } 6226 } 6227 6228 // Set the lexical context. If the declarator has a C++ scope specifier, the 6229 // lexical context will be different from the semantic context. 6230 NewVD->setLexicalDeclContext(CurContext); 6231 if (NewTemplate) 6232 NewTemplate->setLexicalDeclContext(CurContext); 6233 6234 if (IsLocalExternDecl) { 6235 if (D.isDecompositionDeclarator()) 6236 for (auto *B : Bindings) 6237 B->setLocalExternDecl(); 6238 else 6239 NewVD->setLocalExternDecl(); 6240 } 6241 6242 bool EmitTLSUnsupportedError = false; 6243 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6244 // C++11 [dcl.stc]p4: 6245 // When thread_local is applied to a variable of block scope the 6246 // storage-class-specifier static is implied if it does not appear 6247 // explicitly. 6248 // Core issue: 'static' is not implied if the variable is declared 6249 // 'extern'. 6250 if (NewVD->hasLocalStorage() && 6251 (SCSpec != DeclSpec::SCS_unspecified || 6252 TSCS != DeclSpec::TSCS_thread_local || 6253 !DC->isFunctionOrMethod())) 6254 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6255 diag::err_thread_non_global) 6256 << DeclSpec::getSpecifierName(TSCS); 6257 else if (!Context.getTargetInfo().isTLSSupported()) { 6258 if (getLangOpts().CUDA) { 6259 // Postpone error emission until we've collected attributes required to 6260 // figure out whether it's a host or device variable and whether the 6261 // error should be ignored. 6262 EmitTLSUnsupportedError = true; 6263 // We still need to mark the variable as TLS so it shows up in AST with 6264 // proper storage class for other tools to use even if we're not going 6265 // to emit any code for it. 6266 NewVD->setTSCSpec(TSCS); 6267 } else 6268 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6269 diag::err_thread_unsupported); 6270 } else 6271 NewVD->setTSCSpec(TSCS); 6272 } 6273 6274 // C99 6.7.4p3 6275 // An inline definition of a function with external linkage shall 6276 // not contain a definition of a modifiable object with static or 6277 // thread storage duration... 6278 // We only apply this when the function is required to be defined 6279 // elsewhere, i.e. when the function is not 'extern inline'. Note 6280 // that a local variable with thread storage duration still has to 6281 // be marked 'static'. Also note that it's possible to get these 6282 // semantics in C++ using __attribute__((gnu_inline)). 6283 if (SC == SC_Static && S->getFnParent() != nullptr && 6284 !NewVD->getType().isConstQualified()) { 6285 FunctionDecl *CurFD = getCurFunctionDecl(); 6286 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6287 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6288 diag::warn_static_local_in_extern_inline); 6289 MaybeSuggestAddingStaticToDecl(CurFD); 6290 } 6291 } 6292 6293 if (D.getDeclSpec().isModulePrivateSpecified()) { 6294 if (IsVariableTemplateSpecialization) 6295 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6296 << (IsPartialSpecialization ? 1 : 0) 6297 << FixItHint::CreateRemoval( 6298 D.getDeclSpec().getModulePrivateSpecLoc()); 6299 else if (IsExplicitSpecialization) 6300 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6301 << 2 6302 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6303 else if (NewVD->hasLocalStorage()) 6304 Diag(NewVD->getLocation(), diag::err_module_private_local) 6305 << 0 << NewVD->getDeclName() 6306 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6307 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6308 else { 6309 NewVD->setModulePrivate(); 6310 if (NewTemplate) 6311 NewTemplate->setModulePrivate(); 6312 for (auto *B : Bindings) 6313 B->setModulePrivate(); 6314 } 6315 } 6316 6317 // Handle attributes prior to checking for duplicates in MergeVarDecl 6318 ProcessDeclAttributes(S, NewVD, D); 6319 6320 if (getLangOpts().CUDA) { 6321 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6322 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6323 diag::err_thread_unsupported); 6324 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6325 // storage [duration]." 6326 if (SC == SC_None && S->getFnParent() != nullptr && 6327 (NewVD->hasAttr<CUDASharedAttr>() || 6328 NewVD->hasAttr<CUDAConstantAttr>())) { 6329 NewVD->setStorageClass(SC_Static); 6330 } 6331 } 6332 6333 // Ensure that dllimport globals without explicit storage class are treated as 6334 // extern. The storage class is set above using parsed attributes. Now we can 6335 // check the VarDecl itself. 6336 assert(!NewVD->hasAttr<DLLImportAttr>() || 6337 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6338 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6339 6340 // In auto-retain/release, infer strong retension for variables of 6341 // retainable type. 6342 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6343 NewVD->setInvalidDecl(); 6344 6345 // Handle GNU asm-label extension (encoded as an attribute). 6346 if (Expr *E = (Expr*)D.getAsmLabel()) { 6347 // The parser guarantees this is a string. 6348 StringLiteral *SE = cast<StringLiteral>(E); 6349 StringRef Label = SE->getString(); 6350 if (S->getFnParent() != nullptr) { 6351 switch (SC) { 6352 case SC_None: 6353 case SC_Auto: 6354 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6355 break; 6356 case SC_Register: 6357 // Local Named register 6358 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6359 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6360 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6361 break; 6362 case SC_Static: 6363 case SC_Extern: 6364 case SC_PrivateExtern: 6365 break; 6366 } 6367 } else if (SC == SC_Register) { 6368 // Global Named register 6369 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6370 const auto &TI = Context.getTargetInfo(); 6371 bool HasSizeMismatch; 6372 6373 if (!TI.isValidGCCRegisterName(Label)) 6374 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6375 else if (!TI.validateGlobalRegisterVariable(Label, 6376 Context.getTypeSize(R), 6377 HasSizeMismatch)) 6378 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6379 else if (HasSizeMismatch) 6380 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6381 } 6382 6383 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6384 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6385 NewVD->setInvalidDecl(true); 6386 } 6387 } 6388 6389 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6390 Context, Label, 0)); 6391 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6392 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6393 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6394 if (I != ExtnameUndeclaredIdentifiers.end()) { 6395 if (isDeclExternC(NewVD)) { 6396 NewVD->addAttr(I->second); 6397 ExtnameUndeclaredIdentifiers.erase(I); 6398 } else 6399 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6400 << /*Variable*/1 << NewVD; 6401 } 6402 } 6403 6404 // Diagnose shadowed variables before filtering for scope. 6405 if (D.getCXXScopeSpec().isEmpty()) 6406 CheckShadow(S, NewVD, Previous); 6407 6408 // Don't consider existing declarations that are in a different 6409 // scope and are out-of-semantic-context declarations (if the new 6410 // declaration has linkage). 6411 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6412 D.getCXXScopeSpec().isNotEmpty() || 6413 IsExplicitSpecialization || 6414 IsVariableTemplateSpecialization); 6415 6416 // Check whether the previous declaration is in the same block scope. This 6417 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6418 if (getLangOpts().CPlusPlus && 6419 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6420 NewVD->setPreviousDeclInSameBlockScope( 6421 Previous.isSingleResult() && !Previous.isShadowed() && 6422 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6423 6424 if (!getLangOpts().CPlusPlus) { 6425 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6426 } else { 6427 // If this is an explicit specialization of a static data member, check it. 6428 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6429 CheckMemberSpecialization(NewVD, Previous)) 6430 NewVD->setInvalidDecl(); 6431 6432 // Merge the decl with the existing one if appropriate. 6433 if (!Previous.empty()) { 6434 if (Previous.isSingleResult() && 6435 isa<FieldDecl>(Previous.getFoundDecl()) && 6436 D.getCXXScopeSpec().isSet()) { 6437 // The user tried to define a non-static data member 6438 // out-of-line (C++ [dcl.meaning]p1). 6439 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6440 << D.getCXXScopeSpec().getRange(); 6441 Previous.clear(); 6442 NewVD->setInvalidDecl(); 6443 } 6444 } else if (D.getCXXScopeSpec().isSet()) { 6445 // No previous declaration in the qualifying scope. 6446 Diag(D.getIdentifierLoc(), diag::err_no_member) 6447 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6448 << D.getCXXScopeSpec().getRange(); 6449 NewVD->setInvalidDecl(); 6450 } 6451 6452 if (!IsVariableTemplateSpecialization) 6453 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6454 6455 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6456 // an explicit specialization (14.8.3) or a partial specialization of a 6457 // concept definition. 6458 if (IsVariableTemplateSpecialization && 6459 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6460 Previous.isSingleResult()) { 6461 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6462 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6463 if (VarTmpl->isConcept()) { 6464 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6465 << 1 /*variable*/ 6466 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6467 : 1 /*explicitly specialized*/); 6468 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6469 NewVD->setInvalidDecl(); 6470 } 6471 } 6472 } 6473 6474 if (NewTemplate) { 6475 VarTemplateDecl *PrevVarTemplate = 6476 NewVD->getPreviousDecl() 6477 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6478 : nullptr; 6479 6480 // Check the template parameter list of this declaration, possibly 6481 // merging in the template parameter list from the previous variable 6482 // template declaration. 6483 if (CheckTemplateParameterList( 6484 TemplateParams, 6485 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6486 : nullptr, 6487 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6488 DC->isDependentContext()) 6489 ? TPC_ClassTemplateMember 6490 : TPC_VarTemplate)) 6491 NewVD->setInvalidDecl(); 6492 6493 // If we are providing an explicit specialization of a static variable 6494 // template, make a note of that. 6495 if (PrevVarTemplate && 6496 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6497 PrevVarTemplate->setMemberSpecialization(); 6498 } 6499 } 6500 6501 ProcessPragmaWeak(S, NewVD); 6502 6503 // If this is the first declaration of an extern C variable, update 6504 // the map of such variables. 6505 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6506 isIncompleteDeclExternC(*this, NewVD)) 6507 RegisterLocallyScopedExternCDecl(NewVD, S); 6508 6509 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6510 Decl *ManglingContextDecl; 6511 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6512 NewVD->getDeclContext(), ManglingContextDecl)) { 6513 Context.setManglingNumber( 6514 NewVD, MCtx->getManglingNumber( 6515 NewVD, getMSManglingNumber(getLangOpts(), S))); 6516 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6517 } 6518 } 6519 6520 // Special handling of variable named 'main'. 6521 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6522 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6523 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6524 6525 // C++ [basic.start.main]p3 6526 // A program that declares a variable main at global scope is ill-formed. 6527 if (getLangOpts().CPlusPlus) 6528 Diag(D.getLocStart(), diag::err_main_global_variable); 6529 6530 // In C, and external-linkage variable named main results in undefined 6531 // behavior. 6532 else if (NewVD->hasExternalFormalLinkage()) 6533 Diag(D.getLocStart(), diag::warn_main_redefined); 6534 } 6535 6536 if (D.isRedeclaration() && !Previous.empty()) { 6537 checkDLLAttributeRedeclaration( 6538 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6539 IsExplicitSpecialization, D.isFunctionDefinition()); 6540 } 6541 6542 if (NewTemplate) { 6543 if (NewVD->isInvalidDecl()) 6544 NewTemplate->setInvalidDecl(); 6545 ActOnDocumentableDecl(NewTemplate); 6546 return NewTemplate; 6547 } 6548 6549 return NewVD; 6550 } 6551 6552 /// Enum describing the %select options in diag::warn_decl_shadow. 6553 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6554 6555 /// Determine what kind of declaration we're shadowing. 6556 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6557 const DeclContext *OldDC) { 6558 if (isa<RecordDecl>(OldDC)) 6559 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6560 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6561 } 6562 6563 /// \brief Diagnose variable or built-in function shadowing. Implements 6564 /// -Wshadow. 6565 /// 6566 /// This method is called whenever a VarDecl is added to a "useful" 6567 /// scope. 6568 /// 6569 /// \param S the scope in which the shadowing name is being declared 6570 /// \param R the lookup of the name 6571 /// 6572 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6573 // Return if warning is ignored. 6574 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6575 return; 6576 6577 // Don't diagnose declarations at file scope. 6578 if (D->hasGlobalStorage()) 6579 return; 6580 6581 DeclContext *NewDC = D->getDeclContext(); 6582 6583 // Only diagnose if we're shadowing an unambiguous field or variable. 6584 if (R.getResultKind() != LookupResult::Found) 6585 return; 6586 6587 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6588 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6589 return; 6590 6591 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6592 // Fields are not shadowed by variables in C++ static methods. 6593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6594 if (MD->isStatic()) 6595 return; 6596 6597 // Fields shadowed by constructor parameters are a special case. Usually 6598 // the constructor initializes the field with the parameter. 6599 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6600 // Remember that this was shadowed so we can either warn about its 6601 // modification or its existence depending on warning settings. 6602 D = D->getCanonicalDecl(); 6603 ShadowingDecls.insert({D, FD}); 6604 return; 6605 } 6606 } 6607 6608 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6609 if (shadowedVar->isExternC()) { 6610 // For shadowing external vars, make sure that we point to the global 6611 // declaration, not a locally scoped extern declaration. 6612 for (auto I : shadowedVar->redecls()) 6613 if (I->isFileVarDecl()) { 6614 ShadowedDecl = I; 6615 break; 6616 } 6617 } 6618 6619 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6620 6621 // Only warn about certain kinds of shadowing for class members. 6622 if (NewDC && NewDC->isRecord()) { 6623 // In particular, don't warn about shadowing non-class members. 6624 if (!OldDC->isRecord()) 6625 return; 6626 6627 // TODO: should we warn about static data members shadowing 6628 // static data members from base classes? 6629 6630 // TODO: don't diagnose for inaccessible shadowed members. 6631 // This is hard to do perfectly because we might friend the 6632 // shadowing context, but that's just a false negative. 6633 } 6634 6635 6636 DeclarationName Name = R.getLookupName(); 6637 6638 // Emit warning and note. 6639 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6640 return; 6641 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6642 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6643 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6644 } 6645 6646 /// \brief Check -Wshadow without the advantage of a previous lookup. 6647 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6648 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6649 return; 6650 6651 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6652 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6653 LookupName(R, S); 6654 CheckShadow(S, D, R); 6655 } 6656 6657 /// Check if 'E', which is an expression that is about to be modified, refers 6658 /// to a constructor parameter that shadows a field. 6659 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6660 // Quickly ignore expressions that can't be shadowing ctor parameters. 6661 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6662 return; 6663 E = E->IgnoreParenImpCasts(); 6664 auto *DRE = dyn_cast<DeclRefExpr>(E); 6665 if (!DRE) 6666 return; 6667 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6668 auto I = ShadowingDecls.find(D); 6669 if (I == ShadowingDecls.end()) 6670 return; 6671 const NamedDecl *ShadowedDecl = I->second; 6672 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6673 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6674 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6675 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6676 6677 // Avoid issuing multiple warnings about the same decl. 6678 ShadowingDecls.erase(I); 6679 } 6680 6681 /// Check for conflict between this global or extern "C" declaration and 6682 /// previous global or extern "C" declarations. This is only used in C++. 6683 template<typename T> 6684 static bool checkGlobalOrExternCConflict( 6685 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6686 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6687 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6688 6689 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6690 // The common case: this global doesn't conflict with any extern "C" 6691 // declaration. 6692 return false; 6693 } 6694 6695 if (Prev) { 6696 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6697 // Both the old and new declarations have C language linkage. This is a 6698 // redeclaration. 6699 Previous.clear(); 6700 Previous.addDecl(Prev); 6701 return true; 6702 } 6703 6704 // This is a global, non-extern "C" declaration, and there is a previous 6705 // non-global extern "C" declaration. Diagnose if this is a variable 6706 // declaration. 6707 if (!isa<VarDecl>(ND)) 6708 return false; 6709 } else { 6710 // The declaration is extern "C". Check for any declaration in the 6711 // translation unit which might conflict. 6712 if (IsGlobal) { 6713 // We have already performed the lookup into the translation unit. 6714 IsGlobal = false; 6715 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6716 I != E; ++I) { 6717 if (isa<VarDecl>(*I)) { 6718 Prev = *I; 6719 break; 6720 } 6721 } 6722 } else { 6723 DeclContext::lookup_result R = 6724 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6725 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6726 I != E; ++I) { 6727 if (isa<VarDecl>(*I)) { 6728 Prev = *I; 6729 break; 6730 } 6731 // FIXME: If we have any other entity with this name in global scope, 6732 // the declaration is ill-formed, but that is a defect: it breaks the 6733 // 'stat' hack, for instance. Only variables can have mangled name 6734 // clashes with extern "C" declarations, so only they deserve a 6735 // diagnostic. 6736 } 6737 } 6738 6739 if (!Prev) 6740 return false; 6741 } 6742 6743 // Use the first declaration's location to ensure we point at something which 6744 // is lexically inside an extern "C" linkage-spec. 6745 assert(Prev && "should have found a previous declaration to diagnose"); 6746 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6747 Prev = FD->getFirstDecl(); 6748 else 6749 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6750 6751 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6752 << IsGlobal << ND; 6753 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6754 << IsGlobal; 6755 return false; 6756 } 6757 6758 /// Apply special rules for handling extern "C" declarations. Returns \c true 6759 /// if we have found that this is a redeclaration of some prior entity. 6760 /// 6761 /// Per C++ [dcl.link]p6: 6762 /// Two declarations [for a function or variable] with C language linkage 6763 /// with the same name that appear in different scopes refer to the same 6764 /// [entity]. An entity with C language linkage shall not be declared with 6765 /// the same name as an entity in global scope. 6766 template<typename T> 6767 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6768 LookupResult &Previous) { 6769 if (!S.getLangOpts().CPlusPlus) { 6770 // In C, when declaring a global variable, look for a corresponding 'extern' 6771 // variable declared in function scope. We don't need this in C++, because 6772 // we find local extern decls in the surrounding file-scope DeclContext. 6773 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6774 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6775 Previous.clear(); 6776 Previous.addDecl(Prev); 6777 return true; 6778 } 6779 } 6780 return false; 6781 } 6782 6783 // A declaration in the translation unit can conflict with an extern "C" 6784 // declaration. 6785 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6786 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6787 6788 // An extern "C" declaration can conflict with a declaration in the 6789 // translation unit or can be a redeclaration of an extern "C" declaration 6790 // in another scope. 6791 if (isIncompleteDeclExternC(S,ND)) 6792 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6793 6794 // Neither global nor extern "C": nothing to do. 6795 return false; 6796 } 6797 6798 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6799 // If the decl is already known invalid, don't check it. 6800 if (NewVD->isInvalidDecl()) 6801 return; 6802 6803 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6804 QualType T = TInfo->getType(); 6805 6806 // Defer checking an 'auto' type until its initializer is attached. 6807 if (T->isUndeducedType()) 6808 return; 6809 6810 if (NewVD->hasAttrs()) 6811 CheckAlignasUnderalignment(NewVD); 6812 6813 if (T->isObjCObjectType()) { 6814 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6815 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6816 T = Context.getObjCObjectPointerType(T); 6817 NewVD->setType(T); 6818 } 6819 6820 // Emit an error if an address space was applied to decl with local storage. 6821 // This includes arrays of objects with address space qualifiers, but not 6822 // automatic variables that point to other address spaces. 6823 // ISO/IEC TR 18037 S5.1.2 6824 if (!getLangOpts().OpenCL 6825 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6826 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6827 NewVD->setInvalidDecl(); 6828 return; 6829 } 6830 6831 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6832 // scope. 6833 if (getLangOpts().OpenCLVersion == 120 && 6834 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6835 NewVD->isStaticLocal()) { 6836 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6837 NewVD->setInvalidDecl(); 6838 return; 6839 } 6840 6841 if (getLangOpts().OpenCL) { 6842 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6843 if (NewVD->hasAttr<BlocksAttr>()) { 6844 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6845 return; 6846 } 6847 6848 if (T->isBlockPointerType()) { 6849 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6850 // can't use 'extern' storage class. 6851 if (!T.isConstQualified()) { 6852 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6853 << 0 /*const*/; 6854 NewVD->setInvalidDecl(); 6855 return; 6856 } 6857 if (NewVD->hasExternalStorage()) { 6858 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6859 NewVD->setInvalidDecl(); 6860 return; 6861 } 6862 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported. 6863 // TODO: this check is not enough as it doesn't diagnose the typedef 6864 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>(); 6865 const FunctionProtoType *FTy = 6866 BlkTy->getPointeeType()->getAs<FunctionProtoType>(); 6867 if (FTy && FTy->isVariadic()) { 6868 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic) 6869 << T << NewVD->getSourceRange(); 6870 NewVD->setInvalidDecl(); 6871 return; 6872 } 6873 } 6874 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6875 // __constant address space. 6876 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6877 // variables inside a function can also be declared in the global 6878 // address space. 6879 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6880 NewVD->hasExternalStorage()) { 6881 if (!T->isSamplerT() && 6882 !(T.getAddressSpace() == LangAS::opencl_constant || 6883 (T.getAddressSpace() == LangAS::opencl_global && 6884 getLangOpts().OpenCLVersion == 200))) { 6885 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6886 if (getLangOpts().OpenCLVersion == 200) 6887 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6888 << Scope << "global or constant"; 6889 else 6890 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6891 << Scope << "constant"; 6892 NewVD->setInvalidDecl(); 6893 return; 6894 } 6895 } else { 6896 if (T.getAddressSpace() == LangAS::opencl_global) { 6897 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6898 << 1 /*is any function*/ << "global"; 6899 NewVD->setInvalidDecl(); 6900 return; 6901 } 6902 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6903 // in functions. 6904 if (T.getAddressSpace() == LangAS::opencl_constant || 6905 T.getAddressSpace() == LangAS::opencl_local) { 6906 FunctionDecl *FD = getCurFunctionDecl(); 6907 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6908 if (T.getAddressSpace() == LangAS::opencl_constant) 6909 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6910 << 0 /*non-kernel only*/ << "constant"; 6911 else 6912 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6913 << 0 /*non-kernel only*/ << "local"; 6914 NewVD->setInvalidDecl(); 6915 return; 6916 } 6917 } 6918 } 6919 } 6920 6921 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6922 && !NewVD->hasAttr<BlocksAttr>()) { 6923 if (getLangOpts().getGC() != LangOptions::NonGC) 6924 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6925 else { 6926 assert(!getLangOpts().ObjCAutoRefCount); 6927 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6928 } 6929 } 6930 6931 bool isVM = T->isVariablyModifiedType(); 6932 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6933 NewVD->hasAttr<BlocksAttr>()) 6934 getCurFunction()->setHasBranchProtectedScope(); 6935 6936 if ((isVM && NewVD->hasLinkage()) || 6937 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6938 bool SizeIsNegative; 6939 llvm::APSInt Oversized; 6940 TypeSourceInfo *FixedTInfo = 6941 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6942 SizeIsNegative, Oversized); 6943 if (!FixedTInfo && T->isVariableArrayType()) { 6944 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6945 // FIXME: This won't give the correct result for 6946 // int a[10][n]; 6947 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6948 6949 if (NewVD->isFileVarDecl()) 6950 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6951 << SizeRange; 6952 else if (NewVD->isStaticLocal()) 6953 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6954 << SizeRange; 6955 else 6956 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6957 << SizeRange; 6958 NewVD->setInvalidDecl(); 6959 return; 6960 } 6961 6962 if (!FixedTInfo) { 6963 if (NewVD->isFileVarDecl()) 6964 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6965 else 6966 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6967 NewVD->setInvalidDecl(); 6968 return; 6969 } 6970 6971 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6972 NewVD->setType(FixedTInfo->getType()); 6973 NewVD->setTypeSourceInfo(FixedTInfo); 6974 } 6975 6976 if (T->isVoidType()) { 6977 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6978 // of objects and functions. 6979 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6980 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6981 << T; 6982 NewVD->setInvalidDecl(); 6983 return; 6984 } 6985 } 6986 6987 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6988 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6989 NewVD->setInvalidDecl(); 6990 return; 6991 } 6992 6993 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6994 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6995 NewVD->setInvalidDecl(); 6996 return; 6997 } 6998 6999 if (NewVD->isConstexpr() && !T->isDependentType() && 7000 RequireLiteralType(NewVD->getLocation(), T, 7001 diag::err_constexpr_var_non_literal)) { 7002 NewVD->setInvalidDecl(); 7003 return; 7004 } 7005 } 7006 7007 /// \brief Perform semantic checking on a newly-created variable 7008 /// declaration. 7009 /// 7010 /// This routine performs all of the type-checking required for a 7011 /// variable declaration once it has been built. It is used both to 7012 /// check variables after they have been parsed and their declarators 7013 /// have been translated into a declaration, and to check variables 7014 /// that have been instantiated from a template. 7015 /// 7016 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7017 /// 7018 /// Returns true if the variable declaration is a redeclaration. 7019 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7020 CheckVariableDeclarationType(NewVD); 7021 7022 // If the decl is already known invalid, don't check it. 7023 if (NewVD->isInvalidDecl()) 7024 return false; 7025 7026 // If we did not find anything by this name, look for a non-visible 7027 // extern "C" declaration with the same name. 7028 if (Previous.empty() && 7029 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7030 Previous.setShadowed(); 7031 7032 if (!Previous.empty()) { 7033 MergeVarDecl(NewVD, Previous); 7034 return true; 7035 } 7036 return false; 7037 } 7038 7039 namespace { 7040 struct FindOverriddenMethod { 7041 Sema *S; 7042 CXXMethodDecl *Method; 7043 7044 /// Member lookup function that determines whether a given C++ 7045 /// method overrides a method in a base class, to be used with 7046 /// CXXRecordDecl::lookupInBases(). 7047 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7048 RecordDecl *BaseRecord = 7049 Specifier->getType()->getAs<RecordType>()->getDecl(); 7050 7051 DeclarationName Name = Method->getDeclName(); 7052 7053 // FIXME: Do we care about other names here too? 7054 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7055 // We really want to find the base class destructor here. 7056 QualType T = S->Context.getTypeDeclType(BaseRecord); 7057 CanQualType CT = S->Context.getCanonicalType(T); 7058 7059 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7060 } 7061 7062 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7063 Path.Decls = Path.Decls.slice(1)) { 7064 NamedDecl *D = Path.Decls.front(); 7065 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7066 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7067 return true; 7068 } 7069 } 7070 7071 return false; 7072 } 7073 }; 7074 7075 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7076 } // end anonymous namespace 7077 7078 /// \brief Report an error regarding overriding, along with any relevant 7079 /// overriden methods. 7080 /// 7081 /// \param DiagID the primary error to report. 7082 /// \param MD the overriding method. 7083 /// \param OEK which overrides to include as notes. 7084 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7085 OverrideErrorKind OEK = OEK_All) { 7086 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7087 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7088 E = MD->end_overridden_methods(); 7089 I != E; ++I) { 7090 // This check (& the OEK parameter) could be replaced by a predicate, but 7091 // without lambdas that would be overkill. This is still nicer than writing 7092 // out the diag loop 3 times. 7093 if ((OEK == OEK_All) || 7094 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7095 (OEK == OEK_Deleted && (*I)->isDeleted())) 7096 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7097 } 7098 } 7099 7100 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7101 /// and if so, check that it's a valid override and remember it. 7102 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7103 // Look for methods in base classes that this method might override. 7104 CXXBasePaths Paths; 7105 FindOverriddenMethod FOM; 7106 FOM.Method = MD; 7107 FOM.S = this; 7108 bool hasDeletedOverridenMethods = false; 7109 bool hasNonDeletedOverridenMethods = false; 7110 bool AddedAny = false; 7111 if (DC->lookupInBases(FOM, Paths)) { 7112 for (auto *I : Paths.found_decls()) { 7113 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7114 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7115 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7116 !CheckOverridingFunctionAttributes(MD, OldMD) && 7117 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7118 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7119 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7120 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7121 AddedAny = true; 7122 } 7123 } 7124 } 7125 } 7126 7127 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7128 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7129 } 7130 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7131 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7132 } 7133 7134 return AddedAny; 7135 } 7136 7137 namespace { 7138 // Struct for holding all of the extra arguments needed by 7139 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7140 struct ActOnFDArgs { 7141 Scope *S; 7142 Declarator &D; 7143 MultiTemplateParamsArg TemplateParamLists; 7144 bool AddToScope; 7145 }; 7146 } // end anonymous namespace 7147 7148 namespace { 7149 7150 // Callback to only accept typo corrections that have a non-zero edit distance. 7151 // Also only accept corrections that have the same parent decl. 7152 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7153 public: 7154 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7155 CXXRecordDecl *Parent) 7156 : Context(Context), OriginalFD(TypoFD), 7157 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7158 7159 bool ValidateCandidate(const TypoCorrection &candidate) override { 7160 if (candidate.getEditDistance() == 0) 7161 return false; 7162 7163 SmallVector<unsigned, 1> MismatchedParams; 7164 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7165 CDeclEnd = candidate.end(); 7166 CDecl != CDeclEnd; ++CDecl) { 7167 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7168 7169 if (FD && !FD->hasBody() && 7170 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7171 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7172 CXXRecordDecl *Parent = MD->getParent(); 7173 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7174 return true; 7175 } else if (!ExpectedParent) { 7176 return true; 7177 } 7178 } 7179 } 7180 7181 return false; 7182 } 7183 7184 private: 7185 ASTContext &Context; 7186 FunctionDecl *OriginalFD; 7187 CXXRecordDecl *ExpectedParent; 7188 }; 7189 7190 } // end anonymous namespace 7191 7192 /// \brief Generate diagnostics for an invalid function redeclaration. 7193 /// 7194 /// This routine handles generating the diagnostic messages for an invalid 7195 /// function redeclaration, including finding possible similar declarations 7196 /// or performing typo correction if there are no previous declarations with 7197 /// the same name. 7198 /// 7199 /// Returns a NamedDecl iff typo correction was performed and substituting in 7200 /// the new declaration name does not cause new errors. 7201 static NamedDecl *DiagnoseInvalidRedeclaration( 7202 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7203 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7204 DeclarationName Name = NewFD->getDeclName(); 7205 DeclContext *NewDC = NewFD->getDeclContext(); 7206 SmallVector<unsigned, 1> MismatchedParams; 7207 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7208 TypoCorrection Correction; 7209 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7210 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7211 : diag::err_member_decl_does_not_match; 7212 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7213 IsLocalFriend ? Sema::LookupLocalFriendName 7214 : Sema::LookupOrdinaryName, 7215 Sema::ForRedeclaration); 7216 7217 NewFD->setInvalidDecl(); 7218 if (IsLocalFriend) 7219 SemaRef.LookupName(Prev, S); 7220 else 7221 SemaRef.LookupQualifiedName(Prev, NewDC); 7222 assert(!Prev.isAmbiguous() && 7223 "Cannot have an ambiguity in previous-declaration lookup"); 7224 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7225 if (!Prev.empty()) { 7226 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7227 Func != FuncEnd; ++Func) { 7228 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7229 if (FD && 7230 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7231 // Add 1 to the index so that 0 can mean the mismatch didn't 7232 // involve a parameter 7233 unsigned ParamNum = 7234 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7235 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7236 } 7237 } 7238 // If the qualified name lookup yielded nothing, try typo correction 7239 } else if ((Correction = SemaRef.CorrectTypo( 7240 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7241 &ExtraArgs.D.getCXXScopeSpec(), 7242 llvm::make_unique<DifferentNameValidatorCCC>( 7243 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7244 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7245 // Set up everything for the call to ActOnFunctionDeclarator 7246 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7247 ExtraArgs.D.getIdentifierLoc()); 7248 Previous.clear(); 7249 Previous.setLookupName(Correction.getCorrection()); 7250 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7251 CDeclEnd = Correction.end(); 7252 CDecl != CDeclEnd; ++CDecl) { 7253 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7254 if (FD && !FD->hasBody() && 7255 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7256 Previous.addDecl(FD); 7257 } 7258 } 7259 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7260 7261 NamedDecl *Result; 7262 // Retry building the function declaration with the new previous 7263 // declarations, and with errors suppressed. 7264 { 7265 // Trap errors. 7266 Sema::SFINAETrap Trap(SemaRef); 7267 7268 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7269 // pieces need to verify the typo-corrected C++ declaration and hopefully 7270 // eliminate the need for the parameter pack ExtraArgs. 7271 Result = SemaRef.ActOnFunctionDeclarator( 7272 ExtraArgs.S, ExtraArgs.D, 7273 Correction.getCorrectionDecl()->getDeclContext(), 7274 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7275 ExtraArgs.AddToScope); 7276 7277 if (Trap.hasErrorOccurred()) 7278 Result = nullptr; 7279 } 7280 7281 if (Result) { 7282 // Determine which correction we picked. 7283 Decl *Canonical = Result->getCanonicalDecl(); 7284 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7285 I != E; ++I) 7286 if ((*I)->getCanonicalDecl() == Canonical) 7287 Correction.setCorrectionDecl(*I); 7288 7289 SemaRef.diagnoseTypo( 7290 Correction, 7291 SemaRef.PDiag(IsLocalFriend 7292 ? diag::err_no_matching_local_friend_suggest 7293 : diag::err_member_decl_does_not_match_suggest) 7294 << Name << NewDC << IsDefinition); 7295 return Result; 7296 } 7297 7298 // Pretend the typo correction never occurred 7299 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7300 ExtraArgs.D.getIdentifierLoc()); 7301 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7302 Previous.clear(); 7303 Previous.setLookupName(Name); 7304 } 7305 7306 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7307 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7308 7309 bool NewFDisConst = false; 7310 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7311 NewFDisConst = NewMD->isConst(); 7312 7313 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7314 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7315 NearMatch != NearMatchEnd; ++NearMatch) { 7316 FunctionDecl *FD = NearMatch->first; 7317 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7318 bool FDisConst = MD && MD->isConst(); 7319 bool IsMember = MD || !IsLocalFriend; 7320 7321 // FIXME: These notes are poorly worded for the local friend case. 7322 if (unsigned Idx = NearMatch->second) { 7323 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7324 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7325 if (Loc.isInvalid()) Loc = FD->getLocation(); 7326 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7327 : diag::note_local_decl_close_param_match) 7328 << Idx << FDParam->getType() 7329 << NewFD->getParamDecl(Idx - 1)->getType(); 7330 } else if (FDisConst != NewFDisConst) { 7331 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7332 << NewFDisConst << FD->getSourceRange().getEnd(); 7333 } else 7334 SemaRef.Diag(FD->getLocation(), 7335 IsMember ? diag::note_member_def_close_match 7336 : diag::note_local_decl_close_match); 7337 } 7338 return nullptr; 7339 } 7340 7341 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7342 switch (D.getDeclSpec().getStorageClassSpec()) { 7343 default: llvm_unreachable("Unknown storage class!"); 7344 case DeclSpec::SCS_auto: 7345 case DeclSpec::SCS_register: 7346 case DeclSpec::SCS_mutable: 7347 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7348 diag::err_typecheck_sclass_func); 7349 D.setInvalidType(); 7350 break; 7351 case DeclSpec::SCS_unspecified: break; 7352 case DeclSpec::SCS_extern: 7353 if (D.getDeclSpec().isExternInLinkageSpec()) 7354 return SC_None; 7355 return SC_Extern; 7356 case DeclSpec::SCS_static: { 7357 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7358 // C99 6.7.1p5: 7359 // The declaration of an identifier for a function that has 7360 // block scope shall have no explicit storage-class specifier 7361 // other than extern 7362 // See also (C++ [dcl.stc]p4). 7363 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7364 diag::err_static_block_func); 7365 break; 7366 } else 7367 return SC_Static; 7368 } 7369 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7370 } 7371 7372 // No explicit storage class has already been returned 7373 return SC_None; 7374 } 7375 7376 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7377 DeclContext *DC, QualType &R, 7378 TypeSourceInfo *TInfo, 7379 StorageClass SC, 7380 bool &IsVirtualOkay) { 7381 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7382 DeclarationName Name = NameInfo.getName(); 7383 7384 FunctionDecl *NewFD = nullptr; 7385 bool isInline = D.getDeclSpec().isInlineSpecified(); 7386 7387 if (!SemaRef.getLangOpts().CPlusPlus) { 7388 // Determine whether the function was written with a 7389 // prototype. This true when: 7390 // - there is a prototype in the declarator, or 7391 // - the type R of the function is some kind of typedef or other reference 7392 // to a type name (which eventually refers to a function type). 7393 bool HasPrototype = 7394 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7395 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7396 7397 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7398 D.getLocStart(), NameInfo, R, 7399 TInfo, SC, isInline, 7400 HasPrototype, false); 7401 if (D.isInvalidType()) 7402 NewFD->setInvalidDecl(); 7403 7404 return NewFD; 7405 } 7406 7407 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7408 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7409 7410 // Check that the return type is not an abstract class type. 7411 // For record types, this is done by the AbstractClassUsageDiagnoser once 7412 // the class has been completely parsed. 7413 if (!DC->isRecord() && 7414 SemaRef.RequireNonAbstractType( 7415 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7416 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7417 D.setInvalidType(); 7418 7419 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7420 // This is a C++ constructor declaration. 7421 assert(DC->isRecord() && 7422 "Constructors can only be declared in a member context"); 7423 7424 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7425 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7426 D.getLocStart(), NameInfo, 7427 R, TInfo, isExplicit, isInline, 7428 /*isImplicitlyDeclared=*/false, 7429 isConstexpr); 7430 7431 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7432 // This is a C++ destructor declaration. 7433 if (DC->isRecord()) { 7434 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7435 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7436 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7437 SemaRef.Context, Record, 7438 D.getLocStart(), 7439 NameInfo, R, TInfo, isInline, 7440 /*isImplicitlyDeclared=*/false); 7441 7442 // If the class is complete, then we now create the implicit exception 7443 // specification. If the class is incomplete or dependent, we can't do 7444 // it yet. 7445 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7446 Record->getDefinition() && !Record->isBeingDefined() && 7447 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7448 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7449 } 7450 7451 IsVirtualOkay = true; 7452 return NewDD; 7453 7454 } else { 7455 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7456 D.setInvalidType(); 7457 7458 // Create a FunctionDecl to satisfy the function definition parsing 7459 // code path. 7460 return FunctionDecl::Create(SemaRef.Context, DC, 7461 D.getLocStart(), 7462 D.getIdentifierLoc(), Name, R, TInfo, 7463 SC, isInline, 7464 /*hasPrototype=*/true, isConstexpr); 7465 } 7466 7467 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7468 if (!DC->isRecord()) { 7469 SemaRef.Diag(D.getIdentifierLoc(), 7470 diag::err_conv_function_not_member); 7471 return nullptr; 7472 } 7473 7474 SemaRef.CheckConversionDeclarator(D, R, SC); 7475 IsVirtualOkay = true; 7476 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7477 D.getLocStart(), NameInfo, 7478 R, TInfo, isInline, isExplicit, 7479 isConstexpr, SourceLocation()); 7480 7481 } else if (DC->isRecord()) { 7482 // If the name of the function is the same as the name of the record, 7483 // then this must be an invalid constructor that has a return type. 7484 // (The parser checks for a return type and makes the declarator a 7485 // constructor if it has no return type). 7486 if (Name.getAsIdentifierInfo() && 7487 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7488 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7489 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7490 << SourceRange(D.getIdentifierLoc()); 7491 return nullptr; 7492 } 7493 7494 // This is a C++ method declaration. 7495 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7496 cast<CXXRecordDecl>(DC), 7497 D.getLocStart(), NameInfo, R, 7498 TInfo, SC, isInline, 7499 isConstexpr, SourceLocation()); 7500 IsVirtualOkay = !Ret->isStatic(); 7501 return Ret; 7502 } else { 7503 bool isFriend = 7504 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7505 if (!isFriend && SemaRef.CurContext->isRecord()) 7506 return nullptr; 7507 7508 // Determine whether the function was written with a 7509 // prototype. This true when: 7510 // - we're in C++ (where every function has a prototype), 7511 return FunctionDecl::Create(SemaRef.Context, DC, 7512 D.getLocStart(), 7513 NameInfo, R, TInfo, SC, isInline, 7514 true/*HasPrototype*/, isConstexpr); 7515 } 7516 } 7517 7518 enum OpenCLParamType { 7519 ValidKernelParam, 7520 PtrPtrKernelParam, 7521 PtrKernelParam, 7522 PrivatePtrKernelParam, 7523 InvalidKernelParam, 7524 RecordKernelParam 7525 }; 7526 7527 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 7528 if (PT->isPointerType()) { 7529 QualType PointeeType = PT->getPointeeType(); 7530 if (PointeeType->isPointerType()) 7531 return PtrPtrKernelParam; 7532 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7533 : PtrKernelParam; 7534 } 7535 7536 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7537 // be used as builtin types. 7538 7539 if (PT->isImageType()) 7540 return PtrKernelParam; 7541 7542 if (PT->isBooleanType()) 7543 return InvalidKernelParam; 7544 7545 if (PT->isEventT()) 7546 return InvalidKernelParam; 7547 7548 if (PT->isHalfType()) 7549 return InvalidKernelParam; 7550 7551 if (PT->isRecordType()) 7552 return RecordKernelParam; 7553 7554 return ValidKernelParam; 7555 } 7556 7557 static void checkIsValidOpenCLKernelParameter( 7558 Sema &S, 7559 Declarator &D, 7560 ParmVarDecl *Param, 7561 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7562 QualType PT = Param->getType(); 7563 7564 // Cache the valid types we encounter to avoid rechecking structs that are 7565 // used again 7566 if (ValidTypes.count(PT.getTypePtr())) 7567 return; 7568 7569 switch (getOpenCLKernelParameterType(PT)) { 7570 case PtrPtrKernelParam: 7571 // OpenCL v1.2 s6.9.a: 7572 // A kernel function argument cannot be declared as a 7573 // pointer to a pointer type. 7574 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7575 D.setInvalidType(); 7576 return; 7577 7578 case PrivatePtrKernelParam: 7579 // OpenCL v1.2 s6.9.a: 7580 // A kernel function argument cannot be declared as a 7581 // pointer to the private address space. 7582 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7583 D.setInvalidType(); 7584 return; 7585 7586 // OpenCL v1.2 s6.9.k: 7587 // Arguments to kernel functions in a program cannot be declared with the 7588 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7589 // uintptr_t or a struct and/or union that contain fields declared to be 7590 // one of these built-in scalar types. 7591 7592 case InvalidKernelParam: 7593 // OpenCL v1.2 s6.8 n: 7594 // A kernel function argument cannot be declared 7595 // of event_t type. 7596 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7597 D.setInvalidType(); 7598 return; 7599 7600 case PtrKernelParam: 7601 case ValidKernelParam: 7602 ValidTypes.insert(PT.getTypePtr()); 7603 return; 7604 7605 case RecordKernelParam: 7606 break; 7607 } 7608 7609 // Track nested structs we will inspect 7610 SmallVector<const Decl *, 4> VisitStack; 7611 7612 // Track where we are in the nested structs. Items will migrate from 7613 // VisitStack to HistoryStack as we do the DFS for bad field. 7614 SmallVector<const FieldDecl *, 4> HistoryStack; 7615 HistoryStack.push_back(nullptr); 7616 7617 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7618 VisitStack.push_back(PD); 7619 7620 assert(VisitStack.back() && "First decl null?"); 7621 7622 do { 7623 const Decl *Next = VisitStack.pop_back_val(); 7624 if (!Next) { 7625 assert(!HistoryStack.empty()); 7626 // Found a marker, we have gone up a level 7627 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7628 ValidTypes.insert(Hist->getType().getTypePtr()); 7629 7630 continue; 7631 } 7632 7633 // Adds everything except the original parameter declaration (which is not a 7634 // field itself) to the history stack. 7635 const RecordDecl *RD; 7636 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7637 HistoryStack.push_back(Field); 7638 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7639 } else { 7640 RD = cast<RecordDecl>(Next); 7641 } 7642 7643 // Add a null marker so we know when we've gone back up a level 7644 VisitStack.push_back(nullptr); 7645 7646 for (const auto *FD : RD->fields()) { 7647 QualType QT = FD->getType(); 7648 7649 if (ValidTypes.count(QT.getTypePtr())) 7650 continue; 7651 7652 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7653 if (ParamType == ValidKernelParam) 7654 continue; 7655 7656 if (ParamType == RecordKernelParam) { 7657 VisitStack.push_back(FD); 7658 continue; 7659 } 7660 7661 // OpenCL v1.2 s6.9.p: 7662 // Arguments to kernel functions that are declared to be a struct or union 7663 // do not allow OpenCL objects to be passed as elements of the struct or 7664 // union. 7665 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7666 ParamType == PrivatePtrKernelParam) { 7667 S.Diag(Param->getLocation(), 7668 diag::err_record_with_pointers_kernel_param) 7669 << PT->isUnionType() 7670 << PT; 7671 } else { 7672 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7673 } 7674 7675 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7676 << PD->getDeclName(); 7677 7678 // We have an error, now let's go back up through history and show where 7679 // the offending field came from 7680 for (ArrayRef<const FieldDecl *>::const_iterator 7681 I = HistoryStack.begin() + 1, 7682 E = HistoryStack.end(); 7683 I != E; ++I) { 7684 const FieldDecl *OuterField = *I; 7685 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7686 << OuterField->getType(); 7687 } 7688 7689 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7690 << QT->isPointerType() 7691 << QT; 7692 D.setInvalidType(); 7693 return; 7694 } 7695 } while (!VisitStack.empty()); 7696 } 7697 7698 NamedDecl* 7699 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7700 TypeSourceInfo *TInfo, LookupResult &Previous, 7701 MultiTemplateParamsArg TemplateParamLists, 7702 bool &AddToScope) { 7703 QualType R = TInfo->getType(); 7704 7705 assert(R.getTypePtr()->isFunctionType()); 7706 7707 // TODO: consider using NameInfo for diagnostic. 7708 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7709 DeclarationName Name = NameInfo.getName(); 7710 StorageClass SC = getFunctionStorageClass(*this, D); 7711 7712 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7713 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7714 diag::err_invalid_thread) 7715 << DeclSpec::getSpecifierName(TSCS); 7716 7717 if (D.isFirstDeclarationOfMember()) 7718 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7719 D.getIdentifierLoc()); 7720 7721 bool isFriend = false; 7722 FunctionTemplateDecl *FunctionTemplate = nullptr; 7723 bool isExplicitSpecialization = false; 7724 bool isFunctionTemplateSpecialization = false; 7725 7726 bool isDependentClassScopeExplicitSpecialization = false; 7727 bool HasExplicitTemplateArgs = false; 7728 TemplateArgumentListInfo TemplateArgs; 7729 7730 bool isVirtualOkay = false; 7731 7732 DeclContext *OriginalDC = DC; 7733 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7734 7735 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7736 isVirtualOkay); 7737 if (!NewFD) return nullptr; 7738 7739 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7740 NewFD->setTopLevelDeclInObjCContainer(); 7741 7742 // Set the lexical context. If this is a function-scope declaration, or has a 7743 // C++ scope specifier, or is the object of a friend declaration, the lexical 7744 // context will be different from the semantic context. 7745 NewFD->setLexicalDeclContext(CurContext); 7746 7747 if (IsLocalExternDecl) 7748 NewFD->setLocalExternDecl(); 7749 7750 if (getLangOpts().CPlusPlus) { 7751 bool isInline = D.getDeclSpec().isInlineSpecified(); 7752 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7753 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7754 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7755 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7756 isFriend = D.getDeclSpec().isFriendSpecified(); 7757 if (isFriend && !isInline && D.isFunctionDefinition()) { 7758 // C++ [class.friend]p5 7759 // A function can be defined in a friend declaration of a 7760 // class . . . . Such a function is implicitly inline. 7761 NewFD->setImplicitlyInline(); 7762 } 7763 7764 // If this is a method defined in an __interface, and is not a constructor 7765 // or an overloaded operator, then set the pure flag (isVirtual will already 7766 // return true). 7767 if (const CXXRecordDecl *Parent = 7768 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7769 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7770 NewFD->setPure(true); 7771 7772 // C++ [class.union]p2 7773 // A union can have member functions, but not virtual functions. 7774 if (isVirtual && Parent->isUnion()) 7775 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7776 } 7777 7778 SetNestedNameSpecifier(NewFD, D); 7779 isExplicitSpecialization = false; 7780 isFunctionTemplateSpecialization = false; 7781 if (D.isInvalidType()) 7782 NewFD->setInvalidDecl(); 7783 7784 // Match up the template parameter lists with the scope specifier, then 7785 // determine whether we have a template or a template specialization. 7786 bool Invalid = false; 7787 if (TemplateParameterList *TemplateParams = 7788 MatchTemplateParametersToScopeSpecifier( 7789 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7790 D.getCXXScopeSpec(), 7791 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7792 ? D.getName().TemplateId 7793 : nullptr, 7794 TemplateParamLists, isFriend, isExplicitSpecialization, 7795 Invalid)) { 7796 if (TemplateParams->size() > 0) { 7797 // This is a function template 7798 7799 // Check that we can declare a template here. 7800 if (CheckTemplateDeclScope(S, TemplateParams)) 7801 NewFD->setInvalidDecl(); 7802 7803 // A destructor cannot be a template. 7804 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7805 Diag(NewFD->getLocation(), diag::err_destructor_template); 7806 NewFD->setInvalidDecl(); 7807 } 7808 7809 // If we're adding a template to a dependent context, we may need to 7810 // rebuilding some of the types used within the template parameter list, 7811 // now that we know what the current instantiation is. 7812 if (DC->isDependentContext()) { 7813 ContextRAII SavedContext(*this, DC); 7814 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7815 Invalid = true; 7816 } 7817 7818 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7819 NewFD->getLocation(), 7820 Name, TemplateParams, 7821 NewFD); 7822 FunctionTemplate->setLexicalDeclContext(CurContext); 7823 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7824 7825 // For source fidelity, store the other template param lists. 7826 if (TemplateParamLists.size() > 1) { 7827 NewFD->setTemplateParameterListsInfo(Context, 7828 TemplateParamLists.drop_back(1)); 7829 } 7830 } else { 7831 // This is a function template specialization. 7832 isFunctionTemplateSpecialization = true; 7833 // For source fidelity, store all the template param lists. 7834 if (TemplateParamLists.size() > 0) 7835 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7836 7837 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7838 if (isFriend) { 7839 // We want to remove the "template<>", found here. 7840 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7841 7842 // If we remove the template<> and the name is not a 7843 // template-id, we're actually silently creating a problem: 7844 // the friend declaration will refer to an untemplated decl, 7845 // and clearly the user wants a template specialization. So 7846 // we need to insert '<>' after the name. 7847 SourceLocation InsertLoc; 7848 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7849 InsertLoc = D.getName().getSourceRange().getEnd(); 7850 InsertLoc = getLocForEndOfToken(InsertLoc); 7851 } 7852 7853 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7854 << Name << RemoveRange 7855 << FixItHint::CreateRemoval(RemoveRange) 7856 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7857 } 7858 } 7859 } 7860 else { 7861 // All template param lists were matched against the scope specifier: 7862 // this is NOT (an explicit specialization of) a template. 7863 if (TemplateParamLists.size() > 0) 7864 // For source fidelity, store all the template param lists. 7865 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7866 } 7867 7868 if (Invalid) { 7869 NewFD->setInvalidDecl(); 7870 if (FunctionTemplate) 7871 FunctionTemplate->setInvalidDecl(); 7872 } 7873 7874 // C++ [dcl.fct.spec]p5: 7875 // The virtual specifier shall only be used in declarations of 7876 // nonstatic class member functions that appear within a 7877 // member-specification of a class declaration; see 10.3. 7878 // 7879 if (isVirtual && !NewFD->isInvalidDecl()) { 7880 if (!isVirtualOkay) { 7881 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7882 diag::err_virtual_non_function); 7883 } else if (!CurContext->isRecord()) { 7884 // 'virtual' was specified outside of the class. 7885 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7886 diag::err_virtual_out_of_class) 7887 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7888 } else if (NewFD->getDescribedFunctionTemplate()) { 7889 // C++ [temp.mem]p3: 7890 // A member function template shall not be virtual. 7891 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7892 diag::err_virtual_member_function_template) 7893 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7894 } else { 7895 // Okay: Add virtual to the method. 7896 NewFD->setVirtualAsWritten(true); 7897 } 7898 7899 if (getLangOpts().CPlusPlus14 && 7900 NewFD->getReturnType()->isUndeducedType()) 7901 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7902 } 7903 7904 if (getLangOpts().CPlusPlus14 && 7905 (NewFD->isDependentContext() || 7906 (isFriend && CurContext->isDependentContext())) && 7907 NewFD->getReturnType()->isUndeducedType()) { 7908 // If the function template is referenced directly (for instance, as a 7909 // member of the current instantiation), pretend it has a dependent type. 7910 // This is not really justified by the standard, but is the only sane 7911 // thing to do. 7912 // FIXME: For a friend function, we have not marked the function as being 7913 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7914 const FunctionProtoType *FPT = 7915 NewFD->getType()->castAs<FunctionProtoType>(); 7916 QualType Result = 7917 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7918 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7919 FPT->getExtProtoInfo())); 7920 } 7921 7922 // C++ [dcl.fct.spec]p3: 7923 // The inline specifier shall not appear on a block scope function 7924 // declaration. 7925 if (isInline && !NewFD->isInvalidDecl()) { 7926 if (CurContext->isFunctionOrMethod()) { 7927 // 'inline' is not allowed on block scope function declaration. 7928 Diag(D.getDeclSpec().getInlineSpecLoc(), 7929 diag::err_inline_declaration_block_scope) << Name 7930 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7931 } 7932 } 7933 7934 // C++ [dcl.fct.spec]p6: 7935 // The explicit specifier shall be used only in the declaration of a 7936 // constructor or conversion function within its class definition; 7937 // see 12.3.1 and 12.3.2. 7938 if (isExplicit && !NewFD->isInvalidDecl()) { 7939 if (!CurContext->isRecord()) { 7940 // 'explicit' was specified outside of the class. 7941 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7942 diag::err_explicit_out_of_class) 7943 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7944 } else if (!isa<CXXConstructorDecl>(NewFD) && 7945 !isa<CXXConversionDecl>(NewFD)) { 7946 // 'explicit' was specified on a function that wasn't a constructor 7947 // or conversion function. 7948 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7949 diag::err_explicit_non_ctor_or_conv_function) 7950 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7951 } 7952 } 7953 7954 if (isConstexpr) { 7955 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7956 // are implicitly inline. 7957 NewFD->setImplicitlyInline(); 7958 7959 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7960 // be either constructors or to return a literal type. Therefore, 7961 // destructors cannot be declared constexpr. 7962 if (isa<CXXDestructorDecl>(NewFD)) 7963 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7964 } 7965 7966 if (isConcept) { 7967 // This is a function concept. 7968 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7969 FTD->setConcept(); 7970 7971 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7972 // applied only to the definition of a function template [...] 7973 if (!D.isFunctionDefinition()) { 7974 Diag(D.getDeclSpec().getConceptSpecLoc(), 7975 diag::err_function_concept_not_defined); 7976 NewFD->setInvalidDecl(); 7977 } 7978 7979 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7980 // have no exception-specification and is treated as if it were specified 7981 // with noexcept(true) (15.4). [...] 7982 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7983 if (FPT->hasExceptionSpec()) { 7984 SourceRange Range; 7985 if (D.isFunctionDeclarator()) 7986 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7987 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7988 << FixItHint::CreateRemoval(Range); 7989 NewFD->setInvalidDecl(); 7990 } else { 7991 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 7992 } 7993 7994 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7995 // following restrictions: 7996 // - The declared return type shall have the type bool. 7997 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 7998 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 7999 NewFD->setInvalidDecl(); 8000 } 8001 8002 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8003 // following restrictions: 8004 // - The declaration's parameter list shall be equivalent to an empty 8005 // parameter list. 8006 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8007 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8008 } 8009 8010 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8011 // implicity defined to be a constexpr declaration (implicitly inline) 8012 NewFD->setImplicitlyInline(); 8013 8014 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8015 // be declared with the thread_local, inline, friend, or constexpr 8016 // specifiers, [...] 8017 if (isInline) { 8018 Diag(D.getDeclSpec().getInlineSpecLoc(), 8019 diag::err_concept_decl_invalid_specifiers) 8020 << 1 << 1; 8021 NewFD->setInvalidDecl(true); 8022 } 8023 8024 if (isFriend) { 8025 Diag(D.getDeclSpec().getFriendSpecLoc(), 8026 diag::err_concept_decl_invalid_specifiers) 8027 << 1 << 2; 8028 NewFD->setInvalidDecl(true); 8029 } 8030 8031 if (isConstexpr) { 8032 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8033 diag::err_concept_decl_invalid_specifiers) 8034 << 1 << 3; 8035 NewFD->setInvalidDecl(true); 8036 } 8037 8038 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8039 // applied only to the definition of a function template or variable 8040 // template, declared in namespace scope. 8041 if (isFunctionTemplateSpecialization) { 8042 Diag(D.getDeclSpec().getConceptSpecLoc(), 8043 diag::err_concept_specified_specialization) << 1; 8044 NewFD->setInvalidDecl(true); 8045 return NewFD; 8046 } 8047 } 8048 8049 // If __module_private__ was specified, mark the function accordingly. 8050 if (D.getDeclSpec().isModulePrivateSpecified()) { 8051 if (isFunctionTemplateSpecialization) { 8052 SourceLocation ModulePrivateLoc 8053 = D.getDeclSpec().getModulePrivateSpecLoc(); 8054 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8055 << 0 8056 << FixItHint::CreateRemoval(ModulePrivateLoc); 8057 } else { 8058 NewFD->setModulePrivate(); 8059 if (FunctionTemplate) 8060 FunctionTemplate->setModulePrivate(); 8061 } 8062 } 8063 8064 if (isFriend) { 8065 if (FunctionTemplate) { 8066 FunctionTemplate->setObjectOfFriendDecl(); 8067 FunctionTemplate->setAccess(AS_public); 8068 } 8069 NewFD->setObjectOfFriendDecl(); 8070 NewFD->setAccess(AS_public); 8071 } 8072 8073 // If a function is defined as defaulted or deleted, mark it as such now. 8074 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8075 // definition kind to FDK_Definition. 8076 switch (D.getFunctionDefinitionKind()) { 8077 case FDK_Declaration: 8078 case FDK_Definition: 8079 break; 8080 8081 case FDK_Defaulted: 8082 NewFD->setDefaulted(); 8083 break; 8084 8085 case FDK_Deleted: 8086 NewFD->setDeletedAsWritten(); 8087 break; 8088 } 8089 8090 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8091 D.isFunctionDefinition()) { 8092 // C++ [class.mfct]p2: 8093 // A member function may be defined (8.4) in its class definition, in 8094 // which case it is an inline member function (7.1.2) 8095 NewFD->setImplicitlyInline(); 8096 } 8097 8098 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8099 !CurContext->isRecord()) { 8100 // C++ [class.static]p1: 8101 // A data or function member of a class may be declared static 8102 // in a class definition, in which case it is a static member of 8103 // the class. 8104 8105 // Complain about the 'static' specifier if it's on an out-of-line 8106 // member function definition. 8107 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8108 diag::err_static_out_of_line) 8109 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8110 } 8111 8112 // C++11 [except.spec]p15: 8113 // A deallocation function with no exception-specification is treated 8114 // as if it were specified with noexcept(true). 8115 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8116 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8117 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8118 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8119 NewFD->setType(Context.getFunctionType( 8120 FPT->getReturnType(), FPT->getParamTypes(), 8121 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8122 } 8123 8124 // Filter out previous declarations that don't match the scope. 8125 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8126 D.getCXXScopeSpec().isNotEmpty() || 8127 isExplicitSpecialization || 8128 isFunctionTemplateSpecialization); 8129 8130 // Handle GNU asm-label extension (encoded as an attribute). 8131 if (Expr *E = (Expr*) D.getAsmLabel()) { 8132 // The parser guarantees this is a string. 8133 StringLiteral *SE = cast<StringLiteral>(E); 8134 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8135 SE->getString(), 0)); 8136 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8137 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8138 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8139 if (I != ExtnameUndeclaredIdentifiers.end()) { 8140 if (isDeclExternC(NewFD)) { 8141 NewFD->addAttr(I->second); 8142 ExtnameUndeclaredIdentifiers.erase(I); 8143 } else 8144 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8145 << /*Variable*/0 << NewFD; 8146 } 8147 } 8148 8149 // Copy the parameter declarations from the declarator D to the function 8150 // declaration NewFD, if they are available. First scavenge them into Params. 8151 SmallVector<ParmVarDecl*, 16> Params; 8152 if (D.isFunctionDeclarator()) { 8153 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8154 8155 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8156 // function that takes no arguments, not a function that takes a 8157 // single void argument. 8158 // We let through "const void" here because Sema::GetTypeForDeclarator 8159 // already checks for that case. 8160 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8161 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8162 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8163 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8164 Param->setDeclContext(NewFD); 8165 Params.push_back(Param); 8166 8167 if (Param->isInvalidDecl()) 8168 NewFD->setInvalidDecl(); 8169 } 8170 } 8171 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8172 // When we're declaring a function with a typedef, typeof, etc as in the 8173 // following example, we'll need to synthesize (unnamed) 8174 // parameters for use in the declaration. 8175 // 8176 // @code 8177 // typedef void fn(int); 8178 // fn f; 8179 // @endcode 8180 8181 // Synthesize a parameter for each argument type. 8182 for (const auto &AI : FT->param_types()) { 8183 ParmVarDecl *Param = 8184 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8185 Param->setScopeInfo(0, Params.size()); 8186 Params.push_back(Param); 8187 } 8188 } else { 8189 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8190 "Should not need args for typedef of non-prototype fn"); 8191 } 8192 8193 // Finally, we know we have the right number of parameters, install them. 8194 NewFD->setParams(Params); 8195 8196 // Find all anonymous symbols defined during the declaration of this function 8197 // and add to NewFD. This lets us track decls such 'enum Y' in: 8198 // 8199 // void f(enum Y {AA} x) {} 8200 // 8201 // which would otherwise incorrectly end up in the translation unit scope. 8202 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8203 DeclsInPrototypeScope.clear(); 8204 8205 if (D.getDeclSpec().isNoreturnSpecified()) 8206 NewFD->addAttr( 8207 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8208 Context, 0)); 8209 8210 // Functions returning a variably modified type violate C99 6.7.5.2p2 8211 // because all functions have linkage. 8212 if (!NewFD->isInvalidDecl() && 8213 NewFD->getReturnType()->isVariablyModifiedType()) { 8214 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8215 NewFD->setInvalidDecl(); 8216 } 8217 8218 // Apply an implicit SectionAttr if #pragma code_seg is active. 8219 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8220 !NewFD->hasAttr<SectionAttr>()) { 8221 NewFD->addAttr( 8222 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8223 CodeSegStack.CurrentValue->getString(), 8224 CodeSegStack.CurrentPragmaLocation)); 8225 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8226 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8227 ASTContext::PSF_Read, 8228 NewFD)) 8229 NewFD->dropAttr<SectionAttr>(); 8230 } 8231 8232 // Handle attributes. 8233 ProcessDeclAttributes(S, NewFD, D); 8234 8235 if (getLangOpts().CUDA) 8236 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous); 8237 8238 if (getLangOpts().OpenCL) { 8239 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8240 // type declaration will generate a compilation error. 8241 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8242 if (AddressSpace == LangAS::opencl_local || 8243 AddressSpace == LangAS::opencl_global || 8244 AddressSpace == LangAS::opencl_constant) { 8245 Diag(NewFD->getLocation(), 8246 diag::err_opencl_return_value_with_address_space); 8247 NewFD->setInvalidDecl(); 8248 } 8249 } 8250 8251 if (!getLangOpts().CPlusPlus) { 8252 // Perform semantic checking on the function declaration. 8253 bool isExplicitSpecialization=false; 8254 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8255 CheckMain(NewFD, D.getDeclSpec()); 8256 8257 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8258 CheckMSVCRTEntryPoint(NewFD); 8259 8260 if (!NewFD->isInvalidDecl()) 8261 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8262 isExplicitSpecialization)); 8263 else if (!Previous.empty()) 8264 // Recover gracefully from an invalid redeclaration. 8265 D.setRedeclaration(true); 8266 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8267 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8268 "previous declaration set still overloaded"); 8269 8270 // Diagnose no-prototype function declarations with calling conventions that 8271 // don't support variadic calls. Only do this in C and do it after merging 8272 // possibly prototyped redeclarations. 8273 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8274 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8275 CallingConv CC = FT->getExtInfo().getCC(); 8276 if (!supportsVariadicCall(CC)) { 8277 // Windows system headers sometimes accidentally use stdcall without 8278 // (void) parameters, so we relax this to a warning. 8279 int DiagID = 8280 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8281 Diag(NewFD->getLocation(), DiagID) 8282 << FunctionType::getNameForCallConv(CC); 8283 } 8284 } 8285 } else { 8286 // C++11 [replacement.functions]p3: 8287 // The program's definitions shall not be specified as inline. 8288 // 8289 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8290 // 8291 // Suppress the diagnostic if the function is __attribute__((used)), since 8292 // that forces an external definition to be emitted. 8293 if (D.getDeclSpec().isInlineSpecified() && 8294 NewFD->isReplaceableGlobalAllocationFunction() && 8295 !NewFD->hasAttr<UsedAttr>()) 8296 Diag(D.getDeclSpec().getInlineSpecLoc(), 8297 diag::ext_operator_new_delete_declared_inline) 8298 << NewFD->getDeclName(); 8299 8300 // If the declarator is a template-id, translate the parser's template 8301 // argument list into our AST format. 8302 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8303 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8304 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8305 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8306 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8307 TemplateId->NumArgs); 8308 translateTemplateArguments(TemplateArgsPtr, 8309 TemplateArgs); 8310 8311 HasExplicitTemplateArgs = true; 8312 8313 if (NewFD->isInvalidDecl()) { 8314 HasExplicitTemplateArgs = false; 8315 } else if (FunctionTemplate) { 8316 // Function template with explicit template arguments. 8317 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8318 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8319 8320 HasExplicitTemplateArgs = false; 8321 } else { 8322 assert((isFunctionTemplateSpecialization || 8323 D.getDeclSpec().isFriendSpecified()) && 8324 "should have a 'template<>' for this decl"); 8325 // "friend void foo<>(int);" is an implicit specialization decl. 8326 isFunctionTemplateSpecialization = true; 8327 } 8328 } else if (isFriend && isFunctionTemplateSpecialization) { 8329 // This combination is only possible in a recovery case; the user 8330 // wrote something like: 8331 // template <> friend void foo(int); 8332 // which we're recovering from as if the user had written: 8333 // friend void foo<>(int); 8334 // Go ahead and fake up a template id. 8335 HasExplicitTemplateArgs = true; 8336 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8337 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8338 } 8339 8340 // If it's a friend (and only if it's a friend), it's possible 8341 // that either the specialized function type or the specialized 8342 // template is dependent, and therefore matching will fail. In 8343 // this case, don't check the specialization yet. 8344 bool InstantiationDependent = false; 8345 if (isFunctionTemplateSpecialization && isFriend && 8346 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8347 TemplateSpecializationType::anyDependentTemplateArguments( 8348 TemplateArgs, 8349 InstantiationDependent))) { 8350 assert(HasExplicitTemplateArgs && 8351 "friend function specialization without template args"); 8352 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8353 Previous)) 8354 NewFD->setInvalidDecl(); 8355 } else if (isFunctionTemplateSpecialization) { 8356 if (CurContext->isDependentContext() && CurContext->isRecord() 8357 && !isFriend) { 8358 isDependentClassScopeExplicitSpecialization = true; 8359 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8360 diag::ext_function_specialization_in_class : 8361 diag::err_function_specialization_in_class) 8362 << NewFD->getDeclName(); 8363 } else if (CheckFunctionTemplateSpecialization(NewFD, 8364 (HasExplicitTemplateArgs ? &TemplateArgs 8365 : nullptr), 8366 Previous)) 8367 NewFD->setInvalidDecl(); 8368 8369 // C++ [dcl.stc]p1: 8370 // A storage-class-specifier shall not be specified in an explicit 8371 // specialization (14.7.3) 8372 FunctionTemplateSpecializationInfo *Info = 8373 NewFD->getTemplateSpecializationInfo(); 8374 if (Info && SC != SC_None) { 8375 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8376 Diag(NewFD->getLocation(), 8377 diag::err_explicit_specialization_inconsistent_storage_class) 8378 << SC 8379 << FixItHint::CreateRemoval( 8380 D.getDeclSpec().getStorageClassSpecLoc()); 8381 8382 else 8383 Diag(NewFD->getLocation(), 8384 diag::ext_explicit_specialization_storage_class) 8385 << FixItHint::CreateRemoval( 8386 D.getDeclSpec().getStorageClassSpecLoc()); 8387 } 8388 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8389 if (CheckMemberSpecialization(NewFD, Previous)) 8390 NewFD->setInvalidDecl(); 8391 } 8392 8393 // Perform semantic checking on the function declaration. 8394 if (!isDependentClassScopeExplicitSpecialization) { 8395 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8396 CheckMain(NewFD, D.getDeclSpec()); 8397 8398 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8399 CheckMSVCRTEntryPoint(NewFD); 8400 8401 if (!NewFD->isInvalidDecl()) 8402 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8403 isExplicitSpecialization)); 8404 else if (!Previous.empty()) 8405 // Recover gracefully from an invalid redeclaration. 8406 D.setRedeclaration(true); 8407 } 8408 8409 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8410 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8411 "previous declaration set still overloaded"); 8412 8413 NamedDecl *PrincipalDecl = (FunctionTemplate 8414 ? cast<NamedDecl>(FunctionTemplate) 8415 : NewFD); 8416 8417 if (isFriend && D.isRedeclaration()) { 8418 AccessSpecifier Access = AS_public; 8419 if (!NewFD->isInvalidDecl()) 8420 Access = NewFD->getPreviousDecl()->getAccess(); 8421 8422 NewFD->setAccess(Access); 8423 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8424 } 8425 8426 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8427 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8428 PrincipalDecl->setNonMemberOperator(); 8429 8430 // If we have a function template, check the template parameter 8431 // list. This will check and merge default template arguments. 8432 if (FunctionTemplate) { 8433 FunctionTemplateDecl *PrevTemplate = 8434 FunctionTemplate->getPreviousDecl(); 8435 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8436 PrevTemplate ? PrevTemplate->getTemplateParameters() 8437 : nullptr, 8438 D.getDeclSpec().isFriendSpecified() 8439 ? (D.isFunctionDefinition() 8440 ? TPC_FriendFunctionTemplateDefinition 8441 : TPC_FriendFunctionTemplate) 8442 : (D.getCXXScopeSpec().isSet() && 8443 DC && DC->isRecord() && 8444 DC->isDependentContext()) 8445 ? TPC_ClassTemplateMember 8446 : TPC_FunctionTemplate); 8447 } 8448 8449 if (NewFD->isInvalidDecl()) { 8450 // Ignore all the rest of this. 8451 } else if (!D.isRedeclaration()) { 8452 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8453 AddToScope }; 8454 // Fake up an access specifier if it's supposed to be a class member. 8455 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8456 NewFD->setAccess(AS_public); 8457 8458 // Qualified decls generally require a previous declaration. 8459 if (D.getCXXScopeSpec().isSet()) { 8460 // ...with the major exception of templated-scope or 8461 // dependent-scope friend declarations. 8462 8463 // TODO: we currently also suppress this check in dependent 8464 // contexts because (1) the parameter depth will be off when 8465 // matching friend templates and (2) we might actually be 8466 // selecting a friend based on a dependent factor. But there 8467 // are situations where these conditions don't apply and we 8468 // can actually do this check immediately. 8469 if (isFriend && 8470 (TemplateParamLists.size() || 8471 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8472 CurContext->isDependentContext())) { 8473 // ignore these 8474 } else { 8475 // The user tried to provide an out-of-line definition for a 8476 // function that is a member of a class or namespace, but there 8477 // was no such member function declared (C++ [class.mfct]p2, 8478 // C++ [namespace.memdef]p2). For example: 8479 // 8480 // class X { 8481 // void f() const; 8482 // }; 8483 // 8484 // void X::f() { } // ill-formed 8485 // 8486 // Complain about this problem, and attempt to suggest close 8487 // matches (e.g., those that differ only in cv-qualifiers and 8488 // whether the parameter types are references). 8489 8490 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8491 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8492 AddToScope = ExtraArgs.AddToScope; 8493 return Result; 8494 } 8495 } 8496 8497 // Unqualified local friend declarations are required to resolve 8498 // to something. 8499 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8500 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8501 *this, Previous, NewFD, ExtraArgs, true, S)) { 8502 AddToScope = ExtraArgs.AddToScope; 8503 return Result; 8504 } 8505 } 8506 } else if (!D.isFunctionDefinition() && 8507 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8508 !isFriend && !isFunctionTemplateSpecialization && 8509 !isExplicitSpecialization) { 8510 // An out-of-line member function declaration must also be a 8511 // definition (C++ [class.mfct]p2). 8512 // Note that this is not the case for explicit specializations of 8513 // function templates or member functions of class templates, per 8514 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8515 // extension for compatibility with old SWIG code which likes to 8516 // generate them. 8517 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8518 << D.getCXXScopeSpec().getRange(); 8519 } 8520 } 8521 8522 ProcessPragmaWeak(S, NewFD); 8523 checkAttributesAfterMerging(*this, *NewFD); 8524 8525 AddKnownFunctionAttributes(NewFD); 8526 8527 if (NewFD->hasAttr<OverloadableAttr>() && 8528 !NewFD->getType()->getAs<FunctionProtoType>()) { 8529 Diag(NewFD->getLocation(), 8530 diag::err_attribute_overloadable_no_prototype) 8531 << NewFD; 8532 8533 // Turn this into a variadic function with no parameters. 8534 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8535 FunctionProtoType::ExtProtoInfo EPI( 8536 Context.getDefaultCallingConvention(true, false)); 8537 EPI.Variadic = true; 8538 EPI.ExtInfo = FT->getExtInfo(); 8539 8540 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8541 NewFD->setType(R); 8542 } 8543 8544 // If there's a #pragma GCC visibility in scope, and this isn't a class 8545 // member, set the visibility of this function. 8546 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8547 AddPushedVisibilityAttribute(NewFD); 8548 8549 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8550 // marking the function. 8551 AddCFAuditedAttribute(NewFD); 8552 8553 // If this is a function definition, check if we have to apply optnone due to 8554 // a pragma. 8555 if(D.isFunctionDefinition()) 8556 AddRangeBasedOptnone(NewFD); 8557 8558 // If this is the first declaration of an extern C variable, update 8559 // the map of such variables. 8560 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8561 isIncompleteDeclExternC(*this, NewFD)) 8562 RegisterLocallyScopedExternCDecl(NewFD, S); 8563 8564 // Set this FunctionDecl's range up to the right paren. 8565 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8566 8567 if (D.isRedeclaration() && !Previous.empty()) { 8568 checkDLLAttributeRedeclaration( 8569 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8570 isExplicitSpecialization || isFunctionTemplateSpecialization, 8571 D.isFunctionDefinition()); 8572 } 8573 8574 if (getLangOpts().CUDA) { 8575 IdentifierInfo *II = NewFD->getIdentifier(); 8576 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8577 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8578 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8579 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8580 8581 Context.setcudaConfigureCallDecl(NewFD); 8582 } 8583 8584 // Variadic functions, other than a *declaration* of printf, are not allowed 8585 // in device-side CUDA code, unless someone passed 8586 // -fcuda-allow-variadic-functions. 8587 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8588 (NewFD->hasAttr<CUDADeviceAttr>() || 8589 NewFD->hasAttr<CUDAGlobalAttr>()) && 8590 !(II && II->isStr("printf") && NewFD->isExternC() && 8591 !D.isFunctionDefinition())) { 8592 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8593 } 8594 } 8595 8596 if (getLangOpts().CPlusPlus) { 8597 if (FunctionTemplate) { 8598 if (NewFD->isInvalidDecl()) 8599 FunctionTemplate->setInvalidDecl(); 8600 return FunctionTemplate; 8601 } 8602 } 8603 8604 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8605 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8606 if ((getLangOpts().OpenCLVersion >= 120) 8607 && (SC == SC_Static)) { 8608 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8609 D.setInvalidType(); 8610 } 8611 8612 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8613 if (!NewFD->getReturnType()->isVoidType()) { 8614 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8615 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8616 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8617 : FixItHint()); 8618 D.setInvalidType(); 8619 } 8620 8621 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8622 for (auto Param : NewFD->parameters()) 8623 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8624 } 8625 for (const ParmVarDecl *Param : NewFD->parameters()) { 8626 QualType PT = Param->getType(); 8627 8628 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8629 // types. 8630 if (getLangOpts().OpenCLVersion >= 200) { 8631 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8632 QualType ElemTy = PipeTy->getElementType(); 8633 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8634 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8635 D.setInvalidType(); 8636 } 8637 } 8638 } 8639 } 8640 8641 MarkUnusedFileScopedDecl(NewFD); 8642 8643 // Here we have an function template explicit specialization at class scope. 8644 // The actually specialization will be postponed to template instatiation 8645 // time via the ClassScopeFunctionSpecializationDecl node. 8646 if (isDependentClassScopeExplicitSpecialization) { 8647 ClassScopeFunctionSpecializationDecl *NewSpec = 8648 ClassScopeFunctionSpecializationDecl::Create( 8649 Context, CurContext, SourceLocation(), 8650 cast<CXXMethodDecl>(NewFD), 8651 HasExplicitTemplateArgs, TemplateArgs); 8652 CurContext->addDecl(NewSpec); 8653 AddToScope = false; 8654 } 8655 8656 return NewFD; 8657 } 8658 8659 /// \brief Perform semantic checking of a new function declaration. 8660 /// 8661 /// Performs semantic analysis of the new function declaration 8662 /// NewFD. This routine performs all semantic checking that does not 8663 /// require the actual declarator involved in the declaration, and is 8664 /// used both for the declaration of functions as they are parsed 8665 /// (called via ActOnDeclarator) and for the declaration of functions 8666 /// that have been instantiated via C++ template instantiation (called 8667 /// via InstantiateDecl). 8668 /// 8669 /// \param IsExplicitSpecialization whether this new function declaration is 8670 /// an explicit specialization of the previous declaration. 8671 /// 8672 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8673 /// 8674 /// \returns true if the function declaration is a redeclaration. 8675 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8676 LookupResult &Previous, 8677 bool IsExplicitSpecialization) { 8678 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8679 "Variably modified return types are not handled here"); 8680 8681 // Determine whether the type of this function should be merged with 8682 // a previous visible declaration. This never happens for functions in C++, 8683 // and always happens in C if the previous declaration was visible. 8684 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8685 !Previous.isShadowed(); 8686 8687 bool Redeclaration = false; 8688 NamedDecl *OldDecl = nullptr; 8689 8690 // Merge or overload the declaration with an existing declaration of 8691 // the same name, if appropriate. 8692 if (!Previous.empty()) { 8693 // Determine whether NewFD is an overload of PrevDecl or 8694 // a declaration that requires merging. If it's an overload, 8695 // there's no more work to do here; we'll just add the new 8696 // function to the scope. 8697 if (!AllowOverloadingOfFunction(Previous, Context)) { 8698 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8699 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8700 Redeclaration = true; 8701 OldDecl = Candidate; 8702 } 8703 } else { 8704 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8705 /*NewIsUsingDecl*/ false)) { 8706 case Ovl_Match: 8707 Redeclaration = true; 8708 break; 8709 8710 case Ovl_NonFunction: 8711 Redeclaration = true; 8712 break; 8713 8714 case Ovl_Overload: 8715 Redeclaration = false; 8716 break; 8717 } 8718 8719 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8720 // If a function name is overloadable in C, then every function 8721 // with that name must be marked "overloadable". 8722 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8723 << Redeclaration << NewFD; 8724 NamedDecl *OverloadedDecl = nullptr; 8725 if (Redeclaration) 8726 OverloadedDecl = OldDecl; 8727 else if (!Previous.empty()) 8728 OverloadedDecl = Previous.getRepresentativeDecl(); 8729 if (OverloadedDecl) 8730 Diag(OverloadedDecl->getLocation(), 8731 diag::note_attribute_overloadable_prev_overload); 8732 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8733 } 8734 } 8735 } 8736 8737 // Check for a previous extern "C" declaration with this name. 8738 if (!Redeclaration && 8739 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8740 if (!Previous.empty()) { 8741 // This is an extern "C" declaration with the same name as a previous 8742 // declaration, and thus redeclares that entity... 8743 Redeclaration = true; 8744 OldDecl = Previous.getFoundDecl(); 8745 MergeTypeWithPrevious = false; 8746 8747 // ... except in the presence of __attribute__((overloadable)). 8748 if (OldDecl->hasAttr<OverloadableAttr>()) { 8749 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8750 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8751 << Redeclaration << NewFD; 8752 Diag(Previous.getFoundDecl()->getLocation(), 8753 diag::note_attribute_overloadable_prev_overload); 8754 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8755 } 8756 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8757 Redeclaration = false; 8758 OldDecl = nullptr; 8759 } 8760 } 8761 } 8762 } 8763 8764 // C++11 [dcl.constexpr]p8: 8765 // A constexpr specifier for a non-static member function that is not 8766 // a constructor declares that member function to be const. 8767 // 8768 // This needs to be delayed until we know whether this is an out-of-line 8769 // definition of a static member function. 8770 // 8771 // This rule is not present in C++1y, so we produce a backwards 8772 // compatibility warning whenever it happens in C++11. 8773 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8774 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8775 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8776 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8777 CXXMethodDecl *OldMD = nullptr; 8778 if (OldDecl) 8779 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8780 if (!OldMD || !OldMD->isStatic()) { 8781 const FunctionProtoType *FPT = 8782 MD->getType()->castAs<FunctionProtoType>(); 8783 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8784 EPI.TypeQuals |= Qualifiers::Const; 8785 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8786 FPT->getParamTypes(), EPI)); 8787 8788 // Warn that we did this, if we're not performing template instantiation. 8789 // In that case, we'll have warned already when the template was defined. 8790 if (ActiveTemplateInstantiations.empty()) { 8791 SourceLocation AddConstLoc; 8792 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8793 .IgnoreParens().getAs<FunctionTypeLoc>()) 8794 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8795 8796 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8797 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8798 } 8799 } 8800 } 8801 8802 if (Redeclaration) { 8803 // NewFD and OldDecl represent declarations that need to be 8804 // merged. 8805 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8806 NewFD->setInvalidDecl(); 8807 return Redeclaration; 8808 } 8809 8810 Previous.clear(); 8811 Previous.addDecl(OldDecl); 8812 8813 if (FunctionTemplateDecl *OldTemplateDecl 8814 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8815 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8816 FunctionTemplateDecl *NewTemplateDecl 8817 = NewFD->getDescribedFunctionTemplate(); 8818 assert(NewTemplateDecl && "Template/non-template mismatch"); 8819 if (CXXMethodDecl *Method 8820 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8821 Method->setAccess(OldTemplateDecl->getAccess()); 8822 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8823 } 8824 8825 // If this is an explicit specialization of a member that is a function 8826 // template, mark it as a member specialization. 8827 if (IsExplicitSpecialization && 8828 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8829 NewTemplateDecl->setMemberSpecialization(); 8830 assert(OldTemplateDecl->isMemberSpecialization()); 8831 // Explicit specializations of a member template do not inherit deleted 8832 // status from the parent member template that they are specializing. 8833 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8834 FunctionDecl *const OldTemplatedDecl = 8835 OldTemplateDecl->getTemplatedDecl(); 8836 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8837 OldTemplatedDecl->setDeletedAsWritten(false); 8838 } 8839 } 8840 8841 } else { 8842 // This needs to happen first so that 'inline' propagates. 8843 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8844 8845 if (isa<CXXMethodDecl>(NewFD)) 8846 NewFD->setAccess(OldDecl->getAccess()); 8847 } 8848 } 8849 8850 // Semantic checking for this function declaration (in isolation). 8851 8852 if (getLangOpts().CPlusPlus) { 8853 // C++-specific checks. 8854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8855 CheckConstructor(Constructor); 8856 } else if (CXXDestructorDecl *Destructor = 8857 dyn_cast<CXXDestructorDecl>(NewFD)) { 8858 CXXRecordDecl *Record = Destructor->getParent(); 8859 QualType ClassType = Context.getTypeDeclType(Record); 8860 8861 // FIXME: Shouldn't we be able to perform this check even when the class 8862 // type is dependent? Both gcc and edg can handle that. 8863 if (!ClassType->isDependentType()) { 8864 DeclarationName Name 8865 = Context.DeclarationNames.getCXXDestructorName( 8866 Context.getCanonicalType(ClassType)); 8867 if (NewFD->getDeclName() != Name) { 8868 Diag(NewFD->getLocation(), diag::err_destructor_name); 8869 NewFD->setInvalidDecl(); 8870 return Redeclaration; 8871 } 8872 } 8873 } else if (CXXConversionDecl *Conversion 8874 = dyn_cast<CXXConversionDecl>(NewFD)) { 8875 ActOnConversionDeclarator(Conversion); 8876 } 8877 8878 // Find any virtual functions that this function overrides. 8879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8880 if (!Method->isFunctionTemplateSpecialization() && 8881 !Method->getDescribedFunctionTemplate() && 8882 Method->isCanonicalDecl()) { 8883 if (AddOverriddenMethods(Method->getParent(), Method)) { 8884 // If the function was marked as "static", we have a problem. 8885 if (NewFD->getStorageClass() == SC_Static) { 8886 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8887 } 8888 } 8889 } 8890 8891 if (Method->isStatic()) 8892 checkThisInStaticMemberFunctionType(Method); 8893 } 8894 8895 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8896 if (NewFD->isOverloadedOperator() && 8897 CheckOverloadedOperatorDeclaration(NewFD)) { 8898 NewFD->setInvalidDecl(); 8899 return Redeclaration; 8900 } 8901 8902 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8903 if (NewFD->getLiteralIdentifier() && 8904 CheckLiteralOperatorDeclaration(NewFD)) { 8905 NewFD->setInvalidDecl(); 8906 return Redeclaration; 8907 } 8908 8909 // In C++, check default arguments now that we have merged decls. Unless 8910 // the lexical context is the class, because in this case this is done 8911 // during delayed parsing anyway. 8912 if (!CurContext->isRecord()) 8913 CheckCXXDefaultArguments(NewFD); 8914 8915 // If this function declares a builtin function, check the type of this 8916 // declaration against the expected type for the builtin. 8917 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8918 ASTContext::GetBuiltinTypeError Error; 8919 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8920 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8921 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8922 // The type of this function differs from the type of the builtin, 8923 // so forget about the builtin entirely. 8924 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8925 } 8926 } 8927 8928 // If this function is declared as being extern "C", then check to see if 8929 // the function returns a UDT (class, struct, or union type) that is not C 8930 // compatible, and if it does, warn the user. 8931 // But, issue any diagnostic on the first declaration only. 8932 if (Previous.empty() && NewFD->isExternC()) { 8933 QualType R = NewFD->getReturnType(); 8934 if (R->isIncompleteType() && !R->isVoidType()) 8935 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8936 << NewFD << R; 8937 else if (!R.isPODType(Context) && !R->isVoidType() && 8938 !R->isObjCObjectPointerType()) 8939 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8940 } 8941 } 8942 return Redeclaration; 8943 } 8944 8945 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8946 // C++11 [basic.start.main]p3: 8947 // A program that [...] declares main to be inline, static or 8948 // constexpr is ill-formed. 8949 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8950 // appear in a declaration of main. 8951 // static main is not an error under C99, but we should warn about it. 8952 // We accept _Noreturn main as an extension. 8953 if (FD->getStorageClass() == SC_Static) 8954 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8955 ? diag::err_static_main : diag::warn_static_main) 8956 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8957 if (FD->isInlineSpecified()) 8958 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8959 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8960 if (DS.isNoreturnSpecified()) { 8961 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8962 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8963 Diag(NoreturnLoc, diag::ext_noreturn_main); 8964 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8965 << FixItHint::CreateRemoval(NoreturnRange); 8966 } 8967 if (FD->isConstexpr()) { 8968 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8969 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8970 FD->setConstexpr(false); 8971 } 8972 8973 if (getLangOpts().OpenCL) { 8974 Diag(FD->getLocation(), diag::err_opencl_no_main) 8975 << FD->hasAttr<OpenCLKernelAttr>(); 8976 FD->setInvalidDecl(); 8977 return; 8978 } 8979 8980 QualType T = FD->getType(); 8981 assert(T->isFunctionType() && "function decl is not of function type"); 8982 const FunctionType* FT = T->castAs<FunctionType>(); 8983 8984 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8985 // In C with GNU extensions we allow main() to have non-integer return 8986 // type, but we should warn about the extension, and we disable the 8987 // implicit-return-zero rule. 8988 8989 // GCC in C mode accepts qualified 'int'. 8990 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8991 FD->setHasImplicitReturnZero(true); 8992 else { 8993 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8994 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8995 if (RTRange.isValid()) 8996 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8997 << FixItHint::CreateReplacement(RTRange, "int"); 8998 } 8999 } else { 9000 // In C and C++, main magically returns 0 if you fall off the end; 9001 // set the flag which tells us that. 9002 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9003 9004 // All the standards say that main() should return 'int'. 9005 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9006 FD->setHasImplicitReturnZero(true); 9007 else { 9008 // Otherwise, this is just a flat-out error. 9009 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9010 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9011 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9012 : FixItHint()); 9013 FD->setInvalidDecl(true); 9014 } 9015 } 9016 9017 // Treat protoless main() as nullary. 9018 if (isa<FunctionNoProtoType>(FT)) return; 9019 9020 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9021 unsigned nparams = FTP->getNumParams(); 9022 assert(FD->getNumParams() == nparams); 9023 9024 bool HasExtraParameters = (nparams > 3); 9025 9026 if (FTP->isVariadic()) { 9027 Diag(FD->getLocation(), diag::ext_variadic_main); 9028 // FIXME: if we had information about the location of the ellipsis, we 9029 // could add a FixIt hint to remove it as a parameter. 9030 } 9031 9032 // Darwin passes an undocumented fourth argument of type char**. If 9033 // other platforms start sprouting these, the logic below will start 9034 // getting shifty. 9035 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9036 HasExtraParameters = false; 9037 9038 if (HasExtraParameters) { 9039 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9040 FD->setInvalidDecl(true); 9041 nparams = 3; 9042 } 9043 9044 // FIXME: a lot of the following diagnostics would be improved 9045 // if we had some location information about types. 9046 9047 QualType CharPP = 9048 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9049 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9050 9051 for (unsigned i = 0; i < nparams; ++i) { 9052 QualType AT = FTP->getParamType(i); 9053 9054 bool mismatch = true; 9055 9056 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9057 mismatch = false; 9058 else if (Expected[i] == CharPP) { 9059 // As an extension, the following forms are okay: 9060 // char const ** 9061 // char const * const * 9062 // char * const * 9063 9064 QualifierCollector qs; 9065 const PointerType* PT; 9066 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9067 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9068 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9069 Context.CharTy)) { 9070 qs.removeConst(); 9071 mismatch = !qs.empty(); 9072 } 9073 } 9074 9075 if (mismatch) { 9076 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9077 // TODO: suggest replacing given type with expected type 9078 FD->setInvalidDecl(true); 9079 } 9080 } 9081 9082 if (nparams == 1 && !FD->isInvalidDecl()) { 9083 Diag(FD->getLocation(), diag::warn_main_one_arg); 9084 } 9085 9086 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9087 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9088 FD->setInvalidDecl(); 9089 } 9090 } 9091 9092 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9093 QualType T = FD->getType(); 9094 assert(T->isFunctionType() && "function decl is not of function type"); 9095 const FunctionType *FT = T->castAs<FunctionType>(); 9096 9097 // Set an implicit return of 'zero' if the function can return some integral, 9098 // enumeration, pointer or nullptr type. 9099 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9100 FT->getReturnType()->isAnyPointerType() || 9101 FT->getReturnType()->isNullPtrType()) 9102 // DllMain is exempt because a return value of zero means it failed. 9103 if (FD->getName() != "DllMain") 9104 FD->setHasImplicitReturnZero(true); 9105 9106 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9107 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9108 FD->setInvalidDecl(); 9109 } 9110 } 9111 9112 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9113 // FIXME: Need strict checking. In C89, we need to check for 9114 // any assignment, increment, decrement, function-calls, or 9115 // commas outside of a sizeof. In C99, it's the same list, 9116 // except that the aforementioned are allowed in unevaluated 9117 // expressions. Everything else falls under the 9118 // "may accept other forms of constant expressions" exception. 9119 // (We never end up here for C++, so the constant expression 9120 // rules there don't matter.) 9121 const Expr *Culprit; 9122 if (Init->isConstantInitializer(Context, false, &Culprit)) 9123 return false; 9124 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9125 << Culprit->getSourceRange(); 9126 return true; 9127 } 9128 9129 namespace { 9130 // Visits an initialization expression to see if OrigDecl is evaluated in 9131 // its own initialization and throws a warning if it does. 9132 class SelfReferenceChecker 9133 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9134 Sema &S; 9135 Decl *OrigDecl; 9136 bool isRecordType; 9137 bool isPODType; 9138 bool isReferenceType; 9139 9140 bool isInitList; 9141 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9142 9143 public: 9144 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9145 9146 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9147 S(S), OrigDecl(OrigDecl) { 9148 isPODType = false; 9149 isRecordType = false; 9150 isReferenceType = false; 9151 isInitList = false; 9152 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9153 isPODType = VD->getType().isPODType(S.Context); 9154 isRecordType = VD->getType()->isRecordType(); 9155 isReferenceType = VD->getType()->isReferenceType(); 9156 } 9157 } 9158 9159 // For most expressions, just call the visitor. For initializer lists, 9160 // track the index of the field being initialized since fields are 9161 // initialized in order allowing use of previously initialized fields. 9162 void CheckExpr(Expr *E) { 9163 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9164 if (!InitList) { 9165 Visit(E); 9166 return; 9167 } 9168 9169 // Track and increment the index here. 9170 isInitList = true; 9171 InitFieldIndex.push_back(0); 9172 for (auto Child : InitList->children()) { 9173 CheckExpr(cast<Expr>(Child)); 9174 ++InitFieldIndex.back(); 9175 } 9176 InitFieldIndex.pop_back(); 9177 } 9178 9179 // Returns true if MemberExpr is checked and no futher checking is needed. 9180 // Returns false if additional checking is required. 9181 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9182 llvm::SmallVector<FieldDecl*, 4> Fields; 9183 Expr *Base = E; 9184 bool ReferenceField = false; 9185 9186 // Get the field memebers used. 9187 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9188 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9189 if (!FD) 9190 return false; 9191 Fields.push_back(FD); 9192 if (FD->getType()->isReferenceType()) 9193 ReferenceField = true; 9194 Base = ME->getBase()->IgnoreParenImpCasts(); 9195 } 9196 9197 // Keep checking only if the base Decl is the same. 9198 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9199 if (!DRE || DRE->getDecl() != OrigDecl) 9200 return false; 9201 9202 // A reference field can be bound to an unininitialized field. 9203 if (CheckReference && !ReferenceField) 9204 return true; 9205 9206 // Convert FieldDecls to their index number. 9207 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9208 for (const FieldDecl *I : llvm::reverse(Fields)) 9209 UsedFieldIndex.push_back(I->getFieldIndex()); 9210 9211 // See if a warning is needed by checking the first difference in index 9212 // numbers. If field being used has index less than the field being 9213 // initialized, then the use is safe. 9214 for (auto UsedIter = UsedFieldIndex.begin(), 9215 UsedEnd = UsedFieldIndex.end(), 9216 OrigIter = InitFieldIndex.begin(), 9217 OrigEnd = InitFieldIndex.end(); 9218 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9219 if (*UsedIter < *OrigIter) 9220 return true; 9221 if (*UsedIter > *OrigIter) 9222 break; 9223 } 9224 9225 // TODO: Add a different warning which will print the field names. 9226 HandleDeclRefExpr(DRE); 9227 return true; 9228 } 9229 9230 // For most expressions, the cast is directly above the DeclRefExpr. 9231 // For conditional operators, the cast can be outside the conditional 9232 // operator if both expressions are DeclRefExpr's. 9233 void HandleValue(Expr *E) { 9234 E = E->IgnoreParens(); 9235 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9236 HandleDeclRefExpr(DRE); 9237 return; 9238 } 9239 9240 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9241 Visit(CO->getCond()); 9242 HandleValue(CO->getTrueExpr()); 9243 HandleValue(CO->getFalseExpr()); 9244 return; 9245 } 9246 9247 if (BinaryConditionalOperator *BCO = 9248 dyn_cast<BinaryConditionalOperator>(E)) { 9249 Visit(BCO->getCond()); 9250 HandleValue(BCO->getFalseExpr()); 9251 return; 9252 } 9253 9254 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9255 HandleValue(OVE->getSourceExpr()); 9256 return; 9257 } 9258 9259 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9260 if (BO->getOpcode() == BO_Comma) { 9261 Visit(BO->getLHS()); 9262 HandleValue(BO->getRHS()); 9263 return; 9264 } 9265 } 9266 9267 if (isa<MemberExpr>(E)) { 9268 if (isInitList) { 9269 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9270 false /*CheckReference*/)) 9271 return; 9272 } 9273 9274 Expr *Base = E->IgnoreParenImpCasts(); 9275 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9276 // Check for static member variables and don't warn on them. 9277 if (!isa<FieldDecl>(ME->getMemberDecl())) 9278 return; 9279 Base = ME->getBase()->IgnoreParenImpCasts(); 9280 } 9281 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9282 HandleDeclRefExpr(DRE); 9283 return; 9284 } 9285 9286 Visit(E); 9287 } 9288 9289 // Reference types not handled in HandleValue are handled here since all 9290 // uses of references are bad, not just r-value uses. 9291 void VisitDeclRefExpr(DeclRefExpr *E) { 9292 if (isReferenceType) 9293 HandleDeclRefExpr(E); 9294 } 9295 9296 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9297 if (E->getCastKind() == CK_LValueToRValue) { 9298 HandleValue(E->getSubExpr()); 9299 return; 9300 } 9301 9302 Inherited::VisitImplicitCastExpr(E); 9303 } 9304 9305 void VisitMemberExpr(MemberExpr *E) { 9306 if (isInitList) { 9307 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9308 return; 9309 } 9310 9311 // Don't warn on arrays since they can be treated as pointers. 9312 if (E->getType()->canDecayToPointerType()) return; 9313 9314 // Warn when a non-static method call is followed by non-static member 9315 // field accesses, which is followed by a DeclRefExpr. 9316 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9317 bool Warn = (MD && !MD->isStatic()); 9318 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9319 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9320 if (!isa<FieldDecl>(ME->getMemberDecl())) 9321 Warn = false; 9322 Base = ME->getBase()->IgnoreParenImpCasts(); 9323 } 9324 9325 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9326 if (Warn) 9327 HandleDeclRefExpr(DRE); 9328 return; 9329 } 9330 9331 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9332 // Visit that expression. 9333 Visit(Base); 9334 } 9335 9336 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9337 Expr *Callee = E->getCallee(); 9338 9339 if (isa<UnresolvedLookupExpr>(Callee)) 9340 return Inherited::VisitCXXOperatorCallExpr(E); 9341 9342 Visit(Callee); 9343 for (auto Arg: E->arguments()) 9344 HandleValue(Arg->IgnoreParenImpCasts()); 9345 } 9346 9347 void VisitUnaryOperator(UnaryOperator *E) { 9348 // For POD record types, addresses of its own members are well-defined. 9349 if (E->getOpcode() == UO_AddrOf && isRecordType && 9350 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9351 if (!isPODType) 9352 HandleValue(E->getSubExpr()); 9353 return; 9354 } 9355 9356 if (E->isIncrementDecrementOp()) { 9357 HandleValue(E->getSubExpr()); 9358 return; 9359 } 9360 9361 Inherited::VisitUnaryOperator(E); 9362 } 9363 9364 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9365 9366 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9367 if (E->getConstructor()->isCopyConstructor()) { 9368 Expr *ArgExpr = E->getArg(0); 9369 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9370 if (ILE->getNumInits() == 1) 9371 ArgExpr = ILE->getInit(0); 9372 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9373 if (ICE->getCastKind() == CK_NoOp) 9374 ArgExpr = ICE->getSubExpr(); 9375 HandleValue(ArgExpr); 9376 return; 9377 } 9378 Inherited::VisitCXXConstructExpr(E); 9379 } 9380 9381 void VisitCallExpr(CallExpr *E) { 9382 // Treat std::move as a use. 9383 if (E->getNumArgs() == 1) { 9384 if (FunctionDecl *FD = E->getDirectCallee()) { 9385 if (FD->isInStdNamespace() && FD->getIdentifier() && 9386 FD->getIdentifier()->isStr("move")) { 9387 HandleValue(E->getArg(0)); 9388 return; 9389 } 9390 } 9391 } 9392 9393 Inherited::VisitCallExpr(E); 9394 } 9395 9396 void VisitBinaryOperator(BinaryOperator *E) { 9397 if (E->isCompoundAssignmentOp()) { 9398 HandleValue(E->getLHS()); 9399 Visit(E->getRHS()); 9400 return; 9401 } 9402 9403 Inherited::VisitBinaryOperator(E); 9404 } 9405 9406 // A custom visitor for BinaryConditionalOperator is needed because the 9407 // regular visitor would check the condition and true expression separately 9408 // but both point to the same place giving duplicate diagnostics. 9409 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9410 Visit(E->getCond()); 9411 Visit(E->getFalseExpr()); 9412 } 9413 9414 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9415 Decl* ReferenceDecl = DRE->getDecl(); 9416 if (OrigDecl != ReferenceDecl) return; 9417 unsigned diag; 9418 if (isReferenceType) { 9419 diag = diag::warn_uninit_self_reference_in_reference_init; 9420 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9421 diag = diag::warn_static_self_reference_in_init; 9422 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9423 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9424 DRE->getDecl()->getType()->isRecordType()) { 9425 diag = diag::warn_uninit_self_reference_in_init; 9426 } else { 9427 // Local variables will be handled by the CFG analysis. 9428 return; 9429 } 9430 9431 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9432 S.PDiag(diag) 9433 << DRE->getNameInfo().getName() 9434 << OrigDecl->getLocation() 9435 << DRE->getSourceRange()); 9436 } 9437 }; 9438 9439 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9440 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9441 bool DirectInit) { 9442 // Parameters arguments are occassionially constructed with itself, 9443 // for instance, in recursive functions. Skip them. 9444 if (isa<ParmVarDecl>(OrigDecl)) 9445 return; 9446 9447 E = E->IgnoreParens(); 9448 9449 // Skip checking T a = a where T is not a record or reference type. 9450 // Doing so is a way to silence uninitialized warnings. 9451 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9453 if (ICE->getCastKind() == CK_LValueToRValue) 9454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9455 if (DRE->getDecl() == OrigDecl) 9456 return; 9457 9458 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9459 } 9460 } // end anonymous namespace 9461 9462 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9463 DeclarationName Name, QualType Type, 9464 TypeSourceInfo *TSI, 9465 SourceRange Range, bool DirectInit, 9466 Expr *Init) { 9467 bool IsInitCapture = !VDecl; 9468 assert((!VDecl || !VDecl->isInitCapture()) && 9469 "init captures are expected to be deduced prior to initialization"); 9470 9471 // FIXME: Deduction for a decomposition declaration does weird things if the 9472 // initializer is an array. 9473 9474 ArrayRef<Expr *> DeduceInits = Init; 9475 if (DirectInit) { 9476 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9477 DeduceInits = PL->exprs(); 9478 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9479 DeduceInits = IL->inits(); 9480 } 9481 9482 // Deduction only works if we have exactly one source expression. 9483 if (DeduceInits.empty()) { 9484 // It isn't possible to write this directly, but it is possible to 9485 // end up in this situation with "auto x(some_pack...);" 9486 Diag(Init->getLocStart(), IsInitCapture 9487 ? diag::err_init_capture_no_expression 9488 : diag::err_auto_var_init_no_expression) 9489 << Name << Type << Range; 9490 return QualType(); 9491 } 9492 9493 if (DeduceInits.size() > 1) { 9494 Diag(DeduceInits[1]->getLocStart(), 9495 IsInitCapture ? diag::err_init_capture_multiple_expressions 9496 : diag::err_auto_var_init_multiple_expressions) 9497 << Name << Type << Range; 9498 return QualType(); 9499 } 9500 9501 Expr *DeduceInit = DeduceInits[0]; 9502 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9503 Diag(Init->getLocStart(), IsInitCapture 9504 ? diag::err_init_capture_paren_braces 9505 : diag::err_auto_var_init_paren_braces) 9506 << isa<InitListExpr>(Init) << Name << Type << Range; 9507 return QualType(); 9508 } 9509 9510 // Expressions default to 'id' when we're in a debugger. 9511 bool DefaultedAnyToId = false; 9512 if (getLangOpts().DebuggerCastResultToId && 9513 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9514 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9515 if (Result.isInvalid()) { 9516 return QualType(); 9517 } 9518 Init = Result.get(); 9519 DefaultedAnyToId = true; 9520 } 9521 9522 QualType DeducedType; 9523 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9524 if (!IsInitCapture) 9525 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9526 else if (isa<InitListExpr>(Init)) 9527 Diag(Range.getBegin(), 9528 diag::err_init_capture_deduction_failure_from_init_list) 9529 << Name 9530 << (DeduceInit->getType().isNull() ? TSI->getType() 9531 : DeduceInit->getType()) 9532 << DeduceInit->getSourceRange(); 9533 else 9534 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9535 << Name << TSI->getType() 9536 << (DeduceInit->getType().isNull() ? TSI->getType() 9537 : DeduceInit->getType()) 9538 << DeduceInit->getSourceRange(); 9539 } 9540 9541 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9542 // 'id' instead of a specific object type prevents most of our usual 9543 // checks. 9544 // We only want to warn outside of template instantiations, though: 9545 // inside a template, the 'id' could have come from a parameter. 9546 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9547 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9548 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9549 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9550 } 9551 9552 return DeducedType; 9553 } 9554 9555 /// AddInitializerToDecl - Adds the initializer Init to the 9556 /// declaration dcl. If DirectInit is true, this is C++ direct 9557 /// initialization rather than copy initialization. 9558 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9559 bool DirectInit, bool TypeMayContainAuto) { 9560 // If there is no declaration, there was an error parsing it. Just ignore 9561 // the initializer. 9562 if (!RealDecl || RealDecl->isInvalidDecl()) { 9563 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9564 return; 9565 } 9566 9567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9568 // Pure-specifiers are handled in ActOnPureSpecifier. 9569 Diag(Method->getLocation(), diag::err_member_function_initialization) 9570 << Method->getDeclName() << Init->getSourceRange(); 9571 Method->setInvalidDecl(); 9572 return; 9573 } 9574 9575 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9576 if (!VDecl) { 9577 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9578 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9579 RealDecl->setInvalidDecl(); 9580 return; 9581 } 9582 9583 // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not 9584 // permitted. 9585 if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init)) 9586 Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl; 9587 9588 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9589 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9590 // Attempt typo correction early so that the type of the init expression can 9591 // be deduced based on the chosen correction if the original init contains a 9592 // TypoExpr. 9593 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9594 if (!Res.isUsable()) { 9595 RealDecl->setInvalidDecl(); 9596 return; 9597 } 9598 Init = Res.get(); 9599 9600 QualType DeducedType = deduceVarTypeFromInitializer( 9601 VDecl, VDecl->getDeclName(), VDecl->getType(), 9602 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9603 if (DeducedType.isNull()) { 9604 RealDecl->setInvalidDecl(); 9605 return; 9606 } 9607 9608 VDecl->setType(DeducedType); 9609 assert(VDecl->isLinkageValid()); 9610 9611 // In ARC, infer lifetime. 9612 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9613 VDecl->setInvalidDecl(); 9614 9615 // If this is a redeclaration, check that the type we just deduced matches 9616 // the previously declared type. 9617 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9618 // We never need to merge the type, because we cannot form an incomplete 9619 // array of auto, nor deduce such a type. 9620 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9621 } 9622 9623 // Check the deduced type is valid for a variable declaration. 9624 CheckVariableDeclarationType(VDecl); 9625 if (VDecl->isInvalidDecl()) 9626 return; 9627 } 9628 9629 // dllimport cannot be used on variable definitions. 9630 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9631 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9632 VDecl->setInvalidDecl(); 9633 return; 9634 } 9635 9636 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9637 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9638 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9639 VDecl->setInvalidDecl(); 9640 return; 9641 } 9642 9643 if (!VDecl->getType()->isDependentType()) { 9644 // A definition must end up with a complete type, which means it must be 9645 // complete with the restriction that an array type might be completed by 9646 // the initializer; note that later code assumes this restriction. 9647 QualType BaseDeclType = VDecl->getType(); 9648 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9649 BaseDeclType = Array->getElementType(); 9650 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9651 diag::err_typecheck_decl_incomplete_type)) { 9652 RealDecl->setInvalidDecl(); 9653 return; 9654 } 9655 9656 // The variable can not have an abstract class type. 9657 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9658 diag::err_abstract_type_in_decl, 9659 AbstractVariableType)) 9660 VDecl->setInvalidDecl(); 9661 } 9662 9663 VarDecl *Def; 9664 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9665 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine())) { 9666 NamedDecl *Hidden = nullptr; 9667 if (!hasVisibleDefinition(Def, &Hidden) && 9668 (VDecl->getFormalLinkage() == InternalLinkage || 9669 VDecl->getDescribedVarTemplate() || 9670 VDecl->getNumTemplateParameterLists() || 9671 VDecl->getDeclContext()->isDependentContext())) { 9672 // The previous definition is hidden, and multiple definitions are 9673 // permitted (in separate TUs). Form another definition of it. 9674 } else { 9675 Diag(VDecl->getLocation(), diag::err_redefinition) 9676 << VDecl->getDeclName(); 9677 Diag(Def->getLocation(), diag::note_previous_definition); 9678 VDecl->setInvalidDecl(); 9679 return; 9680 } 9681 } 9682 9683 if (getLangOpts().CPlusPlus) { 9684 // C++ [class.static.data]p4 9685 // If a static data member is of const integral or const 9686 // enumeration type, its declaration in the class definition can 9687 // specify a constant-initializer which shall be an integral 9688 // constant expression (5.19). In that case, the member can appear 9689 // in integral constant expressions. The member shall still be 9690 // defined in a namespace scope if it is used in the program and the 9691 // namespace scope definition shall not contain an initializer. 9692 // 9693 // We already performed a redefinition check above, but for static 9694 // data members we also need to check whether there was an in-class 9695 // declaration with an initializer. 9696 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9697 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9698 << VDecl->getDeclName(); 9699 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9700 diag::note_previous_initializer) 9701 << 0; 9702 return; 9703 } 9704 9705 if (VDecl->hasLocalStorage()) 9706 getCurFunction()->setHasBranchProtectedScope(); 9707 9708 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9709 VDecl->setInvalidDecl(); 9710 return; 9711 } 9712 } 9713 9714 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9715 // a kernel function cannot be initialized." 9716 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9717 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9718 VDecl->setInvalidDecl(); 9719 return; 9720 } 9721 9722 // Get the decls type and save a reference for later, since 9723 // CheckInitializerTypes may change it. 9724 QualType DclT = VDecl->getType(), SavT = DclT; 9725 9726 // Expressions default to 'id' when we're in a debugger 9727 // and we are assigning it to a variable of Objective-C pointer type. 9728 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9729 Init->getType() == Context.UnknownAnyTy) { 9730 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9731 if (Result.isInvalid()) { 9732 VDecl->setInvalidDecl(); 9733 return; 9734 } 9735 Init = Result.get(); 9736 } 9737 9738 // Perform the initialization. 9739 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9740 if (!VDecl->isInvalidDecl()) { 9741 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9742 InitializationKind Kind = 9743 DirectInit 9744 ? CXXDirectInit 9745 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9746 Init->getLocStart(), 9747 Init->getLocEnd()) 9748 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9749 : InitializationKind::CreateCopy(VDecl->getLocation(), 9750 Init->getLocStart()); 9751 9752 MultiExprArg Args = Init; 9753 if (CXXDirectInit) 9754 Args = MultiExprArg(CXXDirectInit->getExprs(), 9755 CXXDirectInit->getNumExprs()); 9756 9757 // Try to correct any TypoExprs in the initialization arguments. 9758 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9759 ExprResult Res = CorrectDelayedTyposInExpr( 9760 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9761 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9762 return Init.Failed() ? ExprError() : E; 9763 }); 9764 if (Res.isInvalid()) { 9765 VDecl->setInvalidDecl(); 9766 } else if (Res.get() != Args[Idx]) { 9767 Args[Idx] = Res.get(); 9768 } 9769 } 9770 if (VDecl->isInvalidDecl()) 9771 return; 9772 9773 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9774 /*TopLevelOfInitList=*/false, 9775 /*TreatUnavailableAsInvalid=*/false); 9776 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9777 if (Result.isInvalid()) { 9778 VDecl->setInvalidDecl(); 9779 return; 9780 } 9781 9782 Init = Result.getAs<Expr>(); 9783 } 9784 9785 // Check for self-references within variable initializers. 9786 // Variables declared within a function/method body (except for references) 9787 // are handled by a dataflow analysis. 9788 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9789 VDecl->getType()->isReferenceType()) { 9790 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9791 } 9792 9793 // If the type changed, it means we had an incomplete type that was 9794 // completed by the initializer. For example: 9795 // int ary[] = { 1, 3, 5 }; 9796 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9797 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9798 VDecl->setType(DclT); 9799 9800 if (!VDecl->isInvalidDecl()) { 9801 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9802 9803 if (VDecl->hasAttr<BlocksAttr>()) 9804 checkRetainCycles(VDecl, Init); 9805 9806 // It is safe to assign a weak reference into a strong variable. 9807 // Although this code can still have problems: 9808 // id x = self.weakProp; 9809 // id y = self.weakProp; 9810 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9811 // paths through the function. This should be revisited if 9812 // -Wrepeated-use-of-weak is made flow-sensitive. 9813 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9814 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9815 Init->getLocStart())) 9816 getCurFunction()->markSafeWeakUse(Init); 9817 } 9818 9819 // The initialization is usually a full-expression. 9820 // 9821 // FIXME: If this is a braced initialization of an aggregate, it is not 9822 // an expression, and each individual field initializer is a separate 9823 // full-expression. For instance, in: 9824 // 9825 // struct Temp { ~Temp(); }; 9826 // struct S { S(Temp); }; 9827 // struct T { S a, b; } t = { Temp(), Temp() } 9828 // 9829 // we should destroy the first Temp before constructing the second. 9830 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9831 false, 9832 VDecl->isConstexpr()); 9833 if (Result.isInvalid()) { 9834 VDecl->setInvalidDecl(); 9835 return; 9836 } 9837 Init = Result.get(); 9838 9839 // Attach the initializer to the decl. 9840 VDecl->setInit(Init); 9841 9842 if (VDecl->isLocalVarDecl()) { 9843 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9844 // static storage duration shall be constant expressions or string literals. 9845 // C++ does not have this restriction. 9846 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9847 const Expr *Culprit; 9848 if (VDecl->getStorageClass() == SC_Static) 9849 CheckForConstantInitializer(Init, DclT); 9850 // C89 is stricter than C99 for non-static aggregate types. 9851 // C89 6.5.7p3: All the expressions [...] in an initializer list 9852 // for an object that has aggregate or union type shall be 9853 // constant expressions. 9854 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9855 isa<InitListExpr>(Init) && 9856 !Init->isConstantInitializer(Context, false, &Culprit)) 9857 Diag(Culprit->getExprLoc(), 9858 diag::ext_aggregate_init_not_constant) 9859 << Culprit->getSourceRange(); 9860 } 9861 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 9862 VDecl->getLexicalDeclContext()->isRecord()) { 9863 // This is an in-class initialization for a static data member, e.g., 9864 // 9865 // struct S { 9866 // static const int value = 17; 9867 // }; 9868 9869 // C++ [class.mem]p4: 9870 // A member-declarator can contain a constant-initializer only 9871 // if it declares a static member (9.4) of const integral or 9872 // const enumeration type, see 9.4.2. 9873 // 9874 // C++11 [class.static.data]p3: 9875 // If a non-volatile non-inline const static data member is of integral 9876 // or enumeration type, its declaration in the class definition can 9877 // specify a brace-or-equal-initializer in which every initalizer-clause 9878 // that is an assignment-expression is a constant expression. A static 9879 // data member of literal type can be declared in the class definition 9880 // with the constexpr specifier; if so, its declaration shall specify a 9881 // brace-or-equal-initializer in which every initializer-clause that is 9882 // an assignment-expression is a constant expression. 9883 9884 // Do nothing on dependent types. 9885 if (DclT->isDependentType()) { 9886 9887 // Allow any 'static constexpr' members, whether or not they are of literal 9888 // type. We separately check that every constexpr variable is of literal 9889 // type. 9890 } else if (VDecl->isConstexpr()) { 9891 9892 // Require constness. 9893 } else if (!DclT.isConstQualified()) { 9894 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9895 << Init->getSourceRange(); 9896 VDecl->setInvalidDecl(); 9897 9898 // We allow integer constant expressions in all cases. 9899 } else if (DclT->isIntegralOrEnumerationType()) { 9900 // Check whether the expression is a constant expression. 9901 SourceLocation Loc; 9902 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9903 // In C++11, a non-constexpr const static data member with an 9904 // in-class initializer cannot be volatile. 9905 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9906 else if (Init->isValueDependent()) 9907 ; // Nothing to check. 9908 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9909 ; // Ok, it's an ICE! 9910 else if (Init->isEvaluatable(Context)) { 9911 // If we can constant fold the initializer through heroics, accept it, 9912 // but report this as a use of an extension for -pedantic. 9913 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9914 << Init->getSourceRange(); 9915 } else { 9916 // Otherwise, this is some crazy unknown case. Report the issue at the 9917 // location provided by the isIntegerConstantExpr failed check. 9918 Diag(Loc, diag::err_in_class_initializer_non_constant) 9919 << Init->getSourceRange(); 9920 VDecl->setInvalidDecl(); 9921 } 9922 9923 // We allow foldable floating-point constants as an extension. 9924 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9925 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9926 // it anyway and provide a fixit to add the 'constexpr'. 9927 if (getLangOpts().CPlusPlus11) { 9928 Diag(VDecl->getLocation(), 9929 diag::ext_in_class_initializer_float_type_cxx11) 9930 << DclT << Init->getSourceRange(); 9931 Diag(VDecl->getLocStart(), 9932 diag::note_in_class_initializer_float_type_cxx11) 9933 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9934 } else { 9935 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9936 << DclT << Init->getSourceRange(); 9937 9938 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9939 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9940 << Init->getSourceRange(); 9941 VDecl->setInvalidDecl(); 9942 } 9943 } 9944 9945 // Suggest adding 'constexpr' in C++11 for literal types. 9946 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9947 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9948 << DclT << Init->getSourceRange() 9949 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9950 VDecl->setConstexpr(true); 9951 9952 } else { 9953 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9954 << DclT << Init->getSourceRange(); 9955 VDecl->setInvalidDecl(); 9956 } 9957 } else if (VDecl->isFileVarDecl()) { 9958 // In C, extern is typically used to avoid tentative definitions when 9959 // declaring variables in headers, but adding an intializer makes it a 9960 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 9961 // In C++, extern is often used to give implictly static const variables 9962 // external linkage, so don't warn in that case. If selectany is present, 9963 // this might be header code intended for C and C++ inclusion, so apply the 9964 // C++ rules. 9965 if (VDecl->getStorageClass() == SC_Extern && 9966 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 9967 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 9968 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 9969 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9970 Diag(VDecl->getLocation(), diag::warn_extern_init); 9971 9972 // C99 6.7.8p4. All file scoped initializers need to be constant. 9973 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9974 CheckForConstantInitializer(Init, DclT); 9975 } 9976 9977 // We will represent direct-initialization similarly to copy-initialization: 9978 // int x(1); -as-> int x = 1; 9979 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9980 // 9981 // Clients that want to distinguish between the two forms, can check for 9982 // direct initializer using VarDecl::getInitStyle(). 9983 // A major benefit is that clients that don't particularly care about which 9984 // exactly form was it (like the CodeGen) can handle both cases without 9985 // special case code. 9986 9987 // C++ 8.5p11: 9988 // The form of initialization (using parentheses or '=') is generally 9989 // insignificant, but does matter when the entity being initialized has a 9990 // class type. 9991 if (CXXDirectInit) { 9992 assert(DirectInit && "Call-style initializer must be direct init."); 9993 VDecl->setInitStyle(VarDecl::CallInit); 9994 } else if (DirectInit) { 9995 // This must be list-initialization. No other way is direct-initialization. 9996 VDecl->setInitStyle(VarDecl::ListInit); 9997 } 9998 9999 CheckCompleteVariableDeclaration(VDecl); 10000 } 10001 10002 /// ActOnInitializerError - Given that there was an error parsing an 10003 /// initializer for the given declaration, try to return to some form 10004 /// of sanity. 10005 void Sema::ActOnInitializerError(Decl *D) { 10006 // Our main concern here is re-establishing invariants like "a 10007 // variable's type is either dependent or complete". 10008 if (!D || D->isInvalidDecl()) return; 10009 10010 VarDecl *VD = dyn_cast<VarDecl>(D); 10011 if (!VD) return; 10012 10013 // Bindings are not usable if we can't make sense of the initializer. 10014 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10015 for (auto *BD : DD->bindings()) 10016 BD->setInvalidDecl(); 10017 10018 // Auto types are meaningless if we can't make sense of the initializer. 10019 if (ParsingInitForAutoVars.count(D)) { 10020 D->setInvalidDecl(); 10021 return; 10022 } 10023 10024 QualType Ty = VD->getType(); 10025 if (Ty->isDependentType()) return; 10026 10027 // Require a complete type. 10028 if (RequireCompleteType(VD->getLocation(), 10029 Context.getBaseElementType(Ty), 10030 diag::err_typecheck_decl_incomplete_type)) { 10031 VD->setInvalidDecl(); 10032 return; 10033 } 10034 10035 // Require a non-abstract type. 10036 if (RequireNonAbstractType(VD->getLocation(), Ty, 10037 diag::err_abstract_type_in_decl, 10038 AbstractVariableType)) { 10039 VD->setInvalidDecl(); 10040 return; 10041 } 10042 10043 // Don't bother complaining about constructors or destructors, 10044 // though. 10045 } 10046 10047 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 10048 bool TypeMayContainAuto) { 10049 // If there is no declaration, there was an error parsing it. Just ignore it. 10050 if (!RealDecl) 10051 return; 10052 10053 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10054 QualType Type = Var->getType(); 10055 10056 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10057 if (isa<DecompositionDecl>(RealDecl)) { 10058 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10059 Var->setInvalidDecl(); 10060 return; 10061 } 10062 10063 // C++11 [dcl.spec.auto]p3 10064 if (TypeMayContainAuto && Type->getContainedAutoType()) { 10065 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10066 << Var->getDeclName() << Type; 10067 Var->setInvalidDecl(); 10068 return; 10069 } 10070 10071 // C++11 [class.static.data]p3: A static data member can be declared with 10072 // the constexpr specifier; if so, its declaration shall specify 10073 // a brace-or-equal-initializer. 10074 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10075 // the definition of a variable [...] or the declaration of a static data 10076 // member. 10077 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 10078 if (Var->isStaticDataMember()) { 10079 // C++1z removes the relevant rule; the in-class declaration is always 10080 // a definition there. 10081 if (!getLangOpts().CPlusPlus1z) { 10082 Diag(Var->getLocation(), 10083 diag::err_constexpr_static_mem_var_requires_init) 10084 << Var->getDeclName(); 10085 Var->setInvalidDecl(); 10086 return; 10087 } 10088 } else { 10089 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10090 Var->setInvalidDecl(); 10091 return; 10092 } 10093 } 10094 10095 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10096 // definition having the concept specifier is called a variable concept. A 10097 // concept definition refers to [...] a variable concept and its initializer. 10098 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10099 if (VTD->isConcept()) { 10100 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10101 Var->setInvalidDecl(); 10102 return; 10103 } 10104 } 10105 10106 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10107 // be initialized. 10108 if (!Var->isInvalidDecl() && 10109 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10110 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10111 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10112 Var->setInvalidDecl(); 10113 return; 10114 } 10115 10116 switch (Var->isThisDeclarationADefinition()) { 10117 case VarDecl::Definition: 10118 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10119 break; 10120 10121 // We have an out-of-line definition of a static data member 10122 // that has an in-class initializer, so we type-check this like 10123 // a declaration. 10124 // 10125 // Fall through 10126 10127 case VarDecl::DeclarationOnly: 10128 // It's only a declaration. 10129 10130 // Block scope. C99 6.7p7: If an identifier for an object is 10131 // declared with no linkage (C99 6.2.2p6), the type for the 10132 // object shall be complete. 10133 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10134 !Var->hasLinkage() && !Var->isInvalidDecl() && 10135 RequireCompleteType(Var->getLocation(), Type, 10136 diag::err_typecheck_decl_incomplete_type)) 10137 Var->setInvalidDecl(); 10138 10139 // Make sure that the type is not abstract. 10140 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10141 RequireNonAbstractType(Var->getLocation(), Type, 10142 diag::err_abstract_type_in_decl, 10143 AbstractVariableType)) 10144 Var->setInvalidDecl(); 10145 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10146 Var->getStorageClass() == SC_PrivateExtern) { 10147 Diag(Var->getLocation(), diag::warn_private_extern); 10148 Diag(Var->getLocation(), diag::note_private_extern); 10149 } 10150 10151 return; 10152 10153 case VarDecl::TentativeDefinition: 10154 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10155 // object that has file scope without an initializer, and without a 10156 // storage-class specifier or with the storage-class specifier "static", 10157 // constitutes a tentative definition. Note: A tentative definition with 10158 // external linkage is valid (C99 6.2.2p5). 10159 if (!Var->isInvalidDecl()) { 10160 if (const IncompleteArrayType *ArrayT 10161 = Context.getAsIncompleteArrayType(Type)) { 10162 if (RequireCompleteType(Var->getLocation(), 10163 ArrayT->getElementType(), 10164 diag::err_illegal_decl_array_incomplete_type)) 10165 Var->setInvalidDecl(); 10166 } else if (Var->getStorageClass() == SC_Static) { 10167 // C99 6.9.2p3: If the declaration of an identifier for an object is 10168 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10169 // declared type shall not be an incomplete type. 10170 // NOTE: code such as the following 10171 // static struct s; 10172 // struct s { int a; }; 10173 // is accepted by gcc. Hence here we issue a warning instead of 10174 // an error and we do not invalidate the static declaration. 10175 // NOTE: to avoid multiple warnings, only check the first declaration. 10176 if (Var->isFirstDecl()) 10177 RequireCompleteType(Var->getLocation(), Type, 10178 diag::ext_typecheck_decl_incomplete_type); 10179 } 10180 } 10181 10182 // Record the tentative definition; we're done. 10183 if (!Var->isInvalidDecl()) 10184 TentativeDefinitions.push_back(Var); 10185 return; 10186 } 10187 10188 // Provide a specific diagnostic for uninitialized variable 10189 // definitions with incomplete array type. 10190 if (Type->isIncompleteArrayType()) { 10191 Diag(Var->getLocation(), 10192 diag::err_typecheck_incomplete_array_needs_initializer); 10193 Var->setInvalidDecl(); 10194 return; 10195 } 10196 10197 // Provide a specific diagnostic for uninitialized variable 10198 // definitions with reference type. 10199 if (Type->isReferenceType()) { 10200 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10201 << Var->getDeclName() 10202 << SourceRange(Var->getLocation(), Var->getLocation()); 10203 Var->setInvalidDecl(); 10204 return; 10205 } 10206 10207 // Do not attempt to type-check the default initializer for a 10208 // variable with dependent type. 10209 if (Type->isDependentType()) 10210 return; 10211 10212 if (Var->isInvalidDecl()) 10213 return; 10214 10215 if (!Var->hasAttr<AliasAttr>()) { 10216 if (RequireCompleteType(Var->getLocation(), 10217 Context.getBaseElementType(Type), 10218 diag::err_typecheck_decl_incomplete_type)) { 10219 Var->setInvalidDecl(); 10220 return; 10221 } 10222 } else { 10223 return; 10224 } 10225 10226 // The variable can not have an abstract class type. 10227 if (RequireNonAbstractType(Var->getLocation(), Type, 10228 diag::err_abstract_type_in_decl, 10229 AbstractVariableType)) { 10230 Var->setInvalidDecl(); 10231 return; 10232 } 10233 10234 // Check for jumps past the implicit initializer. C++0x 10235 // clarifies that this applies to a "variable with automatic 10236 // storage duration", not a "local variable". 10237 // C++11 [stmt.dcl]p3 10238 // A program that jumps from a point where a variable with automatic 10239 // storage duration is not in scope to a point where it is in scope is 10240 // ill-formed unless the variable has scalar type, class type with a 10241 // trivial default constructor and a trivial destructor, a cv-qualified 10242 // version of one of these types, or an array of one of the preceding 10243 // types and is declared without an initializer. 10244 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10245 if (const RecordType *Record 10246 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10247 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10248 // Mark the function for further checking even if the looser rules of 10249 // C++11 do not require such checks, so that we can diagnose 10250 // incompatibilities with C++98. 10251 if (!CXXRecord->isPOD()) 10252 getCurFunction()->setHasBranchProtectedScope(); 10253 } 10254 } 10255 10256 // C++03 [dcl.init]p9: 10257 // If no initializer is specified for an object, and the 10258 // object is of (possibly cv-qualified) non-POD class type (or 10259 // array thereof), the object shall be default-initialized; if 10260 // the object is of const-qualified type, the underlying class 10261 // type shall have a user-declared default 10262 // constructor. Otherwise, if no initializer is specified for 10263 // a non- static object, the object and its subobjects, if 10264 // any, have an indeterminate initial value); if the object 10265 // or any of its subobjects are of const-qualified type, the 10266 // program is ill-formed. 10267 // C++0x [dcl.init]p11: 10268 // If no initializer is specified for an object, the object is 10269 // default-initialized; [...]. 10270 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10271 InitializationKind Kind 10272 = InitializationKind::CreateDefault(Var->getLocation()); 10273 10274 InitializationSequence InitSeq(*this, Entity, Kind, None); 10275 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10276 if (Init.isInvalid()) 10277 Var->setInvalidDecl(); 10278 else if (Init.get()) { 10279 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10280 // This is important for template substitution. 10281 Var->setInitStyle(VarDecl::CallInit); 10282 } 10283 10284 CheckCompleteVariableDeclaration(Var); 10285 } 10286 } 10287 10288 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10289 // If there is no declaration, there was an error parsing it. Ignore it. 10290 if (!D) 10291 return; 10292 10293 VarDecl *VD = dyn_cast<VarDecl>(D); 10294 if (!VD) { 10295 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10296 D->setInvalidDecl(); 10297 return; 10298 } 10299 10300 VD->setCXXForRangeDecl(true); 10301 10302 // for-range-declaration cannot be given a storage class specifier. 10303 int Error = -1; 10304 switch (VD->getStorageClass()) { 10305 case SC_None: 10306 break; 10307 case SC_Extern: 10308 Error = 0; 10309 break; 10310 case SC_Static: 10311 Error = 1; 10312 break; 10313 case SC_PrivateExtern: 10314 Error = 2; 10315 break; 10316 case SC_Auto: 10317 Error = 3; 10318 break; 10319 case SC_Register: 10320 Error = 4; 10321 break; 10322 } 10323 if (Error != -1) { 10324 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10325 << VD->getDeclName() << Error; 10326 D->setInvalidDecl(); 10327 } 10328 } 10329 10330 StmtResult 10331 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10332 IdentifierInfo *Ident, 10333 ParsedAttributes &Attrs, 10334 SourceLocation AttrEnd) { 10335 // C++1y [stmt.iter]p1: 10336 // A range-based for statement of the form 10337 // for ( for-range-identifier : for-range-initializer ) statement 10338 // is equivalent to 10339 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10340 DeclSpec DS(Attrs.getPool().getFactory()); 10341 10342 const char *PrevSpec; 10343 unsigned DiagID; 10344 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10345 getPrintingPolicy()); 10346 10347 Declarator D(DS, Declarator::ForContext); 10348 D.SetIdentifier(Ident, IdentLoc); 10349 D.takeAttributes(Attrs, AttrEnd); 10350 10351 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10352 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10353 EmptyAttrs, IdentLoc); 10354 Decl *Var = ActOnDeclarator(S, D); 10355 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10356 FinalizeDeclaration(Var); 10357 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10358 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10359 } 10360 10361 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10362 if (var->isInvalidDecl()) return; 10363 10364 if (getLangOpts().OpenCL) { 10365 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10366 // initialiser 10367 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10368 !var->hasInit()) { 10369 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10370 << 1 /*Init*/; 10371 var->setInvalidDecl(); 10372 return; 10373 } 10374 } 10375 10376 // In Objective-C, don't allow jumps past the implicit initialization of a 10377 // local retaining variable. 10378 if (getLangOpts().ObjC1 && 10379 var->hasLocalStorage()) { 10380 switch (var->getType().getObjCLifetime()) { 10381 case Qualifiers::OCL_None: 10382 case Qualifiers::OCL_ExplicitNone: 10383 case Qualifiers::OCL_Autoreleasing: 10384 break; 10385 10386 case Qualifiers::OCL_Weak: 10387 case Qualifiers::OCL_Strong: 10388 getCurFunction()->setHasBranchProtectedScope(); 10389 break; 10390 } 10391 } 10392 10393 // Warn about externally-visible variables being defined without a 10394 // prior declaration. We only want to do this for global 10395 // declarations, but we also specifically need to avoid doing it for 10396 // class members because the linkage of an anonymous class can 10397 // change if it's later given a typedef name. 10398 if (var->isThisDeclarationADefinition() && 10399 var->getDeclContext()->getRedeclContext()->isFileContext() && 10400 var->isExternallyVisible() && var->hasLinkage() && 10401 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10402 var->getLocation())) { 10403 // Find a previous declaration that's not a definition. 10404 VarDecl *prev = var->getPreviousDecl(); 10405 while (prev && prev->isThisDeclarationADefinition()) 10406 prev = prev->getPreviousDecl(); 10407 10408 if (!prev) 10409 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10410 } 10411 10412 // Cache the result of checking for constant initialization. 10413 Optional<bool> CacheHasConstInit; 10414 const Expr *CacheCulprit; 10415 auto checkConstInit = [&]() mutable { 10416 if (!CacheHasConstInit) 10417 CacheHasConstInit = var->getInit()->isConstantInitializer( 10418 Context, var->getType()->isReferenceType(), &CacheCulprit); 10419 return *CacheHasConstInit; 10420 }; 10421 10422 if (var->getTLSKind() == VarDecl::TLS_Static) { 10423 if (var->getType().isDestructedType()) { 10424 // GNU C++98 edits for __thread, [basic.start.term]p3: 10425 // The type of an object with thread storage duration shall not 10426 // have a non-trivial destructor. 10427 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10428 if (getLangOpts().CPlusPlus11) 10429 Diag(var->getLocation(), diag::note_use_thread_local); 10430 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10431 if (!checkConstInit()) { 10432 // GNU C++98 edits for __thread, [basic.start.init]p4: 10433 // An object of thread storage duration shall not require dynamic 10434 // initialization. 10435 // FIXME: Need strict checking here. 10436 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10437 << CacheCulprit->getSourceRange(); 10438 if (getLangOpts().CPlusPlus11) 10439 Diag(var->getLocation(), diag::note_use_thread_local); 10440 } 10441 } 10442 } 10443 10444 // Apply section attributes and pragmas to global variables. 10445 bool GlobalStorage = var->hasGlobalStorage(); 10446 if (GlobalStorage && var->isThisDeclarationADefinition() && 10447 ActiveTemplateInstantiations.empty()) { 10448 PragmaStack<StringLiteral *> *Stack = nullptr; 10449 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10450 if (var->getType().isConstQualified()) 10451 Stack = &ConstSegStack; 10452 else if (!var->getInit()) { 10453 Stack = &BSSSegStack; 10454 SectionFlags |= ASTContext::PSF_Write; 10455 } else { 10456 Stack = &DataSegStack; 10457 SectionFlags |= ASTContext::PSF_Write; 10458 } 10459 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10460 var->addAttr(SectionAttr::CreateImplicit( 10461 Context, SectionAttr::Declspec_allocate, 10462 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10463 } 10464 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10465 if (UnifySection(SA->getName(), SectionFlags, var)) 10466 var->dropAttr<SectionAttr>(); 10467 10468 // Apply the init_seg attribute if this has an initializer. If the 10469 // initializer turns out to not be dynamic, we'll end up ignoring this 10470 // attribute. 10471 if (CurInitSeg && var->getInit()) 10472 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10473 CurInitSegLoc)); 10474 } 10475 10476 // All the following checks are C++ only. 10477 if (!getLangOpts().CPlusPlus) return; 10478 10479 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10480 CheckCompleteDecompositionDeclaration(DD); 10481 10482 QualType type = var->getType(); 10483 if (type->isDependentType()) return; 10484 10485 // __block variables might require us to capture a copy-initializer. 10486 if (var->hasAttr<BlocksAttr>()) { 10487 // It's currently invalid to ever have a __block variable with an 10488 // array type; should we diagnose that here? 10489 10490 // Regardless, we don't want to ignore array nesting when 10491 // constructing this copy. 10492 if (type->isStructureOrClassType()) { 10493 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10494 SourceLocation poi = var->getLocation(); 10495 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10496 ExprResult result 10497 = PerformMoveOrCopyInitialization( 10498 InitializedEntity::InitializeBlock(poi, type, false), 10499 var, var->getType(), varRef, /*AllowNRVO=*/true); 10500 if (!result.isInvalid()) { 10501 result = MaybeCreateExprWithCleanups(result); 10502 Expr *init = result.getAs<Expr>(); 10503 Context.setBlockVarCopyInits(var, init); 10504 } 10505 } 10506 } 10507 10508 Expr *Init = var->getInit(); 10509 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10510 QualType baseType = Context.getBaseElementType(type); 10511 10512 if (!var->getDeclContext()->isDependentContext() && 10513 Init && !Init->isValueDependent()) { 10514 10515 if (var->isConstexpr()) { 10516 SmallVector<PartialDiagnosticAt, 8> Notes; 10517 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10518 SourceLocation DiagLoc = var->getLocation(); 10519 // If the note doesn't add any useful information other than a source 10520 // location, fold it into the primary diagnostic. 10521 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10522 diag::note_invalid_subexpr_in_const_expr) { 10523 DiagLoc = Notes[0].first; 10524 Notes.clear(); 10525 } 10526 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10527 << var << Init->getSourceRange(); 10528 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10529 Diag(Notes[I].first, Notes[I].second); 10530 } 10531 } else if (var->isUsableInConstantExpressions(Context)) { 10532 // Check whether the initializer of a const variable of integral or 10533 // enumeration type is an ICE now, since we can't tell whether it was 10534 // initialized by a constant expression if we check later. 10535 var->checkInitIsICE(); 10536 } 10537 10538 // Don't emit further diagnostics about constexpr globals since they 10539 // were just diagnosed. 10540 if (!var->isConstexpr() && GlobalStorage && 10541 var->hasAttr<RequireConstantInitAttr>()) { 10542 // FIXME: Need strict checking in C++03 here. 10543 bool DiagErr = getLangOpts().CPlusPlus11 10544 ? !var->checkInitIsICE() : !checkConstInit(); 10545 if (DiagErr) { 10546 auto attr = var->getAttr<RequireConstantInitAttr>(); 10547 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10548 << Init->getSourceRange(); 10549 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10550 << attr->getRange(); 10551 } 10552 } 10553 else if (!var->isConstexpr() && IsGlobal && 10554 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10555 var->getLocation())) { 10556 // Warn about globals which don't have a constant initializer. Don't 10557 // warn about globals with a non-trivial destructor because we already 10558 // warned about them. 10559 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10560 if (!(RD && !RD->hasTrivialDestructor())) { 10561 if (!checkConstInit()) 10562 Diag(var->getLocation(), diag::warn_global_constructor) 10563 << Init->getSourceRange(); 10564 } 10565 } 10566 } 10567 10568 // Require the destructor. 10569 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10570 FinalizeVarWithDestructor(var, recordType); 10571 10572 // If this variable must be emitted, add it as an initializer for the current 10573 // module. 10574 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10575 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10576 } 10577 10578 /// \brief Determines if a variable's alignment is dependent. 10579 static bool hasDependentAlignment(VarDecl *VD) { 10580 if (VD->getType()->isDependentType()) 10581 return true; 10582 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10583 if (I->isAlignmentDependent()) 10584 return true; 10585 return false; 10586 } 10587 10588 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10589 /// any semantic actions necessary after any initializer has been attached. 10590 void 10591 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10592 // Note that we are no longer parsing the initializer for this declaration. 10593 ParsingInitForAutoVars.erase(ThisDecl); 10594 10595 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10596 if (!VD) 10597 return; 10598 10599 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10600 for (auto *BD : DD->bindings()) { 10601 if (ThisDecl->isInvalidDecl()) 10602 BD->setInvalidDecl(); 10603 FinalizeDeclaration(BD); 10604 } 10605 } 10606 10607 checkAttributesAfterMerging(*this, *VD); 10608 10609 // Perform TLS alignment check here after attributes attached to the variable 10610 // which may affect the alignment have been processed. Only perform the check 10611 // if the target has a maximum TLS alignment (zero means no constraints). 10612 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10613 // Protect the check so that it's not performed on dependent types and 10614 // dependent alignments (we can't determine the alignment in that case). 10615 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10616 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10617 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10618 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10619 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10620 << (unsigned)MaxAlignChars.getQuantity(); 10621 } 10622 } 10623 } 10624 10625 if (VD->isStaticLocal()) { 10626 if (FunctionDecl *FD = 10627 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10628 // Static locals inherit dll attributes from their function. 10629 if (Attr *A = getDLLAttr(FD)) { 10630 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10631 NewAttr->setInherited(true); 10632 VD->addAttr(NewAttr); 10633 } 10634 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10635 // function, only __shared__ variables may be declared with 10636 // static storage class. 10637 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 10638 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) && 10639 !VD->hasAttr<CUDASharedAttr>()) { 10640 Diag(VD->getLocation(), diag::err_device_static_local_var); 10641 VD->setInvalidDecl(); 10642 } 10643 } 10644 } 10645 10646 // Perform check for initializers of device-side global variables. 10647 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10648 // 7.5). We must also apply the same checks to all __shared__ 10649 // variables whether they are local or not. CUDA also allows 10650 // constant initializers for __constant__ and __device__ variables. 10651 if (getLangOpts().CUDA) { 10652 const Expr *Init = VD->getInit(); 10653 if (Init && VD->hasGlobalStorage()) { 10654 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10655 VD->hasAttr<CUDASharedAttr>()) { 10656 assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>())); 10657 bool AllowedInit = false; 10658 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10659 AllowedInit = 10660 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10661 // We'll allow constant initializers even if it's a non-empty 10662 // constructor according to CUDA rules. This deviates from NVCC, 10663 // but allows us to handle things like constexpr constructors. 10664 if (!AllowedInit && 10665 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10666 AllowedInit = VD->getInit()->isConstantInitializer( 10667 Context, VD->getType()->isReferenceType()); 10668 10669 // Also make sure that destructor, if there is one, is empty. 10670 if (AllowedInit) 10671 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10672 AllowedInit = 10673 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10674 10675 if (!AllowedInit) { 10676 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10677 ? diag::err_shared_var_init 10678 : diag::err_dynamic_var_init) 10679 << Init->getSourceRange(); 10680 VD->setInvalidDecl(); 10681 } 10682 } else { 10683 // This is a host-side global variable. Check that the initializer is 10684 // callable from the host side. 10685 const FunctionDecl *InitFn = nullptr; 10686 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 10687 InitFn = CE->getConstructor(); 10688 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 10689 InitFn = CE->getDirectCallee(); 10690 } 10691 if (InitFn) { 10692 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 10693 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 10694 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 10695 << InitFnTarget << InitFn; 10696 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 10697 VD->setInvalidDecl(); 10698 } 10699 } 10700 } 10701 } 10702 } 10703 10704 // Grab the dllimport or dllexport attribute off of the VarDecl. 10705 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10706 10707 // Imported static data members cannot be defined out-of-line. 10708 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10709 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10710 VD->isThisDeclarationADefinition()) { 10711 // We allow definitions of dllimport class template static data members 10712 // with a warning. 10713 CXXRecordDecl *Context = 10714 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10715 bool IsClassTemplateMember = 10716 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10717 Context->getDescribedClassTemplate(); 10718 10719 Diag(VD->getLocation(), 10720 IsClassTemplateMember 10721 ? diag::warn_attribute_dllimport_static_field_definition 10722 : diag::err_attribute_dllimport_static_field_definition); 10723 Diag(IA->getLocation(), diag::note_attribute); 10724 if (!IsClassTemplateMember) 10725 VD->setInvalidDecl(); 10726 } 10727 } 10728 10729 // dllimport/dllexport variables cannot be thread local, their TLS index 10730 // isn't exported with the variable. 10731 if (DLLAttr && VD->getTLSKind()) { 10732 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10733 if (F && getDLLAttr(F)) { 10734 assert(VD->isStaticLocal()); 10735 // But if this is a static local in a dlimport/dllexport function, the 10736 // function will never be inlined, which means the var would never be 10737 // imported, so having it marked import/export is safe. 10738 } else { 10739 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10740 << DLLAttr; 10741 VD->setInvalidDecl(); 10742 } 10743 } 10744 10745 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10746 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10747 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10748 VD->dropAttr<UsedAttr>(); 10749 } 10750 } 10751 10752 const DeclContext *DC = VD->getDeclContext(); 10753 // If there's a #pragma GCC visibility in scope, and this isn't a class 10754 // member, set the visibility of this variable. 10755 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10756 AddPushedVisibilityAttribute(VD); 10757 10758 // FIXME: Warn on unused templates. 10759 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10760 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10761 MarkUnusedFileScopedDecl(VD); 10762 10763 // Now we have parsed the initializer and can update the table of magic 10764 // tag values. 10765 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10766 !VD->getType()->isIntegralOrEnumerationType()) 10767 return; 10768 10769 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10770 const Expr *MagicValueExpr = VD->getInit(); 10771 if (!MagicValueExpr) { 10772 continue; 10773 } 10774 llvm::APSInt MagicValueInt; 10775 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10776 Diag(I->getRange().getBegin(), 10777 diag::err_type_tag_for_datatype_not_ice) 10778 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10779 continue; 10780 } 10781 if (MagicValueInt.getActiveBits() > 64) { 10782 Diag(I->getRange().getBegin(), 10783 diag::err_type_tag_for_datatype_too_large) 10784 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10785 continue; 10786 } 10787 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10788 RegisterTypeTagForDatatype(I->getArgumentKind(), 10789 MagicValue, 10790 I->getMatchingCType(), 10791 I->getLayoutCompatible(), 10792 I->getMustBeNull()); 10793 } 10794 } 10795 10796 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10797 ArrayRef<Decl *> Group) { 10798 SmallVector<Decl*, 8> Decls; 10799 10800 if (DS.isTypeSpecOwned()) 10801 Decls.push_back(DS.getRepAsDecl()); 10802 10803 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10804 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 10805 bool DiagnosedMultipleDecomps = false; 10806 10807 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10808 if (Decl *D = Group[i]) { 10809 auto *DD = dyn_cast<DeclaratorDecl>(D); 10810 if (DD && !FirstDeclaratorInGroup) 10811 FirstDeclaratorInGroup = DD; 10812 10813 auto *Decomp = dyn_cast<DecompositionDecl>(D); 10814 if (Decomp && !FirstDecompDeclaratorInGroup) 10815 FirstDecompDeclaratorInGroup = Decomp; 10816 10817 // A decomposition declaration cannot be combined with any other 10818 // declaration in the same group. 10819 auto *OtherDD = FirstDeclaratorInGroup; 10820 if (OtherDD == FirstDecompDeclaratorInGroup) 10821 OtherDD = DD; 10822 if (OtherDD && FirstDecompDeclaratorInGroup && 10823 OtherDD != FirstDecompDeclaratorInGroup && 10824 !DiagnosedMultipleDecomps) { 10825 Diag(FirstDecompDeclaratorInGroup->getLocation(), 10826 diag::err_decomp_decl_not_alone) 10827 << OtherDD->getSourceRange(); 10828 DiagnosedMultipleDecomps = true; 10829 } 10830 10831 Decls.push_back(D); 10832 } 10833 } 10834 10835 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10836 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10837 handleTagNumbering(Tag, S); 10838 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10839 getLangOpts().CPlusPlus) 10840 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10841 } 10842 } 10843 10844 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10845 } 10846 10847 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10848 /// group, performing any necessary semantic checking. 10849 Sema::DeclGroupPtrTy 10850 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10851 bool TypeMayContainAuto) { 10852 // C++0x [dcl.spec.auto]p7: 10853 // If the type deduced for the template parameter U is not the same in each 10854 // deduction, the program is ill-formed. 10855 // FIXME: When initializer-list support is added, a distinction is needed 10856 // between the deduced type U and the deduced type which 'auto' stands for. 10857 // auto a = 0, b = { 1, 2, 3 }; 10858 // is legal because the deduced type U is 'int' in both cases. 10859 if (TypeMayContainAuto && Group.size() > 1) { 10860 QualType Deduced; 10861 CanQualType DeducedCanon; 10862 VarDecl *DeducedDecl = nullptr; 10863 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10864 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10865 AutoType *AT = D->getType()->getContainedAutoType(); 10866 // Don't reissue diagnostics when instantiating a template. 10867 if (AT && D->isInvalidDecl()) 10868 break; 10869 QualType U = AT ? AT->getDeducedType() : QualType(); 10870 if (!U.isNull()) { 10871 CanQualType UCanon = Context.getCanonicalType(U); 10872 if (Deduced.isNull()) { 10873 Deduced = U; 10874 DeducedCanon = UCanon; 10875 DeducedDecl = D; 10876 } else if (DeducedCanon != UCanon) { 10877 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10878 diag::err_auto_different_deductions) 10879 << (unsigned)AT->getKeyword() 10880 << Deduced << DeducedDecl->getDeclName() 10881 << U << D->getDeclName() 10882 << DeducedDecl->getInit()->getSourceRange() 10883 << D->getInit()->getSourceRange(); 10884 D->setInvalidDecl(); 10885 break; 10886 } 10887 } 10888 } 10889 } 10890 } 10891 10892 ActOnDocumentableDecls(Group); 10893 10894 return DeclGroupPtrTy::make( 10895 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10896 } 10897 10898 void Sema::ActOnDocumentableDecl(Decl *D) { 10899 ActOnDocumentableDecls(D); 10900 } 10901 10902 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10903 // Don't parse the comment if Doxygen diagnostics are ignored. 10904 if (Group.empty() || !Group[0]) 10905 return; 10906 10907 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10908 Group[0]->getLocation()) && 10909 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10910 Group[0]->getLocation())) 10911 return; 10912 10913 if (Group.size() >= 2) { 10914 // This is a decl group. Normally it will contain only declarations 10915 // produced from declarator list. But in case we have any definitions or 10916 // additional declaration references: 10917 // 'typedef struct S {} S;' 10918 // 'typedef struct S *S;' 10919 // 'struct S *pS;' 10920 // FinalizeDeclaratorGroup adds these as separate declarations. 10921 Decl *MaybeTagDecl = Group[0]; 10922 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10923 Group = Group.slice(1); 10924 } 10925 } 10926 10927 // See if there are any new comments that are not attached to a decl. 10928 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10929 if (!Comments.empty() && 10930 !Comments.back()->isAttached()) { 10931 // There is at least one comment that not attached to a decl. 10932 // Maybe it should be attached to one of these decls? 10933 // 10934 // Note that this way we pick up not only comments that precede the 10935 // declaration, but also comments that *follow* the declaration -- thanks to 10936 // the lookahead in the lexer: we've consumed the semicolon and looked 10937 // ahead through comments. 10938 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10939 Context.getCommentForDecl(Group[i], &PP); 10940 } 10941 } 10942 10943 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10944 /// to introduce parameters into function prototype scope. 10945 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10946 const DeclSpec &DS = D.getDeclSpec(); 10947 10948 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10949 10950 // C++03 [dcl.stc]p2 also permits 'auto'. 10951 StorageClass SC = SC_None; 10952 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10953 SC = SC_Register; 10954 } else if (getLangOpts().CPlusPlus && 10955 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10956 SC = SC_Auto; 10957 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10958 Diag(DS.getStorageClassSpecLoc(), 10959 diag::err_invalid_storage_class_in_func_decl); 10960 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10961 } 10962 10963 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10964 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10965 << DeclSpec::getSpecifierName(TSCS); 10966 if (DS.isInlineSpecified()) 10967 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 10968 << getLangOpts().CPlusPlus1z; 10969 if (DS.isConstexprSpecified()) 10970 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10971 << 0; 10972 if (DS.isConceptSpecified()) 10973 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 10974 10975 DiagnoseFunctionSpecifiers(DS); 10976 10977 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10978 QualType parmDeclType = TInfo->getType(); 10979 10980 if (getLangOpts().CPlusPlus) { 10981 // Check that there are no default arguments inside the type of this 10982 // parameter. 10983 CheckExtraCXXDefaultArguments(D); 10984 10985 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10986 if (D.getCXXScopeSpec().isSet()) { 10987 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10988 << D.getCXXScopeSpec().getRange(); 10989 D.getCXXScopeSpec().clear(); 10990 } 10991 } 10992 10993 // Ensure we have a valid name 10994 IdentifierInfo *II = nullptr; 10995 if (D.hasName()) { 10996 II = D.getIdentifier(); 10997 if (!II) { 10998 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10999 << GetNameForDeclarator(D).getName(); 11000 D.setInvalidType(true); 11001 } 11002 } 11003 11004 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11005 if (II) { 11006 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11007 ForRedeclaration); 11008 LookupName(R, S); 11009 if (R.isSingleResult()) { 11010 NamedDecl *PrevDecl = R.getFoundDecl(); 11011 if (PrevDecl->isTemplateParameter()) { 11012 // Maybe we will complain about the shadowed template parameter. 11013 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11014 // Just pretend that we didn't see the previous declaration. 11015 PrevDecl = nullptr; 11016 } else if (S->isDeclScope(PrevDecl)) { 11017 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11018 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11019 11020 // Recover by removing the name 11021 II = nullptr; 11022 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11023 D.setInvalidType(true); 11024 } 11025 } 11026 } 11027 11028 // Temporarily put parameter variables in the translation unit, not 11029 // the enclosing context. This prevents them from accidentally 11030 // looking like class members in C++. 11031 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11032 D.getLocStart(), 11033 D.getIdentifierLoc(), II, 11034 parmDeclType, TInfo, 11035 SC); 11036 11037 if (D.isInvalidType()) 11038 New->setInvalidDecl(); 11039 11040 assert(S->isFunctionPrototypeScope()); 11041 assert(S->getFunctionPrototypeDepth() >= 1); 11042 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11043 S->getNextFunctionPrototypeIndex()); 11044 11045 // Add the parameter declaration into this scope. 11046 S->AddDecl(New); 11047 if (II) 11048 IdResolver.AddDecl(New); 11049 11050 ProcessDeclAttributes(S, New, D); 11051 11052 if (D.getDeclSpec().isModulePrivateSpecified()) 11053 Diag(New->getLocation(), diag::err_module_private_local) 11054 << 1 << New->getDeclName() 11055 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11056 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11057 11058 if (New->hasAttr<BlocksAttr>()) { 11059 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11060 } 11061 return New; 11062 } 11063 11064 /// \brief Synthesizes a variable for a parameter arising from a 11065 /// typedef. 11066 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11067 SourceLocation Loc, 11068 QualType T) { 11069 /* FIXME: setting StartLoc == Loc. 11070 Would it be worth to modify callers so as to provide proper source 11071 location for the unnamed parameters, embedding the parameter's type? */ 11072 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11073 T, Context.getTrivialTypeSourceInfo(T, Loc), 11074 SC_None, nullptr); 11075 Param->setImplicit(); 11076 return Param; 11077 } 11078 11079 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11080 // Don't diagnose unused-parameter errors in template instantiations; we 11081 // will already have done so in the template itself. 11082 if (!ActiveTemplateInstantiations.empty()) 11083 return; 11084 11085 for (const ParmVarDecl *Parameter : Parameters) { 11086 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11087 !Parameter->hasAttr<UnusedAttr>()) { 11088 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11089 << Parameter->getDeclName(); 11090 } 11091 } 11092 } 11093 11094 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11095 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11096 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11097 return; 11098 11099 // Warn if the return value is pass-by-value and larger than the specified 11100 // threshold. 11101 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11102 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11103 if (Size > LangOpts.NumLargeByValueCopy) 11104 Diag(D->getLocation(), diag::warn_return_value_size) 11105 << D->getDeclName() << Size; 11106 } 11107 11108 // Warn if any parameter is pass-by-value and larger than the specified 11109 // threshold. 11110 for (const ParmVarDecl *Parameter : Parameters) { 11111 QualType T = Parameter->getType(); 11112 if (T->isDependentType() || !T.isPODType(Context)) 11113 continue; 11114 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11115 if (Size > LangOpts.NumLargeByValueCopy) 11116 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11117 << Parameter->getDeclName() << Size; 11118 } 11119 } 11120 11121 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11122 SourceLocation NameLoc, IdentifierInfo *Name, 11123 QualType T, TypeSourceInfo *TSInfo, 11124 StorageClass SC) { 11125 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11126 if (getLangOpts().ObjCAutoRefCount && 11127 T.getObjCLifetime() == Qualifiers::OCL_None && 11128 T->isObjCLifetimeType()) { 11129 11130 Qualifiers::ObjCLifetime lifetime; 11131 11132 // Special cases for arrays: 11133 // - if it's const, use __unsafe_unretained 11134 // - otherwise, it's an error 11135 if (T->isArrayType()) { 11136 if (!T.isConstQualified()) { 11137 DelayedDiagnostics.add( 11138 sema::DelayedDiagnostic::makeForbiddenType( 11139 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11140 } 11141 lifetime = Qualifiers::OCL_ExplicitNone; 11142 } else { 11143 lifetime = T->getObjCARCImplicitLifetime(); 11144 } 11145 T = Context.getLifetimeQualifiedType(T, lifetime); 11146 } 11147 11148 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11149 Context.getAdjustedParameterType(T), 11150 TSInfo, SC, nullptr); 11151 11152 // Parameters can not be abstract class types. 11153 // For record types, this is done by the AbstractClassUsageDiagnoser once 11154 // the class has been completely parsed. 11155 if (!CurContext->isRecord() && 11156 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11157 AbstractParamType)) 11158 New->setInvalidDecl(); 11159 11160 // Parameter declarators cannot be interface types. All ObjC objects are 11161 // passed by reference. 11162 if (T->isObjCObjectType()) { 11163 SourceLocation TypeEndLoc = 11164 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11165 Diag(NameLoc, 11166 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11167 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11168 T = Context.getObjCObjectPointerType(T); 11169 New->setType(T); 11170 } 11171 11172 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11173 // duration shall not be qualified by an address-space qualifier." 11174 // Since all parameters have automatic store duration, they can not have 11175 // an address space. 11176 if (T.getAddressSpace() != 0) { 11177 // OpenCL allows function arguments declared to be an array of a type 11178 // to be qualified with an address space. 11179 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11180 Diag(NameLoc, diag::err_arg_with_address_space); 11181 New->setInvalidDecl(); 11182 } 11183 } 11184 11185 return New; 11186 } 11187 11188 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11189 SourceLocation LocAfterDecls) { 11190 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11191 11192 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11193 // for a K&R function. 11194 if (!FTI.hasPrototype) { 11195 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11196 --i; 11197 if (FTI.Params[i].Param == nullptr) { 11198 SmallString<256> Code; 11199 llvm::raw_svector_ostream(Code) 11200 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11201 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11202 << FTI.Params[i].Ident 11203 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11204 11205 // Implicitly declare the argument as type 'int' for lack of a better 11206 // type. 11207 AttributeFactory attrs; 11208 DeclSpec DS(attrs); 11209 const char* PrevSpec; // unused 11210 unsigned DiagID; // unused 11211 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11212 DiagID, Context.getPrintingPolicy()); 11213 // Use the identifier location for the type source range. 11214 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11215 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11216 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11217 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11218 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11219 } 11220 } 11221 } 11222 } 11223 11224 Decl * 11225 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11226 MultiTemplateParamsArg TemplateParameterLists, 11227 SkipBodyInfo *SkipBody) { 11228 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11229 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11230 Scope *ParentScope = FnBodyScope->getParent(); 11231 11232 D.setFunctionDefinitionKind(FDK_Definition); 11233 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11234 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11235 } 11236 11237 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11238 Consumer.HandleInlineFunctionDefinition(D); 11239 } 11240 11241 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11242 const FunctionDecl*& PossibleZeroParamPrototype) { 11243 // Don't warn about invalid declarations. 11244 if (FD->isInvalidDecl()) 11245 return false; 11246 11247 // Or declarations that aren't global. 11248 if (!FD->isGlobal()) 11249 return false; 11250 11251 // Don't warn about C++ member functions. 11252 if (isa<CXXMethodDecl>(FD)) 11253 return false; 11254 11255 // Don't warn about 'main'. 11256 if (FD->isMain()) 11257 return false; 11258 11259 // Don't warn about inline functions. 11260 if (FD->isInlined()) 11261 return false; 11262 11263 // Don't warn about function templates. 11264 if (FD->getDescribedFunctionTemplate()) 11265 return false; 11266 11267 // Don't warn about function template specializations. 11268 if (FD->isFunctionTemplateSpecialization()) 11269 return false; 11270 11271 // Don't warn for OpenCL kernels. 11272 if (FD->hasAttr<OpenCLKernelAttr>()) 11273 return false; 11274 11275 // Don't warn on explicitly deleted functions. 11276 if (FD->isDeleted()) 11277 return false; 11278 11279 bool MissingPrototype = true; 11280 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11281 Prev; Prev = Prev->getPreviousDecl()) { 11282 // Ignore any declarations that occur in function or method 11283 // scope, because they aren't visible from the header. 11284 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11285 continue; 11286 11287 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11288 if (FD->getNumParams() == 0) 11289 PossibleZeroParamPrototype = Prev; 11290 break; 11291 } 11292 11293 return MissingPrototype; 11294 } 11295 11296 void 11297 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11298 const FunctionDecl *EffectiveDefinition, 11299 SkipBodyInfo *SkipBody) { 11300 // Don't complain if we're in GNU89 mode and the previous definition 11301 // was an extern inline function. 11302 const FunctionDecl *Definition = EffectiveDefinition; 11303 if (!Definition) 11304 if (!FD->isDefined(Definition)) 11305 return; 11306 11307 if (canRedefineFunction(Definition, getLangOpts())) 11308 return; 11309 11310 // If we don't have a visible definition of the function, and it's inline or 11311 // a template, skip the new definition. 11312 if (SkipBody && !hasVisibleDefinition(Definition) && 11313 (Definition->getFormalLinkage() == InternalLinkage || 11314 Definition->isInlined() || 11315 Definition->getDescribedFunctionTemplate() || 11316 Definition->getNumTemplateParameterLists())) { 11317 SkipBody->ShouldSkip = true; 11318 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11319 makeMergedDefinitionVisible(TD, FD->getLocation()); 11320 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11321 FD->getLocation()); 11322 return; 11323 } 11324 11325 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11326 Definition->getStorageClass() == SC_Extern) 11327 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11328 << FD->getDeclName() << getLangOpts().CPlusPlus; 11329 else 11330 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11331 11332 Diag(Definition->getLocation(), diag::note_previous_definition); 11333 FD->setInvalidDecl(); 11334 } 11335 11336 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11337 Sema &S) { 11338 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11339 11340 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11341 LSI->CallOperator = CallOperator; 11342 LSI->Lambda = LambdaClass; 11343 LSI->ReturnType = CallOperator->getReturnType(); 11344 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11345 11346 if (LCD == LCD_None) 11347 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11348 else if (LCD == LCD_ByCopy) 11349 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11350 else if (LCD == LCD_ByRef) 11351 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11352 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11353 11354 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11355 LSI->Mutable = !CallOperator->isConst(); 11356 11357 // Add the captures to the LSI so they can be noted as already 11358 // captured within tryCaptureVar. 11359 auto I = LambdaClass->field_begin(); 11360 for (const auto &C : LambdaClass->captures()) { 11361 if (C.capturesVariable()) { 11362 VarDecl *VD = C.getCapturedVar(); 11363 if (VD->isInitCapture()) 11364 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11365 QualType CaptureType = VD->getType(); 11366 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11367 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11368 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11369 /*EllipsisLoc*/C.isPackExpansion() 11370 ? C.getEllipsisLoc() : SourceLocation(), 11371 CaptureType, /*Expr*/ nullptr); 11372 11373 } else if (C.capturesThis()) { 11374 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11375 /*Expr*/ nullptr, 11376 C.getCaptureKind() == LCK_StarThis); 11377 } else { 11378 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11379 } 11380 ++I; 11381 } 11382 } 11383 11384 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11385 SkipBodyInfo *SkipBody) { 11386 // Clear the last template instantiation error context. 11387 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11388 11389 if (!D) 11390 return D; 11391 FunctionDecl *FD = nullptr; 11392 11393 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11394 FD = FunTmpl->getTemplatedDecl(); 11395 else 11396 FD = cast<FunctionDecl>(D); 11397 11398 // See if this is a redefinition. 11399 if (!FD->isLateTemplateParsed()) { 11400 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11401 11402 // If we're skipping the body, we're done. Don't enter the scope. 11403 if (SkipBody && SkipBody->ShouldSkip) 11404 return D; 11405 } 11406 11407 // If we are instantiating a generic lambda call operator, push 11408 // a LambdaScopeInfo onto the function stack. But use the information 11409 // that's already been calculated (ActOnLambdaExpr) to prime the current 11410 // LambdaScopeInfo. 11411 // When the template operator is being specialized, the LambdaScopeInfo, 11412 // has to be properly restored so that tryCaptureVariable doesn't try 11413 // and capture any new variables. In addition when calculating potential 11414 // captures during transformation of nested lambdas, it is necessary to 11415 // have the LSI properly restored. 11416 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11417 assert(ActiveTemplateInstantiations.size() && 11418 "There should be an active template instantiation on the stack " 11419 "when instantiating a generic lambda!"); 11420 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11421 } 11422 else 11423 // Enter a new function scope 11424 PushFunctionScope(); 11425 11426 // Builtin functions cannot be defined. 11427 if (unsigned BuiltinID = FD->getBuiltinID()) { 11428 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11429 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11430 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11431 FD->setInvalidDecl(); 11432 } 11433 } 11434 11435 // The return type of a function definition must be complete 11436 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11437 QualType ResultType = FD->getReturnType(); 11438 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11439 !FD->isInvalidDecl() && 11440 RequireCompleteType(FD->getLocation(), ResultType, 11441 diag::err_func_def_incomplete_result)) 11442 FD->setInvalidDecl(); 11443 11444 if (FnBodyScope) 11445 PushDeclContext(FnBodyScope, FD); 11446 11447 // Check the validity of our function parameters 11448 CheckParmsForFunctionDef(FD->parameters(), 11449 /*CheckParameterNames=*/true); 11450 11451 // Introduce our parameters into the function scope 11452 for (auto Param : FD->parameters()) { 11453 Param->setOwningFunction(FD); 11454 11455 // If this has an identifier, add it to the scope stack. 11456 if (Param->getIdentifier() && FnBodyScope) { 11457 CheckShadow(FnBodyScope, Param); 11458 11459 PushOnScopeChains(Param, FnBodyScope); 11460 } 11461 } 11462 11463 // If we had any tags defined in the function prototype, 11464 // introduce them into the function scope. 11465 if (FnBodyScope) { 11466 for (ArrayRef<NamedDecl *>::iterator 11467 I = FD->getDeclsInPrototypeScope().begin(), 11468 E = FD->getDeclsInPrototypeScope().end(); 11469 I != E; ++I) { 11470 NamedDecl *D = *I; 11471 11472 // Some of these decls (like enums) may have been pinned to the 11473 // translation unit for lack of a real context earlier. If so, remove 11474 // from the translation unit and reattach to the current context. 11475 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11476 // Is the decl actually in the context? 11477 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11478 Context.getTranslationUnitDecl()->removeDecl(D); 11479 // Either way, reassign the lexical decl context to our FunctionDecl. 11480 D->setLexicalDeclContext(CurContext); 11481 } 11482 11483 // If the decl has a non-null name, make accessible in the current scope. 11484 if (!D->getName().empty()) 11485 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11486 11487 // Similarly, dive into enums and fish their constants out, making them 11488 // accessible in this scope. 11489 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11490 for (auto *EI : ED->enumerators()) 11491 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11492 } 11493 } 11494 } 11495 11496 // Ensure that the function's exception specification is instantiated. 11497 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11498 ResolveExceptionSpec(D->getLocation(), FPT); 11499 11500 // dllimport cannot be applied to non-inline function definitions. 11501 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11502 !FD->isTemplateInstantiation()) { 11503 assert(!FD->hasAttr<DLLExportAttr>()); 11504 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11505 FD->setInvalidDecl(); 11506 return D; 11507 } 11508 // We want to attach documentation to original Decl (which might be 11509 // a function template). 11510 ActOnDocumentableDecl(D); 11511 if (getCurLexicalContext()->isObjCContainer() && 11512 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11513 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11514 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11515 11516 return D; 11517 } 11518 11519 /// \brief Given the set of return statements within a function body, 11520 /// compute the variables that are subject to the named return value 11521 /// optimization. 11522 /// 11523 /// Each of the variables that is subject to the named return value 11524 /// optimization will be marked as NRVO variables in the AST, and any 11525 /// return statement that has a marked NRVO variable as its NRVO candidate can 11526 /// use the named return value optimization. 11527 /// 11528 /// This function applies a very simplistic algorithm for NRVO: if every return 11529 /// statement in the scope of a variable has the same NRVO candidate, that 11530 /// candidate is an NRVO variable. 11531 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11532 ReturnStmt **Returns = Scope->Returns.data(); 11533 11534 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11535 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11536 if (!NRVOCandidate->isNRVOVariable()) 11537 Returns[I]->setNRVOCandidate(nullptr); 11538 } 11539 } 11540 } 11541 11542 bool Sema::canDelayFunctionBody(const Declarator &D) { 11543 // We can't delay parsing the body of a constexpr function template (yet). 11544 if (D.getDeclSpec().isConstexprSpecified()) 11545 return false; 11546 11547 // We can't delay parsing the body of a function template with a deduced 11548 // return type (yet). 11549 if (D.getDeclSpec().containsPlaceholderType()) { 11550 // If the placeholder introduces a non-deduced trailing return type, 11551 // we can still delay parsing it. 11552 if (D.getNumTypeObjects()) { 11553 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11554 if (Outer.Kind == DeclaratorChunk::Function && 11555 Outer.Fun.hasTrailingReturnType()) { 11556 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11557 return Ty.isNull() || !Ty->isUndeducedType(); 11558 } 11559 } 11560 return false; 11561 } 11562 11563 return true; 11564 } 11565 11566 bool Sema::canSkipFunctionBody(Decl *D) { 11567 // We cannot skip the body of a function (or function template) which is 11568 // constexpr, since we may need to evaluate its body in order to parse the 11569 // rest of the file. 11570 // We cannot skip the body of a function with an undeduced return type, 11571 // because any callers of that function need to know the type. 11572 if (const FunctionDecl *FD = D->getAsFunction()) 11573 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11574 return false; 11575 return Consumer.shouldSkipFunctionBody(D); 11576 } 11577 11578 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11579 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11580 FD->setHasSkippedBody(); 11581 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11582 MD->setHasSkippedBody(); 11583 return Decl; 11584 } 11585 11586 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11587 return ActOnFinishFunctionBody(D, BodyArg, false); 11588 } 11589 11590 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11591 bool IsInstantiation) { 11592 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11593 11594 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11595 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11596 11597 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty()) 11598 CheckCompletedCoroutineBody(FD, Body); 11599 11600 if (FD) { 11601 FD->setBody(Body); 11602 11603 if (getLangOpts().CPlusPlus14) { 11604 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11605 FD->getReturnType()->isUndeducedType()) { 11606 // If the function has a deduced result type but contains no 'return' 11607 // statements, the result type as written must be exactly 'auto', and 11608 // the deduced result type is 'void'. 11609 if (!FD->getReturnType()->getAs<AutoType>()) { 11610 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11611 << FD->getReturnType(); 11612 FD->setInvalidDecl(); 11613 } else { 11614 // Substitute 'void' for the 'auto' in the type. 11615 TypeLoc ResultType = getReturnTypeLoc(FD); 11616 Context.adjustDeducedFunctionResultType( 11617 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11618 } 11619 } 11620 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11621 // In C++11, we don't use 'auto' deduction rules for lambda call 11622 // operators because we don't support return type deduction. 11623 auto *LSI = getCurLambda(); 11624 if (LSI->HasImplicitReturnType) { 11625 deduceClosureReturnType(*LSI); 11626 11627 // C++11 [expr.prim.lambda]p4: 11628 // [...] if there are no return statements in the compound-statement 11629 // [the deduced type is] the type void 11630 QualType RetType = 11631 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11632 11633 // Update the return type to the deduced type. 11634 const FunctionProtoType *Proto = 11635 FD->getType()->getAs<FunctionProtoType>(); 11636 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11637 Proto->getExtProtoInfo())); 11638 } 11639 } 11640 11641 // The only way to be included in UndefinedButUsed is if there is an 11642 // ODR use before the definition. Avoid the expensive map lookup if this 11643 // is the first declaration. 11644 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11645 if (!FD->isExternallyVisible()) 11646 UndefinedButUsed.erase(FD); 11647 else if (FD->isInlined() && 11648 !LangOpts.GNUInline && 11649 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11650 UndefinedButUsed.erase(FD); 11651 } 11652 11653 // If the function implicitly returns zero (like 'main') or is naked, 11654 // don't complain about missing return statements. 11655 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11656 WP.disableCheckFallThrough(); 11657 11658 // MSVC permits the use of pure specifier (=0) on function definition, 11659 // defined at class scope, warn about this non-standard construct. 11660 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11661 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11662 11663 if (!FD->isInvalidDecl()) { 11664 // Don't diagnose unused parameters of defaulted or deleted functions. 11665 if (!FD->isDeleted() && !FD->isDefaulted()) 11666 DiagnoseUnusedParameters(FD->parameters()); 11667 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11668 FD->getReturnType(), FD); 11669 11670 // If this is a structor, we need a vtable. 11671 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11672 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11673 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11674 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11675 11676 // Try to apply the named return value optimization. We have to check 11677 // if we can do this here because lambdas keep return statements around 11678 // to deduce an implicit return type. 11679 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11680 !FD->isDependentContext()) 11681 computeNRVO(Body, getCurFunction()); 11682 } 11683 11684 // GNU warning -Wmissing-prototypes: 11685 // Warn if a global function is defined without a previous 11686 // prototype declaration. This warning is issued even if the 11687 // definition itself provides a prototype. The aim is to detect 11688 // global functions that fail to be declared in header files. 11689 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11690 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11691 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11692 11693 if (PossibleZeroParamPrototype) { 11694 // We found a declaration that is not a prototype, 11695 // but that could be a zero-parameter prototype 11696 if (TypeSourceInfo *TI = 11697 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11698 TypeLoc TL = TI->getTypeLoc(); 11699 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11700 Diag(PossibleZeroParamPrototype->getLocation(), 11701 diag::note_declaration_not_a_prototype) 11702 << PossibleZeroParamPrototype 11703 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11704 } 11705 } 11706 } 11707 11708 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11709 const CXXMethodDecl *KeyFunction; 11710 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11711 MD->isVirtual() && 11712 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11713 MD == KeyFunction->getCanonicalDecl()) { 11714 // Update the key-function state if necessary for this ABI. 11715 if (FD->isInlined() && 11716 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11717 Context.setNonKeyFunction(MD); 11718 11719 // If the newly-chosen key function is already defined, then we 11720 // need to mark the vtable as used retroactively. 11721 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11722 const FunctionDecl *Definition; 11723 if (KeyFunction && KeyFunction->isDefined(Definition)) 11724 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11725 } else { 11726 // We just defined they key function; mark the vtable as used. 11727 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11728 } 11729 } 11730 } 11731 11732 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11733 "Function parsing confused"); 11734 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11735 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11736 MD->setBody(Body); 11737 if (!MD->isInvalidDecl()) { 11738 DiagnoseUnusedParameters(MD->parameters()); 11739 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 11740 MD->getReturnType(), MD); 11741 11742 if (Body) 11743 computeNRVO(Body, getCurFunction()); 11744 } 11745 if (getCurFunction()->ObjCShouldCallSuper) { 11746 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11747 << MD->getSelector().getAsString(); 11748 getCurFunction()->ObjCShouldCallSuper = false; 11749 } 11750 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11751 const ObjCMethodDecl *InitMethod = nullptr; 11752 bool isDesignated = 11753 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11754 assert(isDesignated && InitMethod); 11755 (void)isDesignated; 11756 11757 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11758 auto IFace = MD->getClassInterface(); 11759 if (!IFace) 11760 return false; 11761 auto SuperD = IFace->getSuperClass(); 11762 if (!SuperD) 11763 return false; 11764 return SuperD->getIdentifier() == 11765 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11766 }; 11767 // Don't issue this warning for unavailable inits or direct subclasses 11768 // of NSObject. 11769 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11770 Diag(MD->getLocation(), 11771 diag::warn_objc_designated_init_missing_super_call); 11772 Diag(InitMethod->getLocation(), 11773 diag::note_objc_designated_init_marked_here); 11774 } 11775 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11776 } 11777 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11778 // Don't issue this warning for unavaialable inits. 11779 if (!MD->isUnavailable()) 11780 Diag(MD->getLocation(), 11781 diag::warn_objc_secondary_init_missing_init_call); 11782 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11783 } 11784 } else { 11785 return nullptr; 11786 } 11787 11788 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 11789 DiagnoseUnguardedAvailabilityViolations(dcl); 11790 11791 assert(!getCurFunction()->ObjCShouldCallSuper && 11792 "This should only be set for ObjC methods, which should have been " 11793 "handled in the block above."); 11794 11795 // Verify and clean out per-function state. 11796 if (Body && (!FD || !FD->isDefaulted())) { 11797 // C++ constructors that have function-try-blocks can't have return 11798 // statements in the handlers of that block. (C++ [except.handle]p14) 11799 // Verify this. 11800 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11801 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11802 11803 // Verify that gotos and switch cases don't jump into scopes illegally. 11804 if (getCurFunction()->NeedsScopeChecking() && 11805 !PP.isCodeCompletionEnabled()) 11806 DiagnoseInvalidJumps(Body); 11807 11808 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11809 if (!Destructor->getParent()->isDependentType()) 11810 CheckDestructor(Destructor); 11811 11812 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11813 Destructor->getParent()); 11814 } 11815 11816 // If any errors have occurred, clear out any temporaries that may have 11817 // been leftover. This ensures that these temporaries won't be picked up for 11818 // deletion in some later function. 11819 if (getDiagnostics().hasErrorOccurred() || 11820 getDiagnostics().getSuppressAllDiagnostics()) { 11821 DiscardCleanupsInEvaluationContext(); 11822 } 11823 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11824 !isa<FunctionTemplateDecl>(dcl)) { 11825 // Since the body is valid, issue any analysis-based warnings that are 11826 // enabled. 11827 ActivePolicy = &WP; 11828 } 11829 11830 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11831 (!CheckConstexprFunctionDecl(FD) || 11832 !CheckConstexprFunctionBody(FD, Body))) 11833 FD->setInvalidDecl(); 11834 11835 if (FD && FD->hasAttr<NakedAttr>()) { 11836 for (const Stmt *S : Body->children()) { 11837 // Allow local register variables without initializer as they don't 11838 // require prologue. 11839 bool RegisterVariables = false; 11840 if (auto *DS = dyn_cast<DeclStmt>(S)) { 11841 for (const auto *Decl : DS->decls()) { 11842 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 11843 RegisterVariables = 11844 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 11845 if (!RegisterVariables) 11846 break; 11847 } 11848 } 11849 } 11850 if (RegisterVariables) 11851 continue; 11852 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11853 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11854 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11855 FD->setInvalidDecl(); 11856 break; 11857 } 11858 } 11859 } 11860 11861 assert(ExprCleanupObjects.size() == 11862 ExprEvalContexts.back().NumCleanupObjects && 11863 "Leftover temporaries in function"); 11864 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 11865 assert(MaybeODRUseExprs.empty() && 11866 "Leftover expressions for odr-use checking"); 11867 } 11868 11869 if (!IsInstantiation) 11870 PopDeclContext(); 11871 11872 PopFunctionScopeInfo(ActivePolicy, dcl); 11873 // If any errors have occurred, clear out any temporaries that may have 11874 // been leftover. This ensures that these temporaries won't be picked up for 11875 // deletion in some later function. 11876 if (getDiagnostics().hasErrorOccurred()) { 11877 DiscardCleanupsInEvaluationContext(); 11878 } 11879 11880 return dcl; 11881 } 11882 11883 /// When we finish delayed parsing of an attribute, we must attach it to the 11884 /// relevant Decl. 11885 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11886 ParsedAttributes &Attrs) { 11887 // Always attach attributes to the underlying decl. 11888 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11889 D = TD->getTemplatedDecl(); 11890 ProcessDeclAttributeList(S, D, Attrs.getList()); 11891 11892 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11893 if (Method->isStatic()) 11894 checkThisInStaticMemberFunctionAttributes(Method); 11895 } 11896 11897 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11898 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11899 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11900 IdentifierInfo &II, Scope *S) { 11901 // Before we produce a declaration for an implicitly defined 11902 // function, see whether there was a locally-scoped declaration of 11903 // this name as a function or variable. If so, use that 11904 // (non-visible) declaration, and complain about it. 11905 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11906 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11907 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11908 return ExternCPrev; 11909 } 11910 11911 // Extension in C99. Legal in C90, but warn about it. 11912 unsigned diag_id; 11913 if (II.getName().startswith("__builtin_")) 11914 diag_id = diag::warn_builtin_unknown; 11915 else if (getLangOpts().C99) 11916 diag_id = diag::ext_implicit_function_decl; 11917 else 11918 diag_id = diag::warn_implicit_function_decl; 11919 Diag(Loc, diag_id) << &II; 11920 11921 // Because typo correction is expensive, only do it if the implicit 11922 // function declaration is going to be treated as an error. 11923 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11924 TypoCorrection Corrected; 11925 if (S && 11926 (Corrected = CorrectTypo( 11927 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11928 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11929 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11930 /*ErrorRecovery*/false); 11931 } 11932 11933 // Set a Declarator for the implicit definition: int foo(); 11934 const char *Dummy; 11935 AttributeFactory attrFactory; 11936 DeclSpec DS(attrFactory); 11937 unsigned DiagID; 11938 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11939 Context.getPrintingPolicy()); 11940 (void)Error; // Silence warning. 11941 assert(!Error && "Error setting up implicit decl!"); 11942 SourceLocation NoLoc; 11943 Declarator D(DS, Declarator::BlockContext); 11944 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11945 /*IsAmbiguous=*/false, 11946 /*LParenLoc=*/NoLoc, 11947 /*Params=*/nullptr, 11948 /*NumParams=*/0, 11949 /*EllipsisLoc=*/NoLoc, 11950 /*RParenLoc=*/NoLoc, 11951 /*TypeQuals=*/0, 11952 /*RefQualifierIsLvalueRef=*/true, 11953 /*RefQualifierLoc=*/NoLoc, 11954 /*ConstQualifierLoc=*/NoLoc, 11955 /*VolatileQualifierLoc=*/NoLoc, 11956 /*RestrictQualifierLoc=*/NoLoc, 11957 /*MutableLoc=*/NoLoc, 11958 EST_None, 11959 /*ESpecRange=*/SourceRange(), 11960 /*Exceptions=*/nullptr, 11961 /*ExceptionRanges=*/nullptr, 11962 /*NumExceptions=*/0, 11963 /*NoexceptExpr=*/nullptr, 11964 /*ExceptionSpecTokens=*/nullptr, 11965 Loc, Loc, D), 11966 DS.getAttributes(), 11967 SourceLocation()); 11968 D.SetIdentifier(&II, Loc); 11969 11970 // Insert this function into translation-unit scope. 11971 11972 DeclContext *PrevDC = CurContext; 11973 CurContext = Context.getTranslationUnitDecl(); 11974 11975 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11976 FD->setImplicit(); 11977 11978 CurContext = PrevDC; 11979 11980 AddKnownFunctionAttributes(FD); 11981 11982 return FD; 11983 } 11984 11985 /// \brief Adds any function attributes that we know a priori based on 11986 /// the declaration of this function. 11987 /// 11988 /// These attributes can apply both to implicitly-declared builtins 11989 /// (like __builtin___printf_chk) or to library-declared functions 11990 /// like NSLog or printf. 11991 /// 11992 /// We need to check for duplicate attributes both here and where user-written 11993 /// attributes are applied to declarations. 11994 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11995 if (FD->isInvalidDecl()) 11996 return; 11997 11998 // If this is a built-in function, map its builtin attributes to 11999 // actual attributes. 12000 if (unsigned BuiltinID = FD->getBuiltinID()) { 12001 // Handle printf-formatting attributes. 12002 unsigned FormatIdx; 12003 bool HasVAListArg; 12004 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12005 if (!FD->hasAttr<FormatAttr>()) { 12006 const char *fmt = "printf"; 12007 unsigned int NumParams = FD->getNumParams(); 12008 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12009 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12010 fmt = "NSString"; 12011 FD->addAttr(FormatAttr::CreateImplicit(Context, 12012 &Context.Idents.get(fmt), 12013 FormatIdx+1, 12014 HasVAListArg ? 0 : FormatIdx+2, 12015 FD->getLocation())); 12016 } 12017 } 12018 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12019 HasVAListArg)) { 12020 if (!FD->hasAttr<FormatAttr>()) 12021 FD->addAttr(FormatAttr::CreateImplicit(Context, 12022 &Context.Idents.get("scanf"), 12023 FormatIdx+1, 12024 HasVAListArg ? 0 : FormatIdx+2, 12025 FD->getLocation())); 12026 } 12027 12028 // Mark const if we don't care about errno and that is the only 12029 // thing preventing the function from being const. This allows 12030 // IRgen to use LLVM intrinsics for such functions. 12031 if (!getLangOpts().MathErrno && 12032 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12033 if (!FD->hasAttr<ConstAttr>()) 12034 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12035 } 12036 12037 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12038 !FD->hasAttr<ReturnsTwiceAttr>()) 12039 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12040 FD->getLocation())); 12041 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12042 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12043 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12044 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12045 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12046 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12047 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12048 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12049 // Add the appropriate attribute, depending on the CUDA compilation mode 12050 // and which target the builtin belongs to. For example, during host 12051 // compilation, aux builtins are __device__, while the rest are __host__. 12052 if (getLangOpts().CUDAIsDevice != 12053 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12054 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12055 else 12056 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12057 } 12058 } 12059 12060 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12061 // throw, add an implicit nothrow attribute to any extern "C" function we come 12062 // across. 12063 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12064 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12065 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12066 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12067 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12068 } 12069 12070 IdentifierInfo *Name = FD->getIdentifier(); 12071 if (!Name) 12072 return; 12073 if ((!getLangOpts().CPlusPlus && 12074 FD->getDeclContext()->isTranslationUnit()) || 12075 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12076 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12077 LinkageSpecDecl::lang_c)) { 12078 // Okay: this could be a libc/libm/Objective-C function we know 12079 // about. 12080 } else 12081 return; 12082 12083 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12084 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12085 // target-specific builtins, perhaps? 12086 if (!FD->hasAttr<FormatAttr>()) 12087 FD->addAttr(FormatAttr::CreateImplicit(Context, 12088 &Context.Idents.get("printf"), 2, 12089 Name->isStr("vasprintf") ? 0 : 3, 12090 FD->getLocation())); 12091 } 12092 12093 if (Name->isStr("__CFStringMakeConstantString")) { 12094 // We already have a __builtin___CFStringMakeConstantString, 12095 // but builds that use -fno-constant-cfstrings don't go through that. 12096 if (!FD->hasAttr<FormatArgAttr>()) 12097 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12098 FD->getLocation())); 12099 } 12100 } 12101 12102 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12103 TypeSourceInfo *TInfo) { 12104 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12105 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12106 12107 if (!TInfo) { 12108 assert(D.isInvalidType() && "no declarator info for valid type"); 12109 TInfo = Context.getTrivialTypeSourceInfo(T); 12110 } 12111 12112 // Scope manipulation handled by caller. 12113 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12114 D.getLocStart(), 12115 D.getIdentifierLoc(), 12116 D.getIdentifier(), 12117 TInfo); 12118 12119 // Bail out immediately if we have an invalid declaration. 12120 if (D.isInvalidType()) { 12121 NewTD->setInvalidDecl(); 12122 return NewTD; 12123 } 12124 12125 if (D.getDeclSpec().isModulePrivateSpecified()) { 12126 if (CurContext->isFunctionOrMethod()) 12127 Diag(NewTD->getLocation(), diag::err_module_private_local) 12128 << 2 << NewTD->getDeclName() 12129 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12130 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12131 else 12132 NewTD->setModulePrivate(); 12133 } 12134 12135 // C++ [dcl.typedef]p8: 12136 // If the typedef declaration defines an unnamed class (or 12137 // enum), the first typedef-name declared by the declaration 12138 // to be that class type (or enum type) is used to denote the 12139 // class type (or enum type) for linkage purposes only. 12140 // We need to check whether the type was declared in the declaration. 12141 switch (D.getDeclSpec().getTypeSpecType()) { 12142 case TST_enum: 12143 case TST_struct: 12144 case TST_interface: 12145 case TST_union: 12146 case TST_class: { 12147 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12148 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12149 break; 12150 } 12151 12152 default: 12153 break; 12154 } 12155 12156 return NewTD; 12157 } 12158 12159 /// \brief Check that this is a valid underlying type for an enum declaration. 12160 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12161 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12162 QualType T = TI->getType(); 12163 12164 if (T->isDependentType()) 12165 return false; 12166 12167 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12168 if (BT->isInteger()) 12169 return false; 12170 12171 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12172 return true; 12173 } 12174 12175 /// Check whether this is a valid redeclaration of a previous enumeration. 12176 /// \return true if the redeclaration was invalid. 12177 bool Sema::CheckEnumRedeclaration( 12178 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12179 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12180 bool IsFixed = !EnumUnderlyingTy.isNull(); 12181 12182 if (IsScoped != Prev->isScoped()) { 12183 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12184 << Prev->isScoped(); 12185 Diag(Prev->getLocation(), diag::note_previous_declaration); 12186 return true; 12187 } 12188 12189 if (IsFixed && Prev->isFixed()) { 12190 if (!EnumUnderlyingTy->isDependentType() && 12191 !Prev->getIntegerType()->isDependentType() && 12192 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12193 Prev->getIntegerType())) { 12194 // TODO: Highlight the underlying type of the redeclaration. 12195 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12196 << EnumUnderlyingTy << Prev->getIntegerType(); 12197 Diag(Prev->getLocation(), diag::note_previous_declaration) 12198 << Prev->getIntegerTypeRange(); 12199 return true; 12200 } 12201 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12202 ; 12203 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12204 ; 12205 } else if (IsFixed != Prev->isFixed()) { 12206 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12207 << Prev->isFixed(); 12208 Diag(Prev->getLocation(), diag::note_previous_declaration); 12209 return true; 12210 } 12211 12212 return false; 12213 } 12214 12215 /// \brief Get diagnostic %select index for tag kind for 12216 /// redeclaration diagnostic message. 12217 /// WARNING: Indexes apply to particular diagnostics only! 12218 /// 12219 /// \returns diagnostic %select index. 12220 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12221 switch (Tag) { 12222 case TTK_Struct: return 0; 12223 case TTK_Interface: return 1; 12224 case TTK_Class: return 2; 12225 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12226 } 12227 } 12228 12229 /// \brief Determine if tag kind is a class-key compatible with 12230 /// class for redeclaration (class, struct, or __interface). 12231 /// 12232 /// \returns true iff the tag kind is compatible. 12233 static bool isClassCompatTagKind(TagTypeKind Tag) 12234 { 12235 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12236 } 12237 12238 /// \brief Determine whether a tag with a given kind is acceptable 12239 /// as a redeclaration of the given tag declaration. 12240 /// 12241 /// \returns true if the new tag kind is acceptable, false otherwise. 12242 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12243 TagTypeKind NewTag, bool isDefinition, 12244 SourceLocation NewTagLoc, 12245 const IdentifierInfo *Name) { 12246 // C++ [dcl.type.elab]p3: 12247 // The class-key or enum keyword present in the 12248 // elaborated-type-specifier shall agree in kind with the 12249 // declaration to which the name in the elaborated-type-specifier 12250 // refers. This rule also applies to the form of 12251 // elaborated-type-specifier that declares a class-name or 12252 // friend class since it can be construed as referring to the 12253 // definition of the class. Thus, in any 12254 // elaborated-type-specifier, the enum keyword shall be used to 12255 // refer to an enumeration (7.2), the union class-key shall be 12256 // used to refer to a union (clause 9), and either the class or 12257 // struct class-key shall be used to refer to a class (clause 9) 12258 // declared using the class or struct class-key. 12259 TagTypeKind OldTag = Previous->getTagKind(); 12260 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12261 if (OldTag == NewTag) 12262 return true; 12263 12264 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12265 // Warn about the struct/class tag mismatch. 12266 bool isTemplate = false; 12267 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12268 isTemplate = Record->getDescribedClassTemplate(); 12269 12270 if (!ActiveTemplateInstantiations.empty()) { 12271 // In a template instantiation, do not offer fix-its for tag mismatches 12272 // since they usually mess up the template instead of fixing the problem. 12273 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12274 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12275 << getRedeclDiagFromTagKind(OldTag); 12276 return true; 12277 } 12278 12279 if (isDefinition) { 12280 // On definitions, check previous tags and issue a fix-it for each 12281 // one that doesn't match the current tag. 12282 if (Previous->getDefinition()) { 12283 // Don't suggest fix-its for redefinitions. 12284 return true; 12285 } 12286 12287 bool previousMismatch = false; 12288 for (auto I : Previous->redecls()) { 12289 if (I->getTagKind() != NewTag) { 12290 if (!previousMismatch) { 12291 previousMismatch = true; 12292 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12293 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12294 << getRedeclDiagFromTagKind(I->getTagKind()); 12295 } 12296 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12297 << getRedeclDiagFromTagKind(NewTag) 12298 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12299 TypeWithKeyword::getTagTypeKindName(NewTag)); 12300 } 12301 } 12302 return true; 12303 } 12304 12305 // Check for a previous definition. If current tag and definition 12306 // are same type, do nothing. If no definition, but disagree with 12307 // with previous tag type, give a warning, but no fix-it. 12308 const TagDecl *Redecl = Previous->getDefinition() ? 12309 Previous->getDefinition() : Previous; 12310 if (Redecl->getTagKind() == NewTag) { 12311 return true; 12312 } 12313 12314 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12315 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12316 << getRedeclDiagFromTagKind(OldTag); 12317 Diag(Redecl->getLocation(), diag::note_previous_use); 12318 12319 // If there is a previous definition, suggest a fix-it. 12320 if (Previous->getDefinition()) { 12321 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12322 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12323 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12324 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12325 } 12326 12327 return true; 12328 } 12329 return false; 12330 } 12331 12332 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12333 /// from an outer enclosing namespace or file scope inside a friend declaration. 12334 /// This should provide the commented out code in the following snippet: 12335 /// namespace N { 12336 /// struct X; 12337 /// namespace M { 12338 /// struct Y { friend struct /*N::*/ X; }; 12339 /// } 12340 /// } 12341 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12342 SourceLocation NameLoc) { 12343 // While the decl is in a namespace, do repeated lookup of that name and see 12344 // if we get the same namespace back. If we do not, continue until 12345 // translation unit scope, at which point we have a fully qualified NNS. 12346 SmallVector<IdentifierInfo *, 4> Namespaces; 12347 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12348 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12349 // This tag should be declared in a namespace, which can only be enclosed by 12350 // other namespaces. Bail if there's an anonymous namespace in the chain. 12351 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12352 if (!Namespace || Namespace->isAnonymousNamespace()) 12353 return FixItHint(); 12354 IdentifierInfo *II = Namespace->getIdentifier(); 12355 Namespaces.push_back(II); 12356 NamedDecl *Lookup = SemaRef.LookupSingleName( 12357 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12358 if (Lookup == Namespace) 12359 break; 12360 } 12361 12362 // Once we have all the namespaces, reverse them to go outermost first, and 12363 // build an NNS. 12364 SmallString<64> Insertion; 12365 llvm::raw_svector_ostream OS(Insertion); 12366 if (DC->isTranslationUnit()) 12367 OS << "::"; 12368 std::reverse(Namespaces.begin(), Namespaces.end()); 12369 for (auto *II : Namespaces) 12370 OS << II->getName() << "::"; 12371 return FixItHint::CreateInsertion(NameLoc, Insertion); 12372 } 12373 12374 /// \brief Determine whether a tag originally declared in context \p OldDC can 12375 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12376 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12377 /// using-declaration). 12378 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12379 DeclContext *NewDC) { 12380 OldDC = OldDC->getRedeclContext(); 12381 NewDC = NewDC->getRedeclContext(); 12382 12383 if (OldDC->Equals(NewDC)) 12384 return true; 12385 12386 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12387 // encloses the other). 12388 if (S.getLangOpts().MSVCCompat && 12389 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12390 return true; 12391 12392 return false; 12393 } 12394 12395 /// Find the DeclContext in which a tag is implicitly declared if we see an 12396 /// elaborated type specifier in the specified context, and lookup finds 12397 /// nothing. 12398 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12399 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12400 DC = DC->getParent(); 12401 return DC; 12402 } 12403 12404 /// Find the Scope in which a tag is implicitly declared if we see an 12405 /// elaborated type specifier in the specified context, and lookup finds 12406 /// nothing. 12407 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12408 while (S->isClassScope() || 12409 (LangOpts.CPlusPlus && 12410 S->isFunctionPrototypeScope()) || 12411 ((S->getFlags() & Scope::DeclScope) == 0) || 12412 (S->getEntity() && S->getEntity()->isTransparentContext())) 12413 S = S->getParent(); 12414 return S; 12415 } 12416 12417 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12418 /// former case, Name will be non-null. In the later case, Name will be null. 12419 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12420 /// reference/declaration/definition of a tag. 12421 /// 12422 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12423 /// trailing-type-specifier) other than one in an alias-declaration. 12424 /// 12425 /// \param SkipBody If non-null, will be set to indicate if the caller should 12426 /// skip the definition of this tag and treat it as if it were a declaration. 12427 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12428 SourceLocation KWLoc, CXXScopeSpec &SS, 12429 IdentifierInfo *Name, SourceLocation NameLoc, 12430 AttributeList *Attr, AccessSpecifier AS, 12431 SourceLocation ModulePrivateLoc, 12432 MultiTemplateParamsArg TemplateParameterLists, 12433 bool &OwnedDecl, bool &IsDependent, 12434 SourceLocation ScopedEnumKWLoc, 12435 bool ScopedEnumUsesClassTag, 12436 TypeResult UnderlyingType, 12437 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12438 // If this is not a definition, it must have a name. 12439 IdentifierInfo *OrigName = Name; 12440 assert((Name != nullptr || TUK == TUK_Definition) && 12441 "Nameless record must be a definition!"); 12442 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12443 12444 OwnedDecl = false; 12445 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12446 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12447 12448 // FIXME: Check explicit specializations more carefully. 12449 bool isExplicitSpecialization = false; 12450 bool Invalid = false; 12451 12452 // We only need to do this matching if we have template parameters 12453 // or a scope specifier, which also conveniently avoids this work 12454 // for non-C++ cases. 12455 if (TemplateParameterLists.size() > 0 || 12456 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12457 if (TemplateParameterList *TemplateParams = 12458 MatchTemplateParametersToScopeSpecifier( 12459 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12460 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12461 if (Kind == TTK_Enum) { 12462 Diag(KWLoc, diag::err_enum_template); 12463 return nullptr; 12464 } 12465 12466 if (TemplateParams->size() > 0) { 12467 // This is a declaration or definition of a class template (which may 12468 // be a member of another template). 12469 12470 if (Invalid) 12471 return nullptr; 12472 12473 OwnedDecl = false; 12474 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12475 SS, Name, NameLoc, Attr, 12476 TemplateParams, AS, 12477 ModulePrivateLoc, 12478 /*FriendLoc*/SourceLocation(), 12479 TemplateParameterLists.size()-1, 12480 TemplateParameterLists.data(), 12481 SkipBody); 12482 return Result.get(); 12483 } else { 12484 // The "template<>" header is extraneous. 12485 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12486 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12487 isExplicitSpecialization = true; 12488 } 12489 } 12490 } 12491 12492 // Figure out the underlying type if this a enum declaration. We need to do 12493 // this early, because it's needed to detect if this is an incompatible 12494 // redeclaration. 12495 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12496 bool EnumUnderlyingIsImplicit = false; 12497 12498 if (Kind == TTK_Enum) { 12499 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12500 // No underlying type explicitly specified, or we failed to parse the 12501 // type, default to int. 12502 EnumUnderlying = Context.IntTy.getTypePtr(); 12503 else if (UnderlyingType.get()) { 12504 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12505 // integral type; any cv-qualification is ignored. 12506 TypeSourceInfo *TI = nullptr; 12507 GetTypeFromParser(UnderlyingType.get(), &TI); 12508 EnumUnderlying = TI; 12509 12510 if (CheckEnumUnderlyingType(TI)) 12511 // Recover by falling back to int. 12512 EnumUnderlying = Context.IntTy.getTypePtr(); 12513 12514 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12515 UPPC_FixedUnderlyingType)) 12516 EnumUnderlying = Context.IntTy.getTypePtr(); 12517 12518 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12519 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12520 // Microsoft enums are always of int type. 12521 EnumUnderlying = Context.IntTy.getTypePtr(); 12522 EnumUnderlyingIsImplicit = true; 12523 } 12524 } 12525 } 12526 12527 DeclContext *SearchDC = CurContext; 12528 DeclContext *DC = CurContext; 12529 bool isStdBadAlloc = false; 12530 12531 RedeclarationKind Redecl = ForRedeclaration; 12532 if (TUK == TUK_Friend || TUK == TUK_Reference) 12533 Redecl = NotForRedeclaration; 12534 12535 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12536 if (Name && SS.isNotEmpty()) { 12537 // We have a nested-name tag ('struct foo::bar'). 12538 12539 // Check for invalid 'foo::'. 12540 if (SS.isInvalid()) { 12541 Name = nullptr; 12542 goto CreateNewDecl; 12543 } 12544 12545 // If this is a friend or a reference to a class in a dependent 12546 // context, don't try to make a decl for it. 12547 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12548 DC = computeDeclContext(SS, false); 12549 if (!DC) { 12550 IsDependent = true; 12551 return nullptr; 12552 } 12553 } else { 12554 DC = computeDeclContext(SS, true); 12555 if (!DC) { 12556 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12557 << SS.getRange(); 12558 return nullptr; 12559 } 12560 } 12561 12562 if (RequireCompleteDeclContext(SS, DC)) 12563 return nullptr; 12564 12565 SearchDC = DC; 12566 // Look-up name inside 'foo::'. 12567 LookupQualifiedName(Previous, DC); 12568 12569 if (Previous.isAmbiguous()) 12570 return nullptr; 12571 12572 if (Previous.empty()) { 12573 // Name lookup did not find anything. However, if the 12574 // nested-name-specifier refers to the current instantiation, 12575 // and that current instantiation has any dependent base 12576 // classes, we might find something at instantiation time: treat 12577 // this as a dependent elaborated-type-specifier. 12578 // But this only makes any sense for reference-like lookups. 12579 if (Previous.wasNotFoundInCurrentInstantiation() && 12580 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12581 IsDependent = true; 12582 return nullptr; 12583 } 12584 12585 // A tag 'foo::bar' must already exist. 12586 Diag(NameLoc, diag::err_not_tag_in_scope) 12587 << Kind << Name << DC << SS.getRange(); 12588 Name = nullptr; 12589 Invalid = true; 12590 goto CreateNewDecl; 12591 } 12592 } else if (Name) { 12593 // C++14 [class.mem]p14: 12594 // If T is the name of a class, then each of the following shall have a 12595 // name different from T: 12596 // -- every member of class T that is itself a type 12597 if (TUK != TUK_Reference && TUK != TUK_Friend && 12598 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12599 return nullptr; 12600 12601 // If this is a named struct, check to see if there was a previous forward 12602 // declaration or definition. 12603 // FIXME: We're looking into outer scopes here, even when we 12604 // shouldn't be. Doing so can result in ambiguities that we 12605 // shouldn't be diagnosing. 12606 LookupName(Previous, S); 12607 12608 // When declaring or defining a tag, ignore ambiguities introduced 12609 // by types using'ed into this scope. 12610 if (Previous.isAmbiguous() && 12611 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12612 LookupResult::Filter F = Previous.makeFilter(); 12613 while (F.hasNext()) { 12614 NamedDecl *ND = F.next(); 12615 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12616 SearchDC->getRedeclContext())) 12617 F.erase(); 12618 } 12619 F.done(); 12620 } 12621 12622 // C++11 [namespace.memdef]p3: 12623 // If the name in a friend declaration is neither qualified nor 12624 // a template-id and the declaration is a function or an 12625 // elaborated-type-specifier, the lookup to determine whether 12626 // the entity has been previously declared shall not consider 12627 // any scopes outside the innermost enclosing namespace. 12628 // 12629 // MSVC doesn't implement the above rule for types, so a friend tag 12630 // declaration may be a redeclaration of a type declared in an enclosing 12631 // scope. They do implement this rule for friend functions. 12632 // 12633 // Does it matter that this should be by scope instead of by 12634 // semantic context? 12635 if (!Previous.empty() && TUK == TUK_Friend) { 12636 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12637 LookupResult::Filter F = Previous.makeFilter(); 12638 bool FriendSawTagOutsideEnclosingNamespace = false; 12639 while (F.hasNext()) { 12640 NamedDecl *ND = F.next(); 12641 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12642 if (DC->isFileContext() && 12643 !EnclosingNS->Encloses(ND->getDeclContext())) { 12644 if (getLangOpts().MSVCCompat) 12645 FriendSawTagOutsideEnclosingNamespace = true; 12646 else 12647 F.erase(); 12648 } 12649 } 12650 F.done(); 12651 12652 // Diagnose this MSVC extension in the easy case where lookup would have 12653 // unambiguously found something outside the enclosing namespace. 12654 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12655 NamedDecl *ND = Previous.getFoundDecl(); 12656 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12657 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12658 } 12659 } 12660 12661 // Note: there used to be some attempt at recovery here. 12662 if (Previous.isAmbiguous()) 12663 return nullptr; 12664 12665 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12666 // FIXME: This makes sure that we ignore the contexts associated 12667 // with C structs, unions, and enums when looking for a matching 12668 // tag declaration or definition. See the similar lookup tweak 12669 // in Sema::LookupName; is there a better way to deal with this? 12670 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12671 SearchDC = SearchDC->getParent(); 12672 } 12673 } 12674 12675 if (Previous.isSingleResult() && 12676 Previous.getFoundDecl()->isTemplateParameter()) { 12677 // Maybe we will complain about the shadowed template parameter. 12678 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12679 // Just pretend that we didn't see the previous declaration. 12680 Previous.clear(); 12681 } 12682 12683 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12684 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 12685 // This is a declaration of or a reference to "std::bad_alloc". 12686 isStdBadAlloc = true; 12687 12688 if (Previous.empty() && StdBadAlloc) { 12689 // std::bad_alloc has been implicitly declared (but made invisible to 12690 // name lookup). Fill in this implicit declaration as the previous 12691 // declaration, so that the declarations get chained appropriately. 12692 Previous.addDecl(getStdBadAlloc()); 12693 } 12694 } 12695 12696 // If we didn't find a previous declaration, and this is a reference 12697 // (or friend reference), move to the correct scope. In C++, we 12698 // also need to do a redeclaration lookup there, just in case 12699 // there's a shadow friend decl. 12700 if (Name && Previous.empty() && 12701 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12702 if (Invalid) goto CreateNewDecl; 12703 assert(SS.isEmpty()); 12704 12705 if (TUK == TUK_Reference) { 12706 // C++ [basic.scope.pdecl]p5: 12707 // -- for an elaborated-type-specifier of the form 12708 // 12709 // class-key identifier 12710 // 12711 // if the elaborated-type-specifier is used in the 12712 // decl-specifier-seq or parameter-declaration-clause of a 12713 // function defined in namespace scope, the identifier is 12714 // declared as a class-name in the namespace that contains 12715 // the declaration; otherwise, except as a friend 12716 // declaration, the identifier is declared in the smallest 12717 // non-class, non-function-prototype scope that contains the 12718 // declaration. 12719 // 12720 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12721 // C structs and unions. 12722 // 12723 // It is an error in C++ to declare (rather than define) an enum 12724 // type, including via an elaborated type specifier. We'll 12725 // diagnose that later; for now, declare the enum in the same 12726 // scope as we would have picked for any other tag type. 12727 // 12728 // GNU C also supports this behavior as part of its incomplete 12729 // enum types extension, while GNU C++ does not. 12730 // 12731 // Find the context where we'll be declaring the tag. 12732 // FIXME: We would like to maintain the current DeclContext as the 12733 // lexical context, 12734 SearchDC = getTagInjectionContext(SearchDC); 12735 12736 // Find the scope where we'll be declaring the tag. 12737 S = getTagInjectionScope(S, getLangOpts()); 12738 } else { 12739 assert(TUK == TUK_Friend); 12740 // C++ [namespace.memdef]p3: 12741 // If a friend declaration in a non-local class first declares a 12742 // class or function, the friend class or function is a member of 12743 // the innermost enclosing namespace. 12744 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12745 } 12746 12747 // In C++, we need to do a redeclaration lookup to properly 12748 // diagnose some problems. 12749 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12750 // hidden declaration so that we don't get ambiguity errors when using a 12751 // type declared by an elaborated-type-specifier. In C that is not correct 12752 // and we should instead merge compatible types found by lookup. 12753 if (getLangOpts().CPlusPlus) { 12754 Previous.setRedeclarationKind(ForRedeclaration); 12755 LookupQualifiedName(Previous, SearchDC); 12756 } else { 12757 Previous.setRedeclarationKind(ForRedeclaration); 12758 LookupName(Previous, S); 12759 } 12760 } 12761 12762 // If we have a known previous declaration to use, then use it. 12763 if (Previous.empty() && SkipBody && SkipBody->Previous) 12764 Previous.addDecl(SkipBody->Previous); 12765 12766 if (!Previous.empty()) { 12767 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12768 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12769 12770 // It's okay to have a tag decl in the same scope as a typedef 12771 // which hides a tag decl in the same scope. Finding this 12772 // insanity with a redeclaration lookup can only actually happen 12773 // in C++. 12774 // 12775 // This is also okay for elaborated-type-specifiers, which is 12776 // technically forbidden by the current standard but which is 12777 // okay according to the likely resolution of an open issue; 12778 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12779 if (getLangOpts().CPlusPlus) { 12780 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12781 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12782 TagDecl *Tag = TT->getDecl(); 12783 if (Tag->getDeclName() == Name && 12784 Tag->getDeclContext()->getRedeclContext() 12785 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12786 PrevDecl = Tag; 12787 Previous.clear(); 12788 Previous.addDecl(Tag); 12789 Previous.resolveKind(); 12790 } 12791 } 12792 } 12793 } 12794 12795 // If this is a redeclaration of a using shadow declaration, it must 12796 // declare a tag in the same context. In MSVC mode, we allow a 12797 // redefinition if either context is within the other. 12798 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12799 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12800 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12801 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12802 !(OldTag && isAcceptableTagRedeclContext( 12803 *this, OldTag->getDeclContext(), SearchDC))) { 12804 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12805 Diag(Shadow->getTargetDecl()->getLocation(), 12806 diag::note_using_decl_target); 12807 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12808 << 0; 12809 // Recover by ignoring the old declaration. 12810 Previous.clear(); 12811 goto CreateNewDecl; 12812 } 12813 } 12814 12815 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12816 // If this is a use of a previous tag, or if the tag is already declared 12817 // in the same scope (so that the definition/declaration completes or 12818 // rementions the tag), reuse the decl. 12819 if (TUK == TUK_Reference || TUK == TUK_Friend || 12820 isDeclInScope(DirectPrevDecl, SearchDC, S, 12821 SS.isNotEmpty() || isExplicitSpecialization)) { 12822 // Make sure that this wasn't declared as an enum and now used as a 12823 // struct or something similar. 12824 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12825 TUK == TUK_Definition, KWLoc, 12826 Name)) { 12827 bool SafeToContinue 12828 = (PrevTagDecl->getTagKind() != TTK_Enum && 12829 Kind != TTK_Enum); 12830 if (SafeToContinue) 12831 Diag(KWLoc, diag::err_use_with_wrong_tag) 12832 << Name 12833 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12834 PrevTagDecl->getKindName()); 12835 else 12836 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12837 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12838 12839 if (SafeToContinue) 12840 Kind = PrevTagDecl->getTagKind(); 12841 else { 12842 // Recover by making this an anonymous redefinition. 12843 Name = nullptr; 12844 Previous.clear(); 12845 Invalid = true; 12846 } 12847 } 12848 12849 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12850 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12851 12852 // If this is an elaborated-type-specifier for a scoped enumeration, 12853 // the 'class' keyword is not necessary and not permitted. 12854 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12855 if (ScopedEnum) 12856 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12857 << PrevEnum->isScoped() 12858 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12859 return PrevTagDecl; 12860 } 12861 12862 QualType EnumUnderlyingTy; 12863 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12864 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12865 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12866 EnumUnderlyingTy = QualType(T, 0); 12867 12868 // All conflicts with previous declarations are recovered by 12869 // returning the previous declaration, unless this is a definition, 12870 // in which case we want the caller to bail out. 12871 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12872 ScopedEnum, EnumUnderlyingTy, 12873 EnumUnderlyingIsImplicit, PrevEnum)) 12874 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12875 } 12876 12877 // C++11 [class.mem]p1: 12878 // A member shall not be declared twice in the member-specification, 12879 // except that a nested class or member class template can be declared 12880 // and then later defined. 12881 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12882 S->isDeclScope(PrevDecl)) { 12883 Diag(NameLoc, diag::ext_member_redeclared); 12884 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12885 } 12886 12887 if (!Invalid) { 12888 // If this is a use, just return the declaration we found, unless 12889 // we have attributes. 12890 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12891 if (Attr) { 12892 // FIXME: Diagnose these attributes. For now, we create a new 12893 // declaration to hold them. 12894 } else if (TUK == TUK_Reference && 12895 (PrevTagDecl->getFriendObjectKind() == 12896 Decl::FOK_Undeclared || 12897 PP.getModuleContainingLocation( 12898 PrevDecl->getLocation()) != 12899 PP.getModuleContainingLocation(KWLoc)) && 12900 SS.isEmpty()) { 12901 // This declaration is a reference to an existing entity, but 12902 // has different visibility from that entity: it either makes 12903 // a friend visible or it makes a type visible in a new module. 12904 // In either case, create a new declaration. We only do this if 12905 // the declaration would have meant the same thing if no prior 12906 // declaration were found, that is, if it was found in the same 12907 // scope where we would have injected a declaration. 12908 if (!getTagInjectionContext(CurContext)->getRedeclContext() 12909 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 12910 return PrevTagDecl; 12911 // This is in the injected scope, create a new declaration in 12912 // that scope. 12913 S = getTagInjectionScope(S, getLangOpts()); 12914 } else { 12915 return PrevTagDecl; 12916 } 12917 } 12918 12919 // Diagnose attempts to redefine a tag. 12920 if (TUK == TUK_Definition) { 12921 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12922 // If we're defining a specialization and the previous definition 12923 // is from an implicit instantiation, don't emit an error 12924 // here; we'll catch this in the general case below. 12925 bool IsExplicitSpecializationAfterInstantiation = false; 12926 if (isExplicitSpecialization) { 12927 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12928 IsExplicitSpecializationAfterInstantiation = 12929 RD->getTemplateSpecializationKind() != 12930 TSK_ExplicitSpecialization; 12931 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12932 IsExplicitSpecializationAfterInstantiation = 12933 ED->getTemplateSpecializationKind() != 12934 TSK_ExplicitSpecialization; 12935 } 12936 12937 NamedDecl *Hidden = nullptr; 12938 if (SkipBody && getLangOpts().CPlusPlus && 12939 !hasVisibleDefinition(Def, &Hidden)) { 12940 // There is a definition of this tag, but it is not visible. We 12941 // explicitly make use of C++'s one definition rule here, and 12942 // assume that this definition is identical to the hidden one 12943 // we already have. Make the existing definition visible and 12944 // use it in place of this one. 12945 SkipBody->ShouldSkip = true; 12946 makeMergedDefinitionVisible(Hidden, KWLoc); 12947 return Def; 12948 } else if (!IsExplicitSpecializationAfterInstantiation) { 12949 // A redeclaration in function prototype scope in C isn't 12950 // visible elsewhere, so merely issue a warning. 12951 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 12952 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 12953 else 12954 Diag(NameLoc, diag::err_redefinition) << Name; 12955 Diag(Def->getLocation(), diag::note_previous_definition); 12956 // If this is a redefinition, recover by making this 12957 // struct be anonymous, which will make any later 12958 // references get the previous definition. 12959 Name = nullptr; 12960 Previous.clear(); 12961 Invalid = true; 12962 } 12963 } else { 12964 // If the type is currently being defined, complain 12965 // about a nested redefinition. 12966 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 12967 if (TD->isBeingDefined()) { 12968 Diag(NameLoc, diag::err_nested_redefinition) << Name; 12969 Diag(PrevTagDecl->getLocation(), 12970 diag::note_previous_definition); 12971 Name = nullptr; 12972 Previous.clear(); 12973 Invalid = true; 12974 } 12975 } 12976 12977 // Okay, this is definition of a previously declared or referenced 12978 // tag. We're going to create a new Decl for it. 12979 } 12980 12981 // Okay, we're going to make a redeclaration. If this is some kind 12982 // of reference, make sure we build the redeclaration in the same DC 12983 // as the original, and ignore the current access specifier. 12984 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12985 SearchDC = PrevTagDecl->getDeclContext(); 12986 AS = AS_none; 12987 } 12988 } 12989 // If we get here we have (another) forward declaration or we 12990 // have a definition. Just create a new decl. 12991 12992 } else { 12993 // If we get here, this is a definition of a new tag type in a nested 12994 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 12995 // new decl/type. We set PrevDecl to NULL so that the entities 12996 // have distinct types. 12997 Previous.clear(); 12998 } 12999 // If we get here, we're going to create a new Decl. If PrevDecl 13000 // is non-NULL, it's a definition of the tag declared by 13001 // PrevDecl. If it's NULL, we have a new definition. 13002 13003 // Otherwise, PrevDecl is not a tag, but was found with tag 13004 // lookup. This is only actually possible in C++, where a few 13005 // things like templates still live in the tag namespace. 13006 } else { 13007 // Use a better diagnostic if an elaborated-type-specifier 13008 // found the wrong kind of type on the first 13009 // (non-redeclaration) lookup. 13010 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13011 !Previous.isForRedeclaration()) { 13012 unsigned Kind = 0; 13013 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 13014 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 13015 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 13016 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 13017 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13018 Invalid = true; 13019 13020 // Otherwise, only diagnose if the declaration is in scope. 13021 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13022 SS.isNotEmpty() || isExplicitSpecialization)) { 13023 // do nothing 13024 13025 // Diagnose implicit declarations introduced by elaborated types. 13026 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13027 unsigned Kind = 0; 13028 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 13029 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 13030 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 13031 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 13032 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13033 Invalid = true; 13034 13035 // Otherwise it's a declaration. Call out a particularly common 13036 // case here. 13037 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13038 unsigned Kind = 0; 13039 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13040 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13041 << Name << Kind << TND->getUnderlyingType(); 13042 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13043 Invalid = true; 13044 13045 // Otherwise, diagnose. 13046 } else { 13047 // The tag name clashes with something else in the target scope, 13048 // issue an error and recover by making this tag be anonymous. 13049 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13050 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13051 Name = nullptr; 13052 Invalid = true; 13053 } 13054 13055 // The existing declaration isn't relevant to us; we're in a 13056 // new scope, so clear out the previous declaration. 13057 Previous.clear(); 13058 } 13059 } 13060 13061 CreateNewDecl: 13062 13063 TagDecl *PrevDecl = nullptr; 13064 if (Previous.isSingleResult()) 13065 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13066 13067 // If there is an identifier, use the location of the identifier as the 13068 // location of the decl, otherwise use the location of the struct/union 13069 // keyword. 13070 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13071 13072 // Otherwise, create a new declaration. If there is a previous 13073 // declaration of the same entity, the two will be linked via 13074 // PrevDecl. 13075 TagDecl *New; 13076 13077 bool IsForwardReference = false; 13078 if (Kind == TTK_Enum) { 13079 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13080 // enum X { A, B, C } D; D should chain to X. 13081 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13082 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13083 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13084 // If this is an undefined enum, warn. 13085 if (TUK != TUK_Definition && !Invalid) { 13086 TagDecl *Def; 13087 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13088 cast<EnumDecl>(New)->isFixed()) { 13089 // C++0x: 7.2p2: opaque-enum-declaration. 13090 // Conflicts are diagnosed above. Do nothing. 13091 } 13092 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13093 Diag(Loc, diag::ext_forward_ref_enum_def) 13094 << New; 13095 Diag(Def->getLocation(), diag::note_previous_definition); 13096 } else { 13097 unsigned DiagID = diag::ext_forward_ref_enum; 13098 if (getLangOpts().MSVCCompat) 13099 DiagID = diag::ext_ms_forward_ref_enum; 13100 else if (getLangOpts().CPlusPlus) 13101 DiagID = diag::err_forward_ref_enum; 13102 Diag(Loc, DiagID); 13103 13104 // If this is a forward-declared reference to an enumeration, make a 13105 // note of it; we won't actually be introducing the declaration into 13106 // the declaration context. 13107 if (TUK == TUK_Reference) 13108 IsForwardReference = true; 13109 } 13110 } 13111 13112 if (EnumUnderlying) { 13113 EnumDecl *ED = cast<EnumDecl>(New); 13114 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13115 ED->setIntegerTypeSourceInfo(TI); 13116 else 13117 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13118 ED->setPromotionType(ED->getIntegerType()); 13119 } 13120 } else { 13121 // struct/union/class 13122 13123 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13124 // struct X { int A; } D; D should chain to X. 13125 if (getLangOpts().CPlusPlus) { 13126 // FIXME: Look for a way to use RecordDecl for simple structs. 13127 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13128 cast_or_null<CXXRecordDecl>(PrevDecl)); 13129 13130 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13131 StdBadAlloc = cast<CXXRecordDecl>(New); 13132 } else 13133 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13134 cast_or_null<RecordDecl>(PrevDecl)); 13135 } 13136 13137 // C++11 [dcl.type]p3: 13138 // A type-specifier-seq shall not define a class or enumeration [...]. 13139 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13140 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13141 << Context.getTagDeclType(New); 13142 Invalid = true; 13143 } 13144 13145 // Maybe add qualifier info. 13146 if (SS.isNotEmpty()) { 13147 if (SS.isSet()) { 13148 // If this is either a declaration or a definition, check the 13149 // nested-name-specifier against the current context. We don't do this 13150 // for explicit specializations, because they have similar checking 13151 // (with more specific diagnostics) in the call to 13152 // CheckMemberSpecialization, below. 13153 if (!isExplicitSpecialization && 13154 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13155 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13156 Invalid = true; 13157 13158 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13159 if (TemplateParameterLists.size() > 0) { 13160 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13161 } 13162 } 13163 else 13164 Invalid = true; 13165 } 13166 13167 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13168 // Add alignment attributes if necessary; these attributes are checked when 13169 // the ASTContext lays out the structure. 13170 // 13171 // It is important for implementing the correct semantics that this 13172 // happen here (in act on tag decl). The #pragma pack stack is 13173 // maintained as a result of parser callbacks which can occur at 13174 // many points during the parsing of a struct declaration (because 13175 // the #pragma tokens are effectively skipped over during the 13176 // parsing of the struct). 13177 if (TUK == TUK_Definition) { 13178 AddAlignmentAttributesForRecord(RD); 13179 AddMsStructLayoutForRecord(RD); 13180 } 13181 } 13182 13183 if (ModulePrivateLoc.isValid()) { 13184 if (isExplicitSpecialization) 13185 Diag(New->getLocation(), diag::err_module_private_specialization) 13186 << 2 13187 << FixItHint::CreateRemoval(ModulePrivateLoc); 13188 // __module_private__ does not apply to local classes. However, we only 13189 // diagnose this as an error when the declaration specifiers are 13190 // freestanding. Here, we just ignore the __module_private__. 13191 else if (!SearchDC->isFunctionOrMethod()) 13192 New->setModulePrivate(); 13193 } 13194 13195 // If this is a specialization of a member class (of a class template), 13196 // check the specialization. 13197 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13198 Invalid = true; 13199 13200 // If we're declaring or defining a tag in function prototype scope in C, 13201 // note that this type can only be used within the function and add it to 13202 // the list of decls to inject into the function definition scope. 13203 if ((Name || Kind == TTK_Enum) && 13204 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13205 if (getLangOpts().CPlusPlus) { 13206 // C++ [dcl.fct]p6: 13207 // Types shall not be defined in return or parameter types. 13208 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13209 Diag(Loc, diag::err_type_defined_in_param_type) 13210 << Name; 13211 Invalid = true; 13212 } 13213 } else if (!PrevDecl) { 13214 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13215 } 13216 DeclsInPrototypeScope.push_back(New); 13217 } 13218 13219 if (Invalid) 13220 New->setInvalidDecl(); 13221 13222 if (Attr) 13223 ProcessDeclAttributeList(S, New, Attr); 13224 13225 // Set the lexical context. If the tag has a C++ scope specifier, the 13226 // lexical context will be different from the semantic context. 13227 New->setLexicalDeclContext(CurContext); 13228 13229 // Mark this as a friend decl if applicable. 13230 // In Microsoft mode, a friend declaration also acts as a forward 13231 // declaration so we always pass true to setObjectOfFriendDecl to make 13232 // the tag name visible. 13233 if (TUK == TUK_Friend) 13234 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13235 13236 // Set the access specifier. 13237 if (!Invalid && SearchDC->isRecord()) 13238 SetMemberAccessSpecifier(New, PrevDecl, AS); 13239 13240 if (TUK == TUK_Definition) 13241 New->startDefinition(); 13242 13243 // If this has an identifier, add it to the scope stack. 13244 if (TUK == TUK_Friend) { 13245 // We might be replacing an existing declaration in the lookup tables; 13246 // if so, borrow its access specifier. 13247 if (PrevDecl) 13248 New->setAccess(PrevDecl->getAccess()); 13249 13250 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13251 DC->makeDeclVisibleInContext(New); 13252 if (Name) // can be null along some error paths 13253 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13254 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13255 } else if (Name) { 13256 S = getNonFieldDeclScope(S); 13257 PushOnScopeChains(New, S, !IsForwardReference); 13258 if (IsForwardReference) 13259 SearchDC->makeDeclVisibleInContext(New); 13260 } else { 13261 CurContext->addDecl(New); 13262 } 13263 13264 // If this is the C FILE type, notify the AST context. 13265 if (IdentifierInfo *II = New->getIdentifier()) 13266 if (!New->isInvalidDecl() && 13267 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13268 II->isStr("FILE")) 13269 Context.setFILEDecl(New); 13270 13271 if (PrevDecl) 13272 mergeDeclAttributes(New, PrevDecl); 13273 13274 // If there's a #pragma GCC visibility in scope, set the visibility of this 13275 // record. 13276 AddPushedVisibilityAttribute(New); 13277 13278 OwnedDecl = true; 13279 // In C++, don't return an invalid declaration. We can't recover well from 13280 // the cases where we make the type anonymous. 13281 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 13282 } 13283 13284 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13285 AdjustDeclIfTemplate(TagD); 13286 TagDecl *Tag = cast<TagDecl>(TagD); 13287 13288 // Enter the tag context. 13289 PushDeclContext(S, Tag); 13290 13291 ActOnDocumentableDecl(TagD); 13292 13293 // If there's a #pragma GCC visibility in scope, set the visibility of this 13294 // record. 13295 AddPushedVisibilityAttribute(Tag); 13296 } 13297 13298 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13299 assert(isa<ObjCContainerDecl>(IDecl) && 13300 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13301 DeclContext *OCD = cast<DeclContext>(IDecl); 13302 assert(getContainingDC(OCD) == CurContext && 13303 "The next DeclContext should be lexically contained in the current one."); 13304 CurContext = OCD; 13305 return IDecl; 13306 } 13307 13308 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13309 SourceLocation FinalLoc, 13310 bool IsFinalSpelledSealed, 13311 SourceLocation LBraceLoc) { 13312 AdjustDeclIfTemplate(TagD); 13313 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13314 13315 FieldCollector->StartClass(); 13316 13317 if (!Record->getIdentifier()) 13318 return; 13319 13320 if (FinalLoc.isValid()) 13321 Record->addAttr(new (Context) 13322 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13323 13324 // C++ [class]p2: 13325 // [...] The class-name is also inserted into the scope of the 13326 // class itself; this is known as the injected-class-name. For 13327 // purposes of access checking, the injected-class-name is treated 13328 // as if it were a public member name. 13329 CXXRecordDecl *InjectedClassName 13330 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13331 Record->getLocStart(), Record->getLocation(), 13332 Record->getIdentifier(), 13333 /*PrevDecl=*/nullptr, 13334 /*DelayTypeCreation=*/true); 13335 Context.getTypeDeclType(InjectedClassName, Record); 13336 InjectedClassName->setImplicit(); 13337 InjectedClassName->setAccess(AS_public); 13338 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13339 InjectedClassName->setDescribedClassTemplate(Template); 13340 PushOnScopeChains(InjectedClassName, S); 13341 assert(InjectedClassName->isInjectedClassName() && 13342 "Broken injected-class-name"); 13343 } 13344 13345 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13346 SourceRange BraceRange) { 13347 AdjustDeclIfTemplate(TagD); 13348 TagDecl *Tag = cast<TagDecl>(TagD); 13349 Tag->setBraceRange(BraceRange); 13350 13351 // Make sure we "complete" the definition even it is invalid. 13352 if (Tag->isBeingDefined()) { 13353 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13354 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13355 RD->completeDefinition(); 13356 } 13357 13358 if (isa<CXXRecordDecl>(Tag)) 13359 FieldCollector->FinishClass(); 13360 13361 // Exit this scope of this tag's definition. 13362 PopDeclContext(); 13363 13364 if (getCurLexicalContext()->isObjCContainer() && 13365 Tag->getDeclContext()->isFileContext()) 13366 Tag->setTopLevelDeclInObjCContainer(); 13367 13368 // Notify the consumer that we've defined a tag. 13369 if (!Tag->isInvalidDecl()) 13370 Consumer.HandleTagDeclDefinition(Tag); 13371 } 13372 13373 void Sema::ActOnObjCContainerFinishDefinition() { 13374 // Exit this scope of this interface definition. 13375 PopDeclContext(); 13376 } 13377 13378 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13379 assert(DC == CurContext && "Mismatch of container contexts"); 13380 OriginalLexicalContext = DC; 13381 ActOnObjCContainerFinishDefinition(); 13382 } 13383 13384 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13385 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13386 OriginalLexicalContext = nullptr; 13387 } 13388 13389 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13390 AdjustDeclIfTemplate(TagD); 13391 TagDecl *Tag = cast<TagDecl>(TagD); 13392 Tag->setInvalidDecl(); 13393 13394 // Make sure we "complete" the definition even it is invalid. 13395 if (Tag->isBeingDefined()) { 13396 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13397 RD->completeDefinition(); 13398 } 13399 13400 // We're undoing ActOnTagStartDefinition here, not 13401 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13402 // the FieldCollector. 13403 13404 PopDeclContext(); 13405 } 13406 13407 // Note that FieldName may be null for anonymous bitfields. 13408 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13409 IdentifierInfo *FieldName, 13410 QualType FieldTy, bool IsMsStruct, 13411 Expr *BitWidth, bool *ZeroWidth) { 13412 // Default to true; that shouldn't confuse checks for emptiness 13413 if (ZeroWidth) 13414 *ZeroWidth = true; 13415 13416 // C99 6.7.2.1p4 - verify the field type. 13417 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13418 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13419 // Handle incomplete types with specific error. 13420 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13421 return ExprError(); 13422 if (FieldName) 13423 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13424 << FieldName << FieldTy << BitWidth->getSourceRange(); 13425 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13426 << FieldTy << BitWidth->getSourceRange(); 13427 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13428 UPPC_BitFieldWidth)) 13429 return ExprError(); 13430 13431 // If the bit-width is type- or value-dependent, don't try to check 13432 // it now. 13433 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13434 return BitWidth; 13435 13436 llvm::APSInt Value; 13437 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13438 if (ICE.isInvalid()) 13439 return ICE; 13440 BitWidth = ICE.get(); 13441 13442 if (Value != 0 && ZeroWidth) 13443 *ZeroWidth = false; 13444 13445 // Zero-width bitfield is ok for anonymous field. 13446 if (Value == 0 && FieldName) 13447 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13448 13449 if (Value.isSigned() && Value.isNegative()) { 13450 if (FieldName) 13451 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13452 << FieldName << Value.toString(10); 13453 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13454 << Value.toString(10); 13455 } 13456 13457 if (!FieldTy->isDependentType()) { 13458 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13459 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13460 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13461 13462 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13463 // ABI. 13464 bool CStdConstraintViolation = 13465 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13466 bool MSBitfieldViolation = 13467 Value.ugt(TypeStorageSize) && 13468 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13469 if (CStdConstraintViolation || MSBitfieldViolation) { 13470 unsigned DiagWidth = 13471 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13472 if (FieldName) 13473 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13474 << FieldName << (unsigned)Value.getZExtValue() 13475 << !CStdConstraintViolation << DiagWidth; 13476 13477 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13478 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13479 << DiagWidth; 13480 } 13481 13482 // Warn on types where the user might conceivably expect to get all 13483 // specified bits as value bits: that's all integral types other than 13484 // 'bool'. 13485 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13486 if (FieldName) 13487 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13488 << FieldName << (unsigned)Value.getZExtValue() 13489 << (unsigned)TypeWidth; 13490 else 13491 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13492 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13493 } 13494 } 13495 13496 return BitWidth; 13497 } 13498 13499 /// ActOnField - Each field of a C struct/union is passed into this in order 13500 /// to create a FieldDecl object for it. 13501 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13502 Declarator &D, Expr *BitfieldWidth) { 13503 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13504 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13505 /*InitStyle=*/ICIS_NoInit, AS_public); 13506 return Res; 13507 } 13508 13509 /// HandleField - Analyze a field of a C struct or a C++ data member. 13510 /// 13511 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13512 SourceLocation DeclStart, 13513 Declarator &D, Expr *BitWidth, 13514 InClassInitStyle InitStyle, 13515 AccessSpecifier AS) { 13516 if (D.isDecompositionDeclarator()) { 13517 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13518 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13519 << Decomp.getSourceRange(); 13520 return nullptr; 13521 } 13522 13523 IdentifierInfo *II = D.getIdentifier(); 13524 SourceLocation Loc = DeclStart; 13525 if (II) Loc = D.getIdentifierLoc(); 13526 13527 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13528 QualType T = TInfo->getType(); 13529 if (getLangOpts().CPlusPlus) { 13530 CheckExtraCXXDefaultArguments(D); 13531 13532 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13533 UPPC_DataMemberType)) { 13534 D.setInvalidType(); 13535 T = Context.IntTy; 13536 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13537 } 13538 } 13539 13540 // TR 18037 does not allow fields to be declared with address spaces. 13541 if (T.getQualifiers().hasAddressSpace()) { 13542 Diag(Loc, diag::err_field_with_address_space); 13543 D.setInvalidType(); 13544 } 13545 13546 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13547 // used as structure or union field: image, sampler, event or block types. 13548 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13549 T->isSamplerT() || T->isBlockPointerType())) { 13550 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13551 D.setInvalidType(); 13552 } 13553 13554 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13555 13556 if (D.getDeclSpec().isInlineSpecified()) 13557 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13558 << getLangOpts().CPlusPlus1z; 13559 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13560 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13561 diag::err_invalid_thread) 13562 << DeclSpec::getSpecifierName(TSCS); 13563 13564 // Check to see if this name was declared as a member previously 13565 NamedDecl *PrevDecl = nullptr; 13566 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13567 LookupName(Previous, S); 13568 switch (Previous.getResultKind()) { 13569 case LookupResult::Found: 13570 case LookupResult::FoundUnresolvedValue: 13571 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13572 break; 13573 13574 case LookupResult::FoundOverloaded: 13575 PrevDecl = Previous.getRepresentativeDecl(); 13576 break; 13577 13578 case LookupResult::NotFound: 13579 case LookupResult::NotFoundInCurrentInstantiation: 13580 case LookupResult::Ambiguous: 13581 break; 13582 } 13583 Previous.suppressDiagnostics(); 13584 13585 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13586 // Maybe we will complain about the shadowed template parameter. 13587 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13588 // Just pretend that we didn't see the previous declaration. 13589 PrevDecl = nullptr; 13590 } 13591 13592 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13593 PrevDecl = nullptr; 13594 13595 bool Mutable 13596 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13597 SourceLocation TSSL = D.getLocStart(); 13598 FieldDecl *NewFD 13599 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13600 TSSL, AS, PrevDecl, &D); 13601 13602 if (NewFD->isInvalidDecl()) 13603 Record->setInvalidDecl(); 13604 13605 if (D.getDeclSpec().isModulePrivateSpecified()) 13606 NewFD->setModulePrivate(); 13607 13608 if (NewFD->isInvalidDecl() && PrevDecl) { 13609 // Don't introduce NewFD into scope; there's already something 13610 // with the same name in the same scope. 13611 } else if (II) { 13612 PushOnScopeChains(NewFD, S); 13613 } else 13614 Record->addDecl(NewFD); 13615 13616 return NewFD; 13617 } 13618 13619 /// \brief Build a new FieldDecl and check its well-formedness. 13620 /// 13621 /// This routine builds a new FieldDecl given the fields name, type, 13622 /// record, etc. \p PrevDecl should refer to any previous declaration 13623 /// with the same name and in the same scope as the field to be 13624 /// created. 13625 /// 13626 /// \returns a new FieldDecl. 13627 /// 13628 /// \todo The Declarator argument is a hack. It will be removed once 13629 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13630 TypeSourceInfo *TInfo, 13631 RecordDecl *Record, SourceLocation Loc, 13632 bool Mutable, Expr *BitWidth, 13633 InClassInitStyle InitStyle, 13634 SourceLocation TSSL, 13635 AccessSpecifier AS, NamedDecl *PrevDecl, 13636 Declarator *D) { 13637 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13638 bool InvalidDecl = false; 13639 if (D) InvalidDecl = D->isInvalidType(); 13640 13641 // If we receive a broken type, recover by assuming 'int' and 13642 // marking this declaration as invalid. 13643 if (T.isNull()) { 13644 InvalidDecl = true; 13645 T = Context.IntTy; 13646 } 13647 13648 QualType EltTy = Context.getBaseElementType(T); 13649 if (!EltTy->isDependentType()) { 13650 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13651 // Fields of incomplete type force their record to be invalid. 13652 Record->setInvalidDecl(); 13653 InvalidDecl = true; 13654 } else { 13655 NamedDecl *Def; 13656 EltTy->isIncompleteType(&Def); 13657 if (Def && Def->isInvalidDecl()) { 13658 Record->setInvalidDecl(); 13659 InvalidDecl = true; 13660 } 13661 } 13662 } 13663 13664 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13665 if (BitWidth && getLangOpts().OpenCL) { 13666 Diag(Loc, diag::err_opencl_bitfields); 13667 InvalidDecl = true; 13668 } 13669 13670 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13671 // than a variably modified type. 13672 if (!InvalidDecl && T->isVariablyModifiedType()) { 13673 bool SizeIsNegative; 13674 llvm::APSInt Oversized; 13675 13676 TypeSourceInfo *FixedTInfo = 13677 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13678 SizeIsNegative, 13679 Oversized); 13680 if (FixedTInfo) { 13681 Diag(Loc, diag::warn_illegal_constant_array_size); 13682 TInfo = FixedTInfo; 13683 T = FixedTInfo->getType(); 13684 } else { 13685 if (SizeIsNegative) 13686 Diag(Loc, diag::err_typecheck_negative_array_size); 13687 else if (Oversized.getBoolValue()) 13688 Diag(Loc, diag::err_array_too_large) 13689 << Oversized.toString(10); 13690 else 13691 Diag(Loc, diag::err_typecheck_field_variable_size); 13692 InvalidDecl = true; 13693 } 13694 } 13695 13696 // Fields can not have abstract class types 13697 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13698 diag::err_abstract_type_in_decl, 13699 AbstractFieldType)) 13700 InvalidDecl = true; 13701 13702 bool ZeroWidth = false; 13703 if (InvalidDecl) 13704 BitWidth = nullptr; 13705 // If this is declared as a bit-field, check the bit-field. 13706 if (BitWidth) { 13707 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13708 &ZeroWidth).get(); 13709 if (!BitWidth) { 13710 InvalidDecl = true; 13711 BitWidth = nullptr; 13712 ZeroWidth = false; 13713 } 13714 } 13715 13716 // Check that 'mutable' is consistent with the type of the declaration. 13717 if (!InvalidDecl && Mutable) { 13718 unsigned DiagID = 0; 13719 if (T->isReferenceType()) 13720 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13721 : diag::err_mutable_reference; 13722 else if (T.isConstQualified()) 13723 DiagID = diag::err_mutable_const; 13724 13725 if (DiagID) { 13726 SourceLocation ErrLoc = Loc; 13727 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13728 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13729 Diag(ErrLoc, DiagID); 13730 if (DiagID != diag::ext_mutable_reference) { 13731 Mutable = false; 13732 InvalidDecl = true; 13733 } 13734 } 13735 } 13736 13737 // C++11 [class.union]p8 (DR1460): 13738 // At most one variant member of a union may have a 13739 // brace-or-equal-initializer. 13740 if (InitStyle != ICIS_NoInit) 13741 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13742 13743 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13744 BitWidth, Mutable, InitStyle); 13745 if (InvalidDecl) 13746 NewFD->setInvalidDecl(); 13747 13748 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13749 Diag(Loc, diag::err_duplicate_member) << II; 13750 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13751 NewFD->setInvalidDecl(); 13752 } 13753 13754 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13755 if (Record->isUnion()) { 13756 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13757 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13758 if (RDecl->getDefinition()) { 13759 // C++ [class.union]p1: An object of a class with a non-trivial 13760 // constructor, a non-trivial copy constructor, a non-trivial 13761 // destructor, or a non-trivial copy assignment operator 13762 // cannot be a member of a union, nor can an array of such 13763 // objects. 13764 if (CheckNontrivialField(NewFD)) 13765 NewFD->setInvalidDecl(); 13766 } 13767 } 13768 13769 // C++ [class.union]p1: If a union contains a member of reference type, 13770 // the program is ill-formed, except when compiling with MSVC extensions 13771 // enabled. 13772 if (EltTy->isReferenceType()) { 13773 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13774 diag::ext_union_member_of_reference_type : 13775 diag::err_union_member_of_reference_type) 13776 << NewFD->getDeclName() << EltTy; 13777 if (!getLangOpts().MicrosoftExt) 13778 NewFD->setInvalidDecl(); 13779 } 13780 } 13781 } 13782 13783 // FIXME: We need to pass in the attributes given an AST 13784 // representation, not a parser representation. 13785 if (D) { 13786 // FIXME: The current scope is almost... but not entirely... correct here. 13787 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13788 13789 if (NewFD->hasAttrs()) 13790 CheckAlignasUnderalignment(NewFD); 13791 } 13792 13793 // In auto-retain/release, infer strong retension for fields of 13794 // retainable type. 13795 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13796 NewFD->setInvalidDecl(); 13797 13798 if (T.isObjCGCWeak()) 13799 Diag(Loc, diag::warn_attribute_weak_on_field); 13800 13801 NewFD->setAccess(AS); 13802 return NewFD; 13803 } 13804 13805 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13806 assert(FD); 13807 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13808 13809 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13810 return false; 13811 13812 QualType EltTy = Context.getBaseElementType(FD->getType()); 13813 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13814 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13815 if (RDecl->getDefinition()) { 13816 // We check for copy constructors before constructors 13817 // because otherwise we'll never get complaints about 13818 // copy constructors. 13819 13820 CXXSpecialMember member = CXXInvalid; 13821 // We're required to check for any non-trivial constructors. Since the 13822 // implicit default constructor is suppressed if there are any 13823 // user-declared constructors, we just need to check that there is a 13824 // trivial default constructor and a trivial copy constructor. (We don't 13825 // worry about move constructors here, since this is a C++98 check.) 13826 if (RDecl->hasNonTrivialCopyConstructor()) 13827 member = CXXCopyConstructor; 13828 else if (!RDecl->hasTrivialDefaultConstructor()) 13829 member = CXXDefaultConstructor; 13830 else if (RDecl->hasNonTrivialCopyAssignment()) 13831 member = CXXCopyAssignment; 13832 else if (RDecl->hasNonTrivialDestructor()) 13833 member = CXXDestructor; 13834 13835 if (member != CXXInvalid) { 13836 if (!getLangOpts().CPlusPlus11 && 13837 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13838 // Objective-C++ ARC: it is an error to have a non-trivial field of 13839 // a union. However, system headers in Objective-C programs 13840 // occasionally have Objective-C lifetime objects within unions, 13841 // and rather than cause the program to fail, we make those 13842 // members unavailable. 13843 SourceLocation Loc = FD->getLocation(); 13844 if (getSourceManager().isInSystemHeader(Loc)) { 13845 if (!FD->hasAttr<UnavailableAttr>()) 13846 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13847 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13848 return false; 13849 } 13850 } 13851 13852 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13853 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13854 diag::err_illegal_union_or_anon_struct_member) 13855 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13856 DiagnoseNontrivial(RDecl, member); 13857 return !getLangOpts().CPlusPlus11; 13858 } 13859 } 13860 } 13861 13862 return false; 13863 } 13864 13865 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13866 /// AST enum value. 13867 static ObjCIvarDecl::AccessControl 13868 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13869 switch (ivarVisibility) { 13870 default: llvm_unreachable("Unknown visitibility kind"); 13871 case tok::objc_private: return ObjCIvarDecl::Private; 13872 case tok::objc_public: return ObjCIvarDecl::Public; 13873 case tok::objc_protected: return ObjCIvarDecl::Protected; 13874 case tok::objc_package: return ObjCIvarDecl::Package; 13875 } 13876 } 13877 13878 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13879 /// in order to create an IvarDecl object for it. 13880 Decl *Sema::ActOnIvar(Scope *S, 13881 SourceLocation DeclStart, 13882 Declarator &D, Expr *BitfieldWidth, 13883 tok::ObjCKeywordKind Visibility) { 13884 13885 IdentifierInfo *II = D.getIdentifier(); 13886 Expr *BitWidth = (Expr*)BitfieldWidth; 13887 SourceLocation Loc = DeclStart; 13888 if (II) Loc = D.getIdentifierLoc(); 13889 13890 // FIXME: Unnamed fields can be handled in various different ways, for 13891 // example, unnamed unions inject all members into the struct namespace! 13892 13893 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13894 QualType T = TInfo->getType(); 13895 13896 if (BitWidth) { 13897 // 6.7.2.1p3, 6.7.2.1p4 13898 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13899 if (!BitWidth) 13900 D.setInvalidType(); 13901 } else { 13902 // Not a bitfield. 13903 13904 // validate II. 13905 13906 } 13907 if (T->isReferenceType()) { 13908 Diag(Loc, diag::err_ivar_reference_type); 13909 D.setInvalidType(); 13910 } 13911 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13912 // than a variably modified type. 13913 else if (T->isVariablyModifiedType()) { 13914 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13915 D.setInvalidType(); 13916 } 13917 13918 // Get the visibility (access control) for this ivar. 13919 ObjCIvarDecl::AccessControl ac = 13920 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13921 : ObjCIvarDecl::None; 13922 // Must set ivar's DeclContext to its enclosing interface. 13923 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13924 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13925 return nullptr; 13926 ObjCContainerDecl *EnclosingContext; 13927 if (ObjCImplementationDecl *IMPDecl = 13928 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13929 if (LangOpts.ObjCRuntime.isFragile()) { 13930 // Case of ivar declared in an implementation. Context is that of its class. 13931 EnclosingContext = IMPDecl->getClassInterface(); 13932 assert(EnclosingContext && "Implementation has no class interface!"); 13933 } 13934 else 13935 EnclosingContext = EnclosingDecl; 13936 } else { 13937 if (ObjCCategoryDecl *CDecl = 13938 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13939 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 13940 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 13941 return nullptr; 13942 } 13943 } 13944 EnclosingContext = EnclosingDecl; 13945 } 13946 13947 // Construct the decl. 13948 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 13949 DeclStart, Loc, II, T, 13950 TInfo, ac, (Expr *)BitfieldWidth); 13951 13952 if (II) { 13953 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 13954 ForRedeclaration); 13955 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 13956 && !isa<TagDecl>(PrevDecl)) { 13957 Diag(Loc, diag::err_duplicate_member) << II; 13958 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13959 NewID->setInvalidDecl(); 13960 } 13961 } 13962 13963 // Process attributes attached to the ivar. 13964 ProcessDeclAttributes(S, NewID, D); 13965 13966 if (D.isInvalidType()) 13967 NewID->setInvalidDecl(); 13968 13969 // In ARC, infer 'retaining' for ivars of retainable type. 13970 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 13971 NewID->setInvalidDecl(); 13972 13973 if (D.getDeclSpec().isModulePrivateSpecified()) 13974 NewID->setModulePrivate(); 13975 13976 if (II) { 13977 // FIXME: When interfaces are DeclContexts, we'll need to add 13978 // these to the interface. 13979 S->AddDecl(NewID); 13980 IdResolver.AddDecl(NewID); 13981 } 13982 13983 if (LangOpts.ObjCRuntime.isNonFragile() && 13984 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 13985 Diag(Loc, diag::warn_ivars_in_interface); 13986 13987 return NewID; 13988 } 13989 13990 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 13991 /// class and class extensions. For every class \@interface and class 13992 /// extension \@interface, if the last ivar is a bitfield of any type, 13993 /// then add an implicit `char :0` ivar to the end of that interface. 13994 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 13995 SmallVectorImpl<Decl *> &AllIvarDecls) { 13996 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 13997 return; 13998 13999 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14000 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14001 14002 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14003 return; 14004 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14005 if (!ID) { 14006 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14007 if (!CD->IsClassExtension()) 14008 return; 14009 } 14010 // No need to add this to end of @implementation. 14011 else 14012 return; 14013 } 14014 // All conditions are met. Add a new bitfield to the tail end of ivars. 14015 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14016 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14017 14018 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14019 DeclLoc, DeclLoc, nullptr, 14020 Context.CharTy, 14021 Context.getTrivialTypeSourceInfo(Context.CharTy, 14022 DeclLoc), 14023 ObjCIvarDecl::Private, BW, 14024 true); 14025 AllIvarDecls.push_back(Ivar); 14026 } 14027 14028 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14029 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14030 SourceLocation RBrac, AttributeList *Attr) { 14031 assert(EnclosingDecl && "missing record or interface decl"); 14032 14033 // If this is an Objective-C @implementation or category and we have 14034 // new fields here we should reset the layout of the interface since 14035 // it will now change. 14036 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14037 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14038 switch (DC->getKind()) { 14039 default: break; 14040 case Decl::ObjCCategory: 14041 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14042 break; 14043 case Decl::ObjCImplementation: 14044 Context. 14045 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14046 break; 14047 } 14048 } 14049 14050 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14051 14052 // Start counting up the number of named members; make sure to include 14053 // members of anonymous structs and unions in the total. 14054 unsigned NumNamedMembers = 0; 14055 if (Record) { 14056 for (const auto *I : Record->decls()) { 14057 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14058 if (IFD->getDeclName()) 14059 ++NumNamedMembers; 14060 } 14061 } 14062 14063 // Verify that all the fields are okay. 14064 SmallVector<FieldDecl*, 32> RecFields; 14065 14066 bool ARCErrReported = false; 14067 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14068 i != end; ++i) { 14069 FieldDecl *FD = cast<FieldDecl>(*i); 14070 14071 // Get the type for the field. 14072 const Type *FDTy = FD->getType().getTypePtr(); 14073 14074 if (!FD->isAnonymousStructOrUnion()) { 14075 // Remember all fields written by the user. 14076 RecFields.push_back(FD); 14077 } 14078 14079 // If the field is already invalid for some reason, don't emit more 14080 // diagnostics about it. 14081 if (FD->isInvalidDecl()) { 14082 EnclosingDecl->setInvalidDecl(); 14083 continue; 14084 } 14085 14086 // C99 6.7.2.1p2: 14087 // A structure or union shall not contain a member with 14088 // incomplete or function type (hence, a structure shall not 14089 // contain an instance of itself, but may contain a pointer to 14090 // an instance of itself), except that the last member of a 14091 // structure with more than one named member may have incomplete 14092 // array type; such a structure (and any union containing, 14093 // possibly recursively, a member that is such a structure) 14094 // shall not be a member of a structure or an element of an 14095 // array. 14096 if (FDTy->isFunctionType()) { 14097 // Field declared as a function. 14098 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14099 << FD->getDeclName(); 14100 FD->setInvalidDecl(); 14101 EnclosingDecl->setInvalidDecl(); 14102 continue; 14103 } else if (FDTy->isIncompleteArrayType() && Record && 14104 ((i + 1 == Fields.end() && !Record->isUnion()) || 14105 ((getLangOpts().MicrosoftExt || 14106 getLangOpts().CPlusPlus) && 14107 (i + 1 == Fields.end() || Record->isUnion())))) { 14108 // Flexible array member. 14109 // Microsoft and g++ is more permissive regarding flexible array. 14110 // It will accept flexible array in union and also 14111 // as the sole element of a struct/class. 14112 unsigned DiagID = 0; 14113 if (Record->isUnion()) 14114 DiagID = getLangOpts().MicrosoftExt 14115 ? diag::ext_flexible_array_union_ms 14116 : getLangOpts().CPlusPlus 14117 ? diag::ext_flexible_array_union_gnu 14118 : diag::err_flexible_array_union; 14119 else if (NumNamedMembers < 1) 14120 DiagID = getLangOpts().MicrosoftExt 14121 ? diag::ext_flexible_array_empty_aggregate_ms 14122 : getLangOpts().CPlusPlus 14123 ? diag::ext_flexible_array_empty_aggregate_gnu 14124 : diag::err_flexible_array_empty_aggregate; 14125 14126 if (DiagID) 14127 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14128 << Record->getTagKind(); 14129 // While the layout of types that contain virtual bases is not specified 14130 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14131 // virtual bases after the derived members. This would make a flexible 14132 // array member declared at the end of an object not adjacent to the end 14133 // of the type. 14134 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14135 if (RD->getNumVBases() != 0) 14136 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14137 << FD->getDeclName() << Record->getTagKind(); 14138 if (!getLangOpts().C99) 14139 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14140 << FD->getDeclName() << Record->getTagKind(); 14141 14142 // If the element type has a non-trivial destructor, we would not 14143 // implicitly destroy the elements, so disallow it for now. 14144 // 14145 // FIXME: GCC allows this. We should probably either implicitly delete 14146 // the destructor of the containing class, or just allow this. 14147 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14148 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14149 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14150 << FD->getDeclName() << FD->getType(); 14151 FD->setInvalidDecl(); 14152 EnclosingDecl->setInvalidDecl(); 14153 continue; 14154 } 14155 // Okay, we have a legal flexible array member at the end of the struct. 14156 Record->setHasFlexibleArrayMember(true); 14157 } else if (!FDTy->isDependentType() && 14158 RequireCompleteType(FD->getLocation(), FD->getType(), 14159 diag::err_field_incomplete)) { 14160 // Incomplete type 14161 FD->setInvalidDecl(); 14162 EnclosingDecl->setInvalidDecl(); 14163 continue; 14164 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14165 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14166 // A type which contains a flexible array member is considered to be a 14167 // flexible array member. 14168 Record->setHasFlexibleArrayMember(true); 14169 if (!Record->isUnion()) { 14170 // If this is a struct/class and this is not the last element, reject 14171 // it. Note that GCC supports variable sized arrays in the middle of 14172 // structures. 14173 if (i + 1 != Fields.end()) 14174 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14175 << FD->getDeclName() << FD->getType(); 14176 else { 14177 // We support flexible arrays at the end of structs in 14178 // other structs as an extension. 14179 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14180 << FD->getDeclName(); 14181 } 14182 } 14183 } 14184 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14185 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14186 diag::err_abstract_type_in_decl, 14187 AbstractIvarType)) { 14188 // Ivars can not have abstract class types 14189 FD->setInvalidDecl(); 14190 } 14191 if (Record && FDTTy->getDecl()->hasObjectMember()) 14192 Record->setHasObjectMember(true); 14193 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14194 Record->setHasVolatileMember(true); 14195 } else if (FDTy->isObjCObjectType()) { 14196 /// A field cannot be an Objective-c object 14197 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14198 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14199 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14200 FD->setType(T); 14201 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14202 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14203 // It's an error in ARC if a field has lifetime. 14204 // We don't want to report this in a system header, though, 14205 // so we just make the field unavailable. 14206 // FIXME: that's really not sufficient; we need to make the type 14207 // itself invalid to, say, initialize or copy. 14208 QualType T = FD->getType(); 14209 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14210 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14211 SourceLocation loc = FD->getLocation(); 14212 if (getSourceManager().isInSystemHeader(loc)) { 14213 if (!FD->hasAttr<UnavailableAttr>()) { 14214 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14215 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14216 } 14217 } else { 14218 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14219 << T->isBlockPointerType() << Record->getTagKind(); 14220 } 14221 ARCErrReported = true; 14222 } 14223 } else if (getLangOpts().ObjC1 && 14224 getLangOpts().getGC() != LangOptions::NonGC && 14225 Record && !Record->hasObjectMember()) { 14226 if (FD->getType()->isObjCObjectPointerType() || 14227 FD->getType().isObjCGCStrong()) 14228 Record->setHasObjectMember(true); 14229 else if (Context.getAsArrayType(FD->getType())) { 14230 QualType BaseType = Context.getBaseElementType(FD->getType()); 14231 if (BaseType->isRecordType() && 14232 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14233 Record->setHasObjectMember(true); 14234 else if (BaseType->isObjCObjectPointerType() || 14235 BaseType.isObjCGCStrong()) 14236 Record->setHasObjectMember(true); 14237 } 14238 } 14239 if (Record && FD->getType().isVolatileQualified()) 14240 Record->setHasVolatileMember(true); 14241 // Keep track of the number of named members. 14242 if (FD->getIdentifier()) 14243 ++NumNamedMembers; 14244 } 14245 14246 // Okay, we successfully defined 'Record'. 14247 if (Record) { 14248 bool Completed = false; 14249 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14250 if (!CXXRecord->isInvalidDecl()) { 14251 // Set access bits correctly on the directly-declared conversions. 14252 for (CXXRecordDecl::conversion_iterator 14253 I = CXXRecord->conversion_begin(), 14254 E = CXXRecord->conversion_end(); I != E; ++I) 14255 I.setAccess((*I)->getAccess()); 14256 } 14257 14258 if (!CXXRecord->isDependentType()) { 14259 if (CXXRecord->hasUserDeclaredDestructor()) { 14260 // Adjust user-defined destructor exception spec. 14261 if (getLangOpts().CPlusPlus11) 14262 AdjustDestructorExceptionSpec(CXXRecord, 14263 CXXRecord->getDestructor()); 14264 } 14265 14266 if (!CXXRecord->isInvalidDecl()) { 14267 // Add any implicitly-declared members to this class. 14268 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14269 14270 // If we have virtual base classes, we may end up finding multiple 14271 // final overriders for a given virtual function. Check for this 14272 // problem now. 14273 if (CXXRecord->getNumVBases()) { 14274 CXXFinalOverriderMap FinalOverriders; 14275 CXXRecord->getFinalOverriders(FinalOverriders); 14276 14277 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14278 MEnd = FinalOverriders.end(); 14279 M != MEnd; ++M) { 14280 for (OverridingMethods::iterator SO = M->second.begin(), 14281 SOEnd = M->second.end(); 14282 SO != SOEnd; ++SO) { 14283 assert(SO->second.size() > 0 && 14284 "Virtual function without overridding functions?"); 14285 if (SO->second.size() == 1) 14286 continue; 14287 14288 // C++ [class.virtual]p2: 14289 // In a derived class, if a virtual member function of a base 14290 // class subobject has more than one final overrider the 14291 // program is ill-formed. 14292 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14293 << (const NamedDecl *)M->first << Record; 14294 Diag(M->first->getLocation(), 14295 diag::note_overridden_virtual_function); 14296 for (OverridingMethods::overriding_iterator 14297 OM = SO->second.begin(), 14298 OMEnd = SO->second.end(); 14299 OM != OMEnd; ++OM) 14300 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14301 << (const NamedDecl *)M->first << OM->Method->getParent(); 14302 14303 Record->setInvalidDecl(); 14304 } 14305 } 14306 CXXRecord->completeDefinition(&FinalOverriders); 14307 Completed = true; 14308 } 14309 } 14310 } 14311 } 14312 14313 if (!Completed) 14314 Record->completeDefinition(); 14315 14316 if (Record->hasAttrs()) { 14317 CheckAlignasUnderalignment(Record); 14318 14319 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14320 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14321 IA->getRange(), IA->getBestCase(), 14322 IA->getSemanticSpelling()); 14323 } 14324 14325 // Check if the structure/union declaration is a type that can have zero 14326 // size in C. For C this is a language extension, for C++ it may cause 14327 // compatibility problems. 14328 bool CheckForZeroSize; 14329 if (!getLangOpts().CPlusPlus) { 14330 CheckForZeroSize = true; 14331 } else { 14332 // For C++ filter out types that cannot be referenced in C code. 14333 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14334 CheckForZeroSize = 14335 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14336 !CXXRecord->isDependentType() && 14337 CXXRecord->isCLike(); 14338 } 14339 if (CheckForZeroSize) { 14340 bool ZeroSize = true; 14341 bool IsEmpty = true; 14342 unsigned NonBitFields = 0; 14343 for (RecordDecl::field_iterator I = Record->field_begin(), 14344 E = Record->field_end(); 14345 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14346 IsEmpty = false; 14347 if (I->isUnnamedBitfield()) { 14348 if (I->getBitWidthValue(Context) > 0) 14349 ZeroSize = false; 14350 } else { 14351 ++NonBitFields; 14352 QualType FieldType = I->getType(); 14353 if (FieldType->isIncompleteType() || 14354 !Context.getTypeSizeInChars(FieldType).isZero()) 14355 ZeroSize = false; 14356 } 14357 } 14358 14359 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14360 // allowed in C++, but warn if its declaration is inside 14361 // extern "C" block. 14362 if (ZeroSize) { 14363 Diag(RecLoc, getLangOpts().CPlusPlus ? 14364 diag::warn_zero_size_struct_union_in_extern_c : 14365 diag::warn_zero_size_struct_union_compat) 14366 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14367 } 14368 14369 // Structs without named members are extension in C (C99 6.7.2.1p7), 14370 // but are accepted by GCC. 14371 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14372 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14373 diag::ext_no_named_members_in_struct_union) 14374 << Record->isUnion(); 14375 } 14376 } 14377 } else { 14378 ObjCIvarDecl **ClsFields = 14379 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14380 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14381 ID->setEndOfDefinitionLoc(RBrac); 14382 // Add ivar's to class's DeclContext. 14383 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14384 ClsFields[i]->setLexicalDeclContext(ID); 14385 ID->addDecl(ClsFields[i]); 14386 } 14387 // Must enforce the rule that ivars in the base classes may not be 14388 // duplicates. 14389 if (ID->getSuperClass()) 14390 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14391 } else if (ObjCImplementationDecl *IMPDecl = 14392 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14393 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14394 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14395 // Ivar declared in @implementation never belongs to the implementation. 14396 // Only it is in implementation's lexical context. 14397 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14398 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14399 IMPDecl->setIvarLBraceLoc(LBrac); 14400 IMPDecl->setIvarRBraceLoc(RBrac); 14401 } else if (ObjCCategoryDecl *CDecl = 14402 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14403 // case of ivars in class extension; all other cases have been 14404 // reported as errors elsewhere. 14405 // FIXME. Class extension does not have a LocEnd field. 14406 // CDecl->setLocEnd(RBrac); 14407 // Add ivar's to class extension's DeclContext. 14408 // Diagnose redeclaration of private ivars. 14409 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14410 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14411 if (IDecl) { 14412 if (const ObjCIvarDecl *ClsIvar = 14413 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14414 Diag(ClsFields[i]->getLocation(), 14415 diag::err_duplicate_ivar_declaration); 14416 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14417 continue; 14418 } 14419 for (const auto *Ext : IDecl->known_extensions()) { 14420 if (const ObjCIvarDecl *ClsExtIvar 14421 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14422 Diag(ClsFields[i]->getLocation(), 14423 diag::err_duplicate_ivar_declaration); 14424 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14425 continue; 14426 } 14427 } 14428 } 14429 ClsFields[i]->setLexicalDeclContext(CDecl); 14430 CDecl->addDecl(ClsFields[i]); 14431 } 14432 CDecl->setIvarLBraceLoc(LBrac); 14433 CDecl->setIvarRBraceLoc(RBrac); 14434 } 14435 } 14436 14437 if (Attr) 14438 ProcessDeclAttributeList(S, Record, Attr); 14439 } 14440 14441 /// \brief Determine whether the given integral value is representable within 14442 /// the given type T. 14443 static bool isRepresentableIntegerValue(ASTContext &Context, 14444 llvm::APSInt &Value, 14445 QualType T) { 14446 assert(T->isIntegralType(Context) && "Integral type required!"); 14447 unsigned BitWidth = Context.getIntWidth(T); 14448 14449 if (Value.isUnsigned() || Value.isNonNegative()) { 14450 if (T->isSignedIntegerOrEnumerationType()) 14451 --BitWidth; 14452 return Value.getActiveBits() <= BitWidth; 14453 } 14454 return Value.getMinSignedBits() <= BitWidth; 14455 } 14456 14457 // \brief Given an integral type, return the next larger integral type 14458 // (or a NULL type of no such type exists). 14459 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14460 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14461 // enum checking below. 14462 assert(T->isIntegralType(Context) && "Integral type required!"); 14463 const unsigned NumTypes = 4; 14464 QualType SignedIntegralTypes[NumTypes] = { 14465 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14466 }; 14467 QualType UnsignedIntegralTypes[NumTypes] = { 14468 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14469 Context.UnsignedLongLongTy 14470 }; 14471 14472 unsigned BitWidth = Context.getTypeSize(T); 14473 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14474 : UnsignedIntegralTypes; 14475 for (unsigned I = 0; I != NumTypes; ++I) 14476 if (Context.getTypeSize(Types[I]) > BitWidth) 14477 return Types[I]; 14478 14479 return QualType(); 14480 } 14481 14482 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14483 EnumConstantDecl *LastEnumConst, 14484 SourceLocation IdLoc, 14485 IdentifierInfo *Id, 14486 Expr *Val) { 14487 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14488 llvm::APSInt EnumVal(IntWidth); 14489 QualType EltTy; 14490 14491 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14492 Val = nullptr; 14493 14494 if (Val) 14495 Val = DefaultLvalueConversion(Val).get(); 14496 14497 if (Val) { 14498 if (Enum->isDependentType() || Val->isTypeDependent()) 14499 EltTy = Context.DependentTy; 14500 else { 14501 SourceLocation ExpLoc; 14502 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14503 !getLangOpts().MSVCCompat) { 14504 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14505 // constant-expression in the enumerator-definition shall be a converted 14506 // constant expression of the underlying type. 14507 EltTy = Enum->getIntegerType(); 14508 ExprResult Converted = 14509 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14510 CCEK_Enumerator); 14511 if (Converted.isInvalid()) 14512 Val = nullptr; 14513 else 14514 Val = Converted.get(); 14515 } else if (!Val->isValueDependent() && 14516 !(Val = VerifyIntegerConstantExpression(Val, 14517 &EnumVal).get())) { 14518 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14519 } else { 14520 if (Enum->isFixed()) { 14521 EltTy = Enum->getIntegerType(); 14522 14523 // In Obj-C and Microsoft mode, require the enumeration value to be 14524 // representable in the underlying type of the enumeration. In C++11, 14525 // we perform a non-narrowing conversion as part of converted constant 14526 // expression checking. 14527 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14528 if (getLangOpts().MSVCCompat) { 14529 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14530 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14531 } else 14532 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14533 } else 14534 Val = ImpCastExprToType(Val, EltTy, 14535 EltTy->isBooleanType() ? 14536 CK_IntegralToBoolean : CK_IntegralCast) 14537 .get(); 14538 } else if (getLangOpts().CPlusPlus) { 14539 // C++11 [dcl.enum]p5: 14540 // If the underlying type is not fixed, the type of each enumerator 14541 // is the type of its initializing value: 14542 // - If an initializer is specified for an enumerator, the 14543 // initializing value has the same type as the expression. 14544 EltTy = Val->getType(); 14545 } else { 14546 // C99 6.7.2.2p2: 14547 // The expression that defines the value of an enumeration constant 14548 // shall be an integer constant expression that has a value 14549 // representable as an int. 14550 14551 // Complain if the value is not representable in an int. 14552 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14553 Diag(IdLoc, diag::ext_enum_value_not_int) 14554 << EnumVal.toString(10) << Val->getSourceRange() 14555 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14556 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14557 // Force the type of the expression to 'int'. 14558 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14559 } 14560 EltTy = Val->getType(); 14561 } 14562 } 14563 } 14564 } 14565 14566 if (!Val) { 14567 if (Enum->isDependentType()) 14568 EltTy = Context.DependentTy; 14569 else if (!LastEnumConst) { 14570 // C++0x [dcl.enum]p5: 14571 // If the underlying type is not fixed, the type of each enumerator 14572 // is the type of its initializing value: 14573 // - If no initializer is specified for the first enumerator, the 14574 // initializing value has an unspecified integral type. 14575 // 14576 // GCC uses 'int' for its unspecified integral type, as does 14577 // C99 6.7.2.2p3. 14578 if (Enum->isFixed()) { 14579 EltTy = Enum->getIntegerType(); 14580 } 14581 else { 14582 EltTy = Context.IntTy; 14583 } 14584 } else { 14585 // Assign the last value + 1. 14586 EnumVal = LastEnumConst->getInitVal(); 14587 ++EnumVal; 14588 EltTy = LastEnumConst->getType(); 14589 14590 // Check for overflow on increment. 14591 if (EnumVal < LastEnumConst->getInitVal()) { 14592 // C++0x [dcl.enum]p5: 14593 // If the underlying type is not fixed, the type of each enumerator 14594 // is the type of its initializing value: 14595 // 14596 // - Otherwise the type of the initializing value is the same as 14597 // the type of the initializing value of the preceding enumerator 14598 // unless the incremented value is not representable in that type, 14599 // in which case the type is an unspecified integral type 14600 // sufficient to contain the incremented value. If no such type 14601 // exists, the program is ill-formed. 14602 QualType T = getNextLargerIntegralType(Context, EltTy); 14603 if (T.isNull() || Enum->isFixed()) { 14604 // There is no integral type larger enough to represent this 14605 // value. Complain, then allow the value to wrap around. 14606 EnumVal = LastEnumConst->getInitVal(); 14607 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14608 ++EnumVal; 14609 if (Enum->isFixed()) 14610 // When the underlying type is fixed, this is ill-formed. 14611 Diag(IdLoc, diag::err_enumerator_wrapped) 14612 << EnumVal.toString(10) 14613 << EltTy; 14614 else 14615 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14616 << EnumVal.toString(10); 14617 } else { 14618 EltTy = T; 14619 } 14620 14621 // Retrieve the last enumerator's value, extent that type to the 14622 // type that is supposed to be large enough to represent the incremented 14623 // value, then increment. 14624 EnumVal = LastEnumConst->getInitVal(); 14625 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14626 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14627 ++EnumVal; 14628 14629 // If we're not in C++, diagnose the overflow of enumerator values, 14630 // which in C99 means that the enumerator value is not representable in 14631 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14632 // permits enumerator values that are representable in some larger 14633 // integral type. 14634 if (!getLangOpts().CPlusPlus && !T.isNull()) 14635 Diag(IdLoc, diag::warn_enum_value_overflow); 14636 } else if (!getLangOpts().CPlusPlus && 14637 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14638 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14639 Diag(IdLoc, diag::ext_enum_value_not_int) 14640 << EnumVal.toString(10) << 1; 14641 } 14642 } 14643 } 14644 14645 if (!EltTy->isDependentType()) { 14646 // Make the enumerator value match the signedness and size of the 14647 // enumerator's type. 14648 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14649 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14650 } 14651 14652 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14653 Val, EnumVal); 14654 } 14655 14656 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14657 SourceLocation IILoc) { 14658 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14659 !getLangOpts().CPlusPlus) 14660 return SkipBodyInfo(); 14661 14662 // We have an anonymous enum definition. Look up the first enumerator to 14663 // determine if we should merge the definition with an existing one and 14664 // skip the body. 14665 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14666 ForRedeclaration); 14667 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14668 if (!PrevECD) 14669 return SkipBodyInfo(); 14670 14671 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14672 NamedDecl *Hidden; 14673 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14674 SkipBodyInfo Skip; 14675 Skip.Previous = Hidden; 14676 return Skip; 14677 } 14678 14679 return SkipBodyInfo(); 14680 } 14681 14682 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14683 SourceLocation IdLoc, IdentifierInfo *Id, 14684 AttributeList *Attr, 14685 SourceLocation EqualLoc, Expr *Val) { 14686 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14687 EnumConstantDecl *LastEnumConst = 14688 cast_or_null<EnumConstantDecl>(lastEnumConst); 14689 14690 // The scope passed in may not be a decl scope. Zip up the scope tree until 14691 // we find one that is. 14692 S = getNonFieldDeclScope(S); 14693 14694 // Verify that there isn't already something declared with this name in this 14695 // scope. 14696 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14697 ForRedeclaration); 14698 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14699 // Maybe we will complain about the shadowed template parameter. 14700 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14701 // Just pretend that we didn't see the previous declaration. 14702 PrevDecl = nullptr; 14703 } 14704 14705 // C++ [class.mem]p15: 14706 // If T is the name of a class, then each of the following shall have a name 14707 // different from T: 14708 // - every enumerator of every member of class T that is an unscoped 14709 // enumerated type 14710 if (!TheEnumDecl->isScoped()) 14711 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14712 DeclarationNameInfo(Id, IdLoc)); 14713 14714 EnumConstantDecl *New = 14715 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14716 if (!New) 14717 return nullptr; 14718 14719 if (PrevDecl) { 14720 // When in C++, we may get a TagDecl with the same name; in this case the 14721 // enum constant will 'hide' the tag. 14722 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14723 "Received TagDecl when not in C++!"); 14724 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14725 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14726 if (isa<EnumConstantDecl>(PrevDecl)) 14727 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14728 else 14729 Diag(IdLoc, diag::err_redefinition) << Id; 14730 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14731 return nullptr; 14732 } 14733 } 14734 14735 // Process attributes. 14736 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14737 14738 // Register this decl in the current scope stack. 14739 New->setAccess(TheEnumDecl->getAccess()); 14740 PushOnScopeChains(New, S); 14741 14742 ActOnDocumentableDecl(New); 14743 14744 return New; 14745 } 14746 14747 // Returns true when the enum initial expression does not trigger the 14748 // duplicate enum warning. A few common cases are exempted as follows: 14749 // Element2 = Element1 14750 // Element2 = Element1 + 1 14751 // Element2 = Element1 - 1 14752 // Where Element2 and Element1 are from the same enum. 14753 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14754 Expr *InitExpr = ECD->getInitExpr(); 14755 if (!InitExpr) 14756 return true; 14757 InitExpr = InitExpr->IgnoreImpCasts(); 14758 14759 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14760 if (!BO->isAdditiveOp()) 14761 return true; 14762 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14763 if (!IL) 14764 return true; 14765 if (IL->getValue() != 1) 14766 return true; 14767 14768 InitExpr = BO->getLHS(); 14769 } 14770 14771 // This checks if the elements are from the same enum. 14772 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14773 if (!DRE) 14774 return true; 14775 14776 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14777 if (!EnumConstant) 14778 return true; 14779 14780 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14781 Enum) 14782 return true; 14783 14784 return false; 14785 } 14786 14787 namespace { 14788 struct DupKey { 14789 int64_t val; 14790 bool isTombstoneOrEmptyKey; 14791 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14792 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14793 }; 14794 14795 static DupKey GetDupKey(const llvm::APSInt& Val) { 14796 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14797 false); 14798 } 14799 14800 struct DenseMapInfoDupKey { 14801 static DupKey getEmptyKey() { return DupKey(0, true); } 14802 static DupKey getTombstoneKey() { return DupKey(1, true); } 14803 static unsigned getHashValue(const DupKey Key) { 14804 return (unsigned)(Key.val * 37); 14805 } 14806 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14807 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14808 LHS.val == RHS.val; 14809 } 14810 }; 14811 } // end anonymous namespace 14812 14813 // Emits a warning when an element is implicitly set a value that 14814 // a previous element has already been set to. 14815 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14816 EnumDecl *Enum, 14817 QualType EnumType) { 14818 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14819 return; 14820 // Avoid anonymous enums 14821 if (!Enum->getIdentifier()) 14822 return; 14823 14824 // Only check for small enums. 14825 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14826 return; 14827 14828 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14829 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14830 14831 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14832 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14833 ValueToVectorMap; 14834 14835 DuplicatesVector DupVector; 14836 ValueToVectorMap EnumMap; 14837 14838 // Populate the EnumMap with all values represented by enum constants without 14839 // an initialier. 14840 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14841 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14842 14843 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14844 // this constant. Skip this enum since it may be ill-formed. 14845 if (!ECD) { 14846 return; 14847 } 14848 14849 if (ECD->getInitExpr()) 14850 continue; 14851 14852 DupKey Key = GetDupKey(ECD->getInitVal()); 14853 DeclOrVector &Entry = EnumMap[Key]; 14854 14855 // First time encountering this value. 14856 if (Entry.isNull()) 14857 Entry = ECD; 14858 } 14859 14860 // Create vectors for any values that has duplicates. 14861 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14862 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14863 if (!ValidDuplicateEnum(ECD, Enum)) 14864 continue; 14865 14866 DupKey Key = GetDupKey(ECD->getInitVal()); 14867 14868 DeclOrVector& Entry = EnumMap[Key]; 14869 if (Entry.isNull()) 14870 continue; 14871 14872 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14873 // Ensure constants are different. 14874 if (D == ECD) 14875 continue; 14876 14877 // Create new vector and push values onto it. 14878 ECDVector *Vec = new ECDVector(); 14879 Vec->push_back(D); 14880 Vec->push_back(ECD); 14881 14882 // Update entry to point to the duplicates vector. 14883 Entry = Vec; 14884 14885 // Store the vector somewhere we can consult later for quick emission of 14886 // diagnostics. 14887 DupVector.push_back(Vec); 14888 continue; 14889 } 14890 14891 ECDVector *Vec = Entry.get<ECDVector*>(); 14892 // Make sure constants are not added more than once. 14893 if (*Vec->begin() == ECD) 14894 continue; 14895 14896 Vec->push_back(ECD); 14897 } 14898 14899 // Emit diagnostics. 14900 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14901 DupVectorEnd = DupVector.end(); 14902 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14903 ECDVector *Vec = *DupVectorIter; 14904 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14905 14906 // Emit warning for one enum constant. 14907 ECDVector::iterator I = Vec->begin(); 14908 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14909 << (*I)->getName() << (*I)->getInitVal().toString(10) 14910 << (*I)->getSourceRange(); 14911 ++I; 14912 14913 // Emit one note for each of the remaining enum constants with 14914 // the same value. 14915 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14916 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14917 << (*I)->getName() << (*I)->getInitVal().toString(10) 14918 << (*I)->getSourceRange(); 14919 delete Vec; 14920 } 14921 } 14922 14923 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14924 bool AllowMask) const { 14925 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14926 assert(ED->isCompleteDefinition() && "expected enum definition"); 14927 14928 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 14929 llvm::APInt &FlagBits = R.first->second; 14930 14931 if (R.second) { 14932 for (auto *E : ED->enumerators()) { 14933 const auto &EVal = E->getInitVal(); 14934 // Only single-bit enumerators introduce new flag values. 14935 if (EVal.isPowerOf2()) 14936 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 14937 } 14938 } 14939 14940 // A value is in a flag enum if either its bits are a subset of the enum's 14941 // flag bits (the first condition) or we are allowing masks and the same is 14942 // true of its complement (the second condition). When masks are allowed, we 14943 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 14944 // 14945 // While it's true that any value could be used as a mask, the assumption is 14946 // that a mask will have all of the insignificant bits set. Anything else is 14947 // likely a logic error. 14948 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 14949 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 14950 } 14951 14952 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 14953 Decl *EnumDeclX, 14954 ArrayRef<Decl *> Elements, 14955 Scope *S, AttributeList *Attr) { 14956 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 14957 QualType EnumType = Context.getTypeDeclType(Enum); 14958 14959 if (Attr) 14960 ProcessDeclAttributeList(S, Enum, Attr); 14961 14962 if (Enum->isDependentType()) { 14963 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14964 EnumConstantDecl *ECD = 14965 cast_or_null<EnumConstantDecl>(Elements[i]); 14966 if (!ECD) continue; 14967 14968 ECD->setType(EnumType); 14969 } 14970 14971 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 14972 return; 14973 } 14974 14975 // TODO: If the result value doesn't fit in an int, it must be a long or long 14976 // long value. ISO C does not support this, but GCC does as an extension, 14977 // emit a warning. 14978 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14979 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 14980 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 14981 14982 // Verify that all the values are okay, compute the size of the values, and 14983 // reverse the list. 14984 unsigned NumNegativeBits = 0; 14985 unsigned NumPositiveBits = 0; 14986 14987 // Keep track of whether all elements have type int. 14988 bool AllElementsInt = true; 14989 14990 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14991 EnumConstantDecl *ECD = 14992 cast_or_null<EnumConstantDecl>(Elements[i]); 14993 if (!ECD) continue; // Already issued a diagnostic. 14994 14995 const llvm::APSInt &InitVal = ECD->getInitVal(); 14996 14997 // Keep track of the size of positive and negative values. 14998 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 14999 NumPositiveBits = std::max(NumPositiveBits, 15000 (unsigned)InitVal.getActiveBits()); 15001 else 15002 NumNegativeBits = std::max(NumNegativeBits, 15003 (unsigned)InitVal.getMinSignedBits()); 15004 15005 // Keep track of whether every enum element has type int (very commmon). 15006 if (AllElementsInt) 15007 AllElementsInt = ECD->getType() == Context.IntTy; 15008 } 15009 15010 // Figure out the type that should be used for this enum. 15011 QualType BestType; 15012 unsigned BestWidth; 15013 15014 // C++0x N3000 [conv.prom]p3: 15015 // An rvalue of an unscoped enumeration type whose underlying 15016 // type is not fixed can be converted to an rvalue of the first 15017 // of the following types that can represent all the values of 15018 // the enumeration: int, unsigned int, long int, unsigned long 15019 // int, long long int, or unsigned long long int. 15020 // C99 6.4.4.3p2: 15021 // An identifier declared as an enumeration constant has type int. 15022 // The C99 rule is modified by a gcc extension 15023 QualType BestPromotionType; 15024 15025 bool Packed = Enum->hasAttr<PackedAttr>(); 15026 // -fshort-enums is the equivalent to specifying the packed attribute on all 15027 // enum definitions. 15028 if (LangOpts.ShortEnums) 15029 Packed = true; 15030 15031 if (Enum->isFixed()) { 15032 BestType = Enum->getIntegerType(); 15033 if (BestType->isPromotableIntegerType()) 15034 BestPromotionType = Context.getPromotedIntegerType(BestType); 15035 else 15036 BestPromotionType = BestType; 15037 15038 BestWidth = Context.getIntWidth(BestType); 15039 } 15040 else if (NumNegativeBits) { 15041 // If there is a negative value, figure out the smallest integer type (of 15042 // int/long/longlong) that fits. 15043 // If it's packed, check also if it fits a char or a short. 15044 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15045 BestType = Context.SignedCharTy; 15046 BestWidth = CharWidth; 15047 } else if (Packed && NumNegativeBits <= ShortWidth && 15048 NumPositiveBits < ShortWidth) { 15049 BestType = Context.ShortTy; 15050 BestWidth = ShortWidth; 15051 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15052 BestType = Context.IntTy; 15053 BestWidth = IntWidth; 15054 } else { 15055 BestWidth = Context.getTargetInfo().getLongWidth(); 15056 15057 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15058 BestType = Context.LongTy; 15059 } else { 15060 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15061 15062 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15063 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15064 BestType = Context.LongLongTy; 15065 } 15066 } 15067 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15068 } else { 15069 // If there is no negative value, figure out the smallest type that fits 15070 // all of the enumerator values. 15071 // If it's packed, check also if it fits a char or a short. 15072 if (Packed && NumPositiveBits <= CharWidth) { 15073 BestType = Context.UnsignedCharTy; 15074 BestPromotionType = Context.IntTy; 15075 BestWidth = CharWidth; 15076 } else if (Packed && NumPositiveBits <= ShortWidth) { 15077 BestType = Context.UnsignedShortTy; 15078 BestPromotionType = Context.IntTy; 15079 BestWidth = ShortWidth; 15080 } else if (NumPositiveBits <= IntWidth) { 15081 BestType = Context.UnsignedIntTy; 15082 BestWidth = IntWidth; 15083 BestPromotionType 15084 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15085 ? Context.UnsignedIntTy : Context.IntTy; 15086 } else if (NumPositiveBits <= 15087 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15088 BestType = Context.UnsignedLongTy; 15089 BestPromotionType 15090 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15091 ? Context.UnsignedLongTy : Context.LongTy; 15092 } else { 15093 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15094 assert(NumPositiveBits <= BestWidth && 15095 "How could an initializer get larger than ULL?"); 15096 BestType = Context.UnsignedLongLongTy; 15097 BestPromotionType 15098 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15099 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15100 } 15101 } 15102 15103 // Loop over all of the enumerator constants, changing their types to match 15104 // the type of the enum if needed. 15105 for (auto *D : Elements) { 15106 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15107 if (!ECD) continue; // Already issued a diagnostic. 15108 15109 // Standard C says the enumerators have int type, but we allow, as an 15110 // extension, the enumerators to be larger than int size. If each 15111 // enumerator value fits in an int, type it as an int, otherwise type it the 15112 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15113 // that X has type 'int', not 'unsigned'. 15114 15115 // Determine whether the value fits into an int. 15116 llvm::APSInt InitVal = ECD->getInitVal(); 15117 15118 // If it fits into an integer type, force it. Otherwise force it to match 15119 // the enum decl type. 15120 QualType NewTy; 15121 unsigned NewWidth; 15122 bool NewSign; 15123 if (!getLangOpts().CPlusPlus && 15124 !Enum->isFixed() && 15125 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15126 NewTy = Context.IntTy; 15127 NewWidth = IntWidth; 15128 NewSign = true; 15129 } else if (ECD->getType() == BestType) { 15130 // Already the right type! 15131 if (getLangOpts().CPlusPlus) 15132 // C++ [dcl.enum]p4: Following the closing brace of an 15133 // enum-specifier, each enumerator has the type of its 15134 // enumeration. 15135 ECD->setType(EnumType); 15136 continue; 15137 } else { 15138 NewTy = BestType; 15139 NewWidth = BestWidth; 15140 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15141 } 15142 15143 // Adjust the APSInt value. 15144 InitVal = InitVal.extOrTrunc(NewWidth); 15145 InitVal.setIsSigned(NewSign); 15146 ECD->setInitVal(InitVal); 15147 15148 // Adjust the Expr initializer and type. 15149 if (ECD->getInitExpr() && 15150 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15151 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15152 CK_IntegralCast, 15153 ECD->getInitExpr(), 15154 /*base paths*/ nullptr, 15155 VK_RValue)); 15156 if (getLangOpts().CPlusPlus) 15157 // C++ [dcl.enum]p4: Following the closing brace of an 15158 // enum-specifier, each enumerator has the type of its 15159 // enumeration. 15160 ECD->setType(EnumType); 15161 else 15162 ECD->setType(NewTy); 15163 } 15164 15165 Enum->completeDefinition(BestType, BestPromotionType, 15166 NumPositiveBits, NumNegativeBits); 15167 15168 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15169 15170 if (Enum->hasAttr<FlagEnumAttr>()) { 15171 for (Decl *D : Elements) { 15172 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15173 if (!ECD) continue; // Already issued a diagnostic. 15174 15175 llvm::APSInt InitVal = ECD->getInitVal(); 15176 if (InitVal != 0 && !InitVal.isPowerOf2() && 15177 !IsValueInFlagEnum(Enum, InitVal, true)) 15178 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15179 << ECD << Enum; 15180 } 15181 } 15182 15183 // Now that the enum type is defined, ensure it's not been underaligned. 15184 if (Enum->hasAttrs()) 15185 CheckAlignasUnderalignment(Enum); 15186 } 15187 15188 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15189 SourceLocation StartLoc, 15190 SourceLocation EndLoc) { 15191 StringLiteral *AsmString = cast<StringLiteral>(expr); 15192 15193 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15194 AsmString, StartLoc, 15195 EndLoc); 15196 CurContext->addDecl(New); 15197 return New; 15198 } 15199 15200 static void checkModuleImportContext(Sema &S, Module *M, 15201 SourceLocation ImportLoc, DeclContext *DC, 15202 bool FromInclude = false) { 15203 SourceLocation ExternCLoc; 15204 15205 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15206 switch (LSD->getLanguage()) { 15207 case LinkageSpecDecl::lang_c: 15208 if (ExternCLoc.isInvalid()) 15209 ExternCLoc = LSD->getLocStart(); 15210 break; 15211 case LinkageSpecDecl::lang_cxx: 15212 break; 15213 } 15214 DC = LSD->getParent(); 15215 } 15216 15217 while (isa<LinkageSpecDecl>(DC)) 15218 DC = DC->getParent(); 15219 15220 if (!isa<TranslationUnitDecl>(DC)) { 15221 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15222 ? diag::ext_module_import_not_at_top_level_noop 15223 : diag::err_module_import_not_at_top_level_fatal) 15224 << M->getFullModuleName() << DC; 15225 S.Diag(cast<Decl>(DC)->getLocStart(), 15226 diag::note_module_import_not_at_top_level) << DC; 15227 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15228 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15229 << M->getFullModuleName(); 15230 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 15231 } 15232 } 15233 15234 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 15235 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 15236 } 15237 15238 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15239 ModuleDeclKind MDK, 15240 ModuleIdPath Path) { 15241 // 'module implementation' requires that we are not compiling a module of any 15242 // kind. 'module' and 'module partition' require that we are compiling a 15243 // module inteface (not a module map). 15244 auto CMK = getLangOpts().getCompilingModule(); 15245 if (MDK == ModuleDeclKind::Implementation 15246 ? CMK != LangOptions::CMK_None 15247 : CMK != LangOptions::CMK_ModuleInterface) { 15248 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15249 << (unsigned)MDK; 15250 return nullptr; 15251 } 15252 15253 // FIXME: Create a ModuleDecl and return it. 15254 15255 // FIXME: Most of this work should be done by the preprocessor rather than 15256 // here, in case we look ahead across something where the current 15257 // module matters (eg a #include). 15258 15259 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15260 // hierarchical module map modules, the dots here are just another character 15261 // that can appear in a module name. Flatten down to the actual module name. 15262 std::string ModuleName; 15263 for (auto &Piece : Path) { 15264 if (!ModuleName.empty()) 15265 ModuleName += "."; 15266 ModuleName += Piece.first->getName(); 15267 } 15268 15269 // If a module name was explicitly specified on the command line, it must be 15270 // correct. 15271 if (!getLangOpts().CurrentModule.empty() && 15272 getLangOpts().CurrentModule != ModuleName) { 15273 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15274 << SourceRange(Path.front().second, Path.back().second) 15275 << getLangOpts().CurrentModule; 15276 return nullptr; 15277 } 15278 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15279 15280 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15281 15282 switch (MDK) { 15283 case ModuleDeclKind::Module: { 15284 // FIXME: Check we're not in a submodule. 15285 15286 // We can't have imported a definition of this module or parsed a module 15287 // map defining it already. 15288 if (auto *M = Map.findModule(ModuleName)) { 15289 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15290 if (M->DefinitionLoc.isValid()) 15291 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15292 else if (const auto *FE = M->getASTFile()) 15293 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15294 << FE->getName(); 15295 return nullptr; 15296 } 15297 15298 // Create a Module for the module that we're defining. 15299 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15300 assert(Mod && "module creation should not fail"); 15301 15302 // Enter the semantic scope of the module. 15303 ActOnModuleBegin(ModuleLoc, Mod); 15304 return nullptr; 15305 } 15306 15307 case ModuleDeclKind::Partition: 15308 // FIXME: Check we are in a submodule of the named module. 15309 return nullptr; 15310 15311 case ModuleDeclKind::Implementation: 15312 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15313 PP.getIdentifierInfo(ModuleName), Path[0].second); 15314 15315 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15316 if (Import.isInvalid()) 15317 return nullptr; 15318 return ConvertDeclToDeclGroup(Import.get()); 15319 } 15320 15321 llvm_unreachable("unexpected module decl kind"); 15322 } 15323 15324 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15325 SourceLocation ImportLoc, 15326 ModuleIdPath Path) { 15327 Module *Mod = 15328 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15329 /*IsIncludeDirective=*/false); 15330 if (!Mod) 15331 return true; 15332 15333 VisibleModules.setVisible(Mod, ImportLoc); 15334 15335 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15336 15337 // FIXME: we should support importing a submodule within a different submodule 15338 // of the same top-level module. Until we do, make it an error rather than 15339 // silently ignoring the import. 15340 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15341 // warn on a redundant import of the current module? 15342 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15343 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15344 Diag(ImportLoc, getLangOpts().isCompilingModule() 15345 ? diag::err_module_self_import 15346 : diag::err_module_import_in_implementation) 15347 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15348 15349 SmallVector<SourceLocation, 2> IdentifierLocs; 15350 Module *ModCheck = Mod; 15351 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15352 // If we've run out of module parents, just drop the remaining identifiers. 15353 // We need the length to be consistent. 15354 if (!ModCheck) 15355 break; 15356 ModCheck = ModCheck->Parent; 15357 15358 IdentifierLocs.push_back(Path[I].second); 15359 } 15360 15361 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15362 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15363 Mod, IdentifierLocs); 15364 if (!ModuleScopes.empty()) 15365 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15366 TU->addDecl(Import); 15367 return Import; 15368 } 15369 15370 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15371 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15372 BuildModuleInclude(DirectiveLoc, Mod); 15373 } 15374 15375 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15376 // Determine whether we're in the #include buffer for a module. The #includes 15377 // in that buffer do not qualify as module imports; they're just an 15378 // implementation detail of us building the module. 15379 // 15380 // FIXME: Should we even get ActOnModuleInclude calls for those? 15381 bool IsInModuleIncludes = 15382 TUKind == TU_Module && 15383 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15384 15385 bool ShouldAddImport = !IsInModuleIncludes; 15386 15387 // If this module import was due to an inclusion directive, create an 15388 // implicit import declaration to capture it in the AST. 15389 if (ShouldAddImport) { 15390 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15391 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15392 DirectiveLoc, Mod, 15393 DirectiveLoc); 15394 if (!ModuleScopes.empty()) 15395 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15396 TU->addDecl(ImportD); 15397 Consumer.HandleImplicitImportDecl(ImportD); 15398 } 15399 15400 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15401 VisibleModules.setVisible(Mod, DirectiveLoc); 15402 } 15403 15404 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15405 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15406 15407 ModuleScopes.push_back({}); 15408 ModuleScopes.back().Module = Mod; 15409 if (getLangOpts().ModulesLocalVisibility) 15410 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15411 15412 VisibleModules.setVisible(Mod, DirectiveLoc); 15413 } 15414 15415 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15416 checkModuleImportContext(*this, Mod, EofLoc, CurContext); 15417 15418 if (getLangOpts().ModulesLocalVisibility) { 15419 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15420 // Leaving a module hides namespace names, so our visible namespace cache 15421 // is now out of date. 15422 VisibleNamespaceCache.clear(); 15423 } 15424 15425 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15426 "left the wrong module scope"); 15427 ModuleScopes.pop_back(); 15428 15429 // We got to the end of processing a #include of a local module. Create an 15430 // ImportDecl as we would for an imported module. 15431 FileID File = getSourceManager().getFileID(EofLoc); 15432 assert(File != getSourceManager().getMainFileID() && 15433 "end of submodule in main source file"); 15434 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15435 BuildModuleInclude(DirectiveLoc, Mod); 15436 } 15437 15438 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15439 Module *Mod) { 15440 // Bail if we're not allowed to implicitly import a module here. 15441 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15442 return; 15443 15444 // Create the implicit import declaration. 15445 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15446 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15447 Loc, Mod, Loc); 15448 TU->addDecl(ImportD); 15449 Consumer.HandleImplicitImportDecl(ImportD); 15450 15451 // Make the module visible. 15452 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15453 VisibleModules.setVisible(Mod, Loc); 15454 } 15455 15456 /// We have parsed the start of an export declaration, including the '{' 15457 /// (if present). 15458 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15459 SourceLocation LBraceLoc) { 15460 // FIXME: C++ Modules TS: 15461 // An export-declaration [...] shall not contain more than one 15462 // export keyword. 15463 // 15464 // The intent here is that an export-declaration cannot appear within another 15465 // export-declaration. 15466 15467 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15468 CurContext->addDecl(D); 15469 PushDeclContext(S, D); 15470 return D; 15471 } 15472 15473 /// Complete the definition of an export declaration. 15474 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15475 auto *ED = cast<ExportDecl>(D); 15476 if (RBraceLoc.isValid()) 15477 ED->setRBraceLoc(RBraceLoc); 15478 15479 // FIXME: Diagnose export of internal-linkage declaration (including 15480 // anonymous namespace). 15481 15482 PopDeclContext(); 15483 return D; 15484 } 15485 15486 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15487 IdentifierInfo* AliasName, 15488 SourceLocation PragmaLoc, 15489 SourceLocation NameLoc, 15490 SourceLocation AliasNameLoc) { 15491 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15492 LookupOrdinaryName); 15493 AsmLabelAttr *Attr = 15494 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15495 15496 // If a declaration that: 15497 // 1) declares a function or a variable 15498 // 2) has external linkage 15499 // already exists, add a label attribute to it. 15500 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15501 if (isDeclExternC(PrevDecl)) 15502 PrevDecl->addAttr(Attr); 15503 else 15504 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15505 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15506 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15507 } else 15508 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15509 } 15510 15511 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15512 SourceLocation PragmaLoc, 15513 SourceLocation NameLoc) { 15514 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15515 15516 if (PrevDecl) { 15517 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15518 } else { 15519 (void)WeakUndeclaredIdentifiers.insert( 15520 std::pair<IdentifierInfo*,WeakInfo> 15521 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15522 } 15523 } 15524 15525 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15526 IdentifierInfo* AliasName, 15527 SourceLocation PragmaLoc, 15528 SourceLocation NameLoc, 15529 SourceLocation AliasNameLoc) { 15530 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15531 LookupOrdinaryName); 15532 WeakInfo W = WeakInfo(Name, NameLoc); 15533 15534 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15535 if (!PrevDecl->hasAttr<AliasAttr>()) 15536 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15537 DeclApplyPragmaWeak(TUScope, ND, W); 15538 } else { 15539 (void)WeakUndeclaredIdentifiers.insert( 15540 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15541 } 15542 } 15543 15544 Decl *Sema::getObjCDeclContext() const { 15545 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15546 } 15547 15548 AvailabilityResult Sema::getCurContextAvailability() const { 15549 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 15550 if (!D) 15551 return AR_Available; 15552 15553 // If we are within an Objective-C method, we should consult 15554 // both the availability of the method as well as the 15555 // enclosing class. If the class is (say) deprecated, 15556 // the entire method is considered deprecated from the 15557 // purpose of checking if the current context is deprecated. 15558 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 15559 AvailabilityResult R = MD->getAvailability(); 15560 if (R != AR_Available) 15561 return R; 15562 D = MD->getClassInterface(); 15563 } 15564 // If we are within an Objective-c @implementation, it 15565 // gets the same availability context as the @interface. 15566 else if (const ObjCImplementationDecl *ID = 15567 dyn_cast<ObjCImplementationDecl>(D)) { 15568 D = ID->getClassInterface(); 15569 } 15570 // Recover from user error. 15571 return D ? D->getAvailability() : AR_Available; 15572 } 15573