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 AllowTemplates(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 = AllowTemplates && getAsTypeTemplateDecl(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 AllowTemplates; 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 bool IsClassTemplateDeductionContext, 256 IdentifierInfo **CorrectedII) { 257 // FIXME: Consider allowing this outside C++1z mode as an extension. 258 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 259 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 260 !isClassName && !HasTrailingDot; 261 262 // Determine where we will perform name lookup. 263 DeclContext *LookupCtx = nullptr; 264 if (ObjectTypePtr) { 265 QualType ObjectType = ObjectTypePtr.get(); 266 if (ObjectType->isRecordType()) 267 LookupCtx = computeDeclContext(ObjectType); 268 } else if (SS && SS->isNotEmpty()) { 269 LookupCtx = computeDeclContext(*SS, false); 270 271 if (!LookupCtx) { 272 if (isDependentScopeSpecifier(*SS)) { 273 // C++ [temp.res]p3: 274 // A qualified-id that refers to a type and in which the 275 // nested-name-specifier depends on a template-parameter (14.6.2) 276 // shall be prefixed by the keyword typename to indicate that the 277 // qualified-id denotes a type, forming an 278 // elaborated-type-specifier (7.1.5.3). 279 // 280 // We therefore do not perform any name lookup if the result would 281 // refer to a member of an unknown specialization. 282 if (!isClassName && !IsCtorOrDtorName) 283 return nullptr; 284 285 // We know from the grammar that this name refers to a type, 286 // so build a dependent node to describe the type. 287 if (WantNontrivialTypeSourceInfo) 288 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 289 290 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 291 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 292 II, NameLoc); 293 return ParsedType::make(T); 294 } 295 296 return nullptr; 297 } 298 299 if (!LookupCtx->isDependentContext() && 300 RequireCompleteDeclContext(*SS, LookupCtx)) 301 return nullptr; 302 } 303 304 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 305 // lookup for class-names. 306 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 307 LookupOrdinaryName; 308 LookupResult Result(*this, &II, NameLoc, Kind); 309 if (LookupCtx) { 310 // Perform "qualified" name lookup into the declaration context we 311 // computed, which is either the type of the base of a member access 312 // expression or the declaration context associated with a prior 313 // nested-name-specifier. 314 LookupQualifiedName(Result, LookupCtx); 315 316 if (ObjectTypePtr && Result.empty()) { 317 // C++ [basic.lookup.classref]p3: 318 // If the unqualified-id is ~type-name, the type-name is looked up 319 // in the context of the entire postfix-expression. If the type T of 320 // the object expression is of a class type C, the type-name is also 321 // looked up in the scope of class C. At least one of the lookups shall 322 // find a name that refers to (possibly cv-qualified) T. 323 LookupName(Result, S); 324 } 325 } else { 326 // Perform unqualified name lookup. 327 LookupName(Result, S); 328 329 // For unqualified lookup in a class template in MSVC mode, look into 330 // dependent base classes where the primary class template is known. 331 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 332 if (ParsedType TypeInBase = 333 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 334 return TypeInBase; 335 } 336 } 337 338 NamedDecl *IIDecl = nullptr; 339 switch (Result.getResultKind()) { 340 case LookupResult::NotFound: 341 case LookupResult::NotFoundInCurrentInstantiation: 342 if (CorrectedII) { 343 TypoCorrection Correction = 344 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 345 llvm::make_unique<TypeNameValidatorCCC>( 346 true, isClassName, AllowDeducedTemplate), 347 CTK_ErrorRecovery); 348 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 349 TemplateTy Template; 350 bool MemberOfUnknownSpecialization; 351 UnqualifiedId TemplateName; 352 TemplateName.setIdentifier(NewII, NameLoc); 353 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 354 CXXScopeSpec NewSS, *NewSSPtr = SS; 355 if (SS && NNS) { 356 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 357 NewSSPtr = &NewSS; 358 } 359 if (Correction && (NNS || NewII != &II) && 360 // Ignore a correction to a template type as the to-be-corrected 361 // identifier is not a template (typo correction for template names 362 // is handled elsewhere). 363 !(getLangOpts().CPlusPlus && NewSSPtr && 364 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 365 Template, MemberOfUnknownSpecialization))) { 366 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 367 isClassName, HasTrailingDot, ObjectTypePtr, 368 IsCtorOrDtorName, 369 WantNontrivialTypeSourceInfo, 370 IsClassTemplateDeductionContext); 371 if (Ty) { 372 diagnoseTypo(Correction, 373 PDiag(diag::err_unknown_type_or_class_name_suggest) 374 << Result.getLookupName() << isClassName); 375 if (SS && NNS) 376 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 377 *CorrectedII = NewII; 378 return Ty; 379 } 380 } 381 } 382 // If typo correction failed or was not performed, fall through 383 case LookupResult::FoundOverloaded: 384 case LookupResult::FoundUnresolvedValue: 385 Result.suppressDiagnostics(); 386 return nullptr; 387 388 case LookupResult::Ambiguous: 389 // Recover from type-hiding ambiguities by hiding the type. We'll 390 // do the lookup again when looking for an object, and we can 391 // diagnose the error then. If we don't do this, then the error 392 // about hiding the type will be immediately followed by an error 393 // that only makes sense if the identifier was treated like a type. 394 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 395 Result.suppressDiagnostics(); 396 return nullptr; 397 } 398 399 // Look to see if we have a type anywhere in the list of results. 400 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 401 Res != ResEnd; ++Res) { 402 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 403 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 404 if (!IIDecl || 405 (*Res)->getLocation().getRawEncoding() < 406 IIDecl->getLocation().getRawEncoding()) 407 IIDecl = *Res; 408 } 409 } 410 411 if (!IIDecl) { 412 // None of the entities we found is a type, so there is no way 413 // to even assume that the result is a type. In this case, don't 414 // complain about the ambiguity. The parser will either try to 415 // perform this lookup again (e.g., as an object name), which 416 // will produce the ambiguity, or will complain that it expected 417 // a type name. 418 Result.suppressDiagnostics(); 419 return nullptr; 420 } 421 422 // We found a type within the ambiguous lookup; diagnose the 423 // ambiguity and then return that type. This might be the right 424 // answer, or it might not be, but it suppresses any attempt to 425 // perform the name lookup again. 426 break; 427 428 case LookupResult::Found: 429 IIDecl = Result.getFoundDecl(); 430 break; 431 } 432 433 assert(IIDecl && "Didn't find decl"); 434 435 QualType T; 436 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 437 // C++ [class.qual]p2: A lookup that would find the injected-class-name 438 // instead names the constructors of the class, except when naming a class. 439 // This is ill-formed when we're not actually forming a ctor or dtor name. 440 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 441 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 442 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 443 FoundRD->isInjectedClassName() && 444 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 445 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 446 << &II << /*Type*/1; 447 448 DiagnoseUseOfDecl(IIDecl, NameLoc); 449 450 T = Context.getTypeDeclType(TD); 451 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 452 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 453 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 454 if (!HasTrailingDot) 455 T = Context.getObjCInterfaceType(IDecl); 456 } else if (AllowDeducedTemplate) { 457 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 458 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 459 QualType(), false); 460 } 461 462 if (T.isNull()) { 463 // If it's not plausibly a type, suppress diagnostics. 464 Result.suppressDiagnostics(); 465 return nullptr; 466 } 467 468 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 469 // constructor or destructor name (in such a case, the scope specifier 470 // will be attached to the enclosing Expr or Decl node). 471 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 472 !isa<ObjCInterfaceDecl>(IIDecl)) { 473 if (WantNontrivialTypeSourceInfo) { 474 // Construct a type with type-source information. 475 TypeLocBuilder Builder; 476 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 477 478 T = getElaboratedType(ETK_None, *SS, T); 479 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 480 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 481 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 482 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 483 } else { 484 T = getElaboratedType(ETK_None, *SS, T); 485 } 486 } 487 488 return ParsedType::make(T); 489 } 490 491 // Builds a fake NNS for the given decl context. 492 static NestedNameSpecifier * 493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 494 for (;; DC = DC->getLookupParent()) { 495 DC = DC->getPrimaryContext(); 496 auto *ND = dyn_cast<NamespaceDecl>(DC); 497 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 498 return NestedNameSpecifier::Create(Context, nullptr, ND); 499 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 500 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 501 RD->getTypeForDecl()); 502 else if (isa<TranslationUnitDecl>(DC)) 503 return NestedNameSpecifier::GlobalSpecifier(Context); 504 } 505 llvm_unreachable("something isn't in TU scope?"); 506 } 507 508 /// Find the parent class with dependent bases of the innermost enclosing method 509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 510 /// up allowing unqualified dependent type names at class-level, which MSVC 511 /// correctly rejects. 512 static const CXXRecordDecl * 513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 514 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 515 DC = DC->getPrimaryContext(); 516 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 517 if (MD->getParent()->hasAnyDependentBases()) 518 return MD->getParent(); 519 } 520 return nullptr; 521 } 522 523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 524 SourceLocation NameLoc, 525 bool IsTemplateTypeArg) { 526 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 527 528 NestedNameSpecifier *NNS = nullptr; 529 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 530 // If we weren't able to parse a default template argument, delay lookup 531 // until instantiation time by making a non-dependent DependentTypeName. We 532 // pretend we saw a NestedNameSpecifier referring to the current scope, and 533 // lookup is retried. 534 // FIXME: This hurts our diagnostic quality, since we get errors like "no 535 // type named 'Foo' in 'current_namespace'" when the user didn't write any 536 // name specifiers. 537 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 538 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 539 } else if (const CXXRecordDecl *RD = 540 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 541 // Build a DependentNameType that will perform lookup into RD at 542 // instantiation time. 543 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 544 RD->getTypeForDecl()); 545 546 // Diagnose that this identifier was undeclared, and retry the lookup during 547 // template instantiation. 548 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 549 << RD; 550 } else { 551 // This is not a situation that we should recover from. 552 return ParsedType(); 553 } 554 555 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 556 557 // Build type location information. We synthesized the qualifier, so we have 558 // to build a fake NestedNameSpecifierLoc. 559 NestedNameSpecifierLocBuilder NNSLocBuilder; 560 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 561 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 562 563 TypeLocBuilder Builder; 564 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 565 DepTL.setNameLoc(NameLoc); 566 DepTL.setElaboratedKeywordLoc(SourceLocation()); 567 DepTL.setQualifierLoc(QualifierLoc); 568 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 569 } 570 571 /// isTagName() - This method is called *for error recovery purposes only* 572 /// to determine if the specified name is a valid tag name ("struct foo"). If 573 /// so, this returns the TST for the tag corresponding to it (TST_enum, 574 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 575 /// cases in C where the user forgot to specify the tag. 576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 577 // Do a tag name lookup in this scope. 578 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 579 LookupName(R, S, false); 580 R.suppressDiagnostics(); 581 if (R.getResultKind() == LookupResult::Found) 582 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 583 switch (TD->getTagKind()) { 584 case TTK_Struct: return DeclSpec::TST_struct; 585 case TTK_Interface: return DeclSpec::TST_interface; 586 case TTK_Union: return DeclSpec::TST_union; 587 case TTK_Class: return DeclSpec::TST_class; 588 case TTK_Enum: return DeclSpec::TST_enum; 589 } 590 } 591 592 return DeclSpec::TST_unspecified; 593 } 594 595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 597 /// then downgrade the missing typename error to a warning. 598 /// This is needed for MSVC compatibility; Example: 599 /// @code 600 /// template<class T> class A { 601 /// public: 602 /// typedef int TYPE; 603 /// }; 604 /// template<class T> class B : public A<T> { 605 /// public: 606 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 607 /// }; 608 /// @endcode 609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 610 if (CurContext->isRecord()) { 611 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 612 return true; 613 614 const Type *Ty = SS->getScopeRep()->getAsType(); 615 616 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 617 for (const auto &Base : RD->bases()) 618 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 619 return true; 620 return S->isFunctionPrototypeScope(); 621 } 622 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 623 } 624 625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 626 SourceLocation IILoc, 627 Scope *S, 628 CXXScopeSpec *SS, 629 ParsedType &SuggestedType, 630 bool AllowClassTemplates) { 631 // We don't have anything to suggest (yet). 632 SuggestedType = nullptr; 633 634 // There may have been a typo in the name of the type. Look up typo 635 // results, in case we have something that we can suggest. 636 if (TypoCorrection Corrected = 637 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 638 llvm::make_unique<TypeNameValidatorCCC>( 639 false, false, AllowClassTemplates), 640 CTK_ErrorRecovery)) { 641 if (Corrected.isKeyword()) { 642 // We corrected to a keyword. 643 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 644 II = Corrected.getCorrectionAsIdentifierInfo(); 645 } else { 646 // We found a similarly-named type or interface; suggest that. 647 if (!SS || !SS->isSet()) { 648 diagnoseTypo(Corrected, 649 PDiag(diag::err_unknown_typename_suggest) << II); 650 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 651 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 652 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 653 II->getName().equals(CorrectedStr); 654 diagnoseTypo(Corrected, 655 PDiag(diag::err_unknown_nested_typename_suggest) 656 << II << DC << DroppedSpecifier << SS->getRange()); 657 } else { 658 llvm_unreachable("could not have corrected a typo here"); 659 } 660 661 CXXScopeSpec tmpSS; 662 if (Corrected.getCorrectionSpecifier()) 663 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 664 SourceRange(IILoc)); 665 // FIXME: Support class template argument deduction here. 666 SuggestedType = 667 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 668 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 669 /*IsCtorOrDtorName=*/false, 670 /*NonTrivialTypeSourceInfo=*/true); 671 } 672 return; 673 } 674 675 if (getLangOpts().CPlusPlus) { 676 // See if II is a class template that the user forgot to pass arguments to. 677 UnqualifiedId Name; 678 Name.setIdentifier(II, IILoc); 679 CXXScopeSpec EmptySS; 680 TemplateTy TemplateResult; 681 bool MemberOfUnknownSpecialization; 682 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 683 Name, nullptr, true, TemplateResult, 684 MemberOfUnknownSpecialization) == TNK_Type_template) { 685 TemplateName TplName = TemplateResult.get(); 686 Diag(IILoc, diag::err_template_missing_args) 687 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 688 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 689 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 690 << TplDecl->getTemplateParameters()->getSourceRange(); 691 } 692 return; 693 } 694 } 695 696 // FIXME: Should we move the logic that tries to recover from a missing tag 697 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 698 699 if (!SS || (!SS->isSet() && !SS->isInvalid())) 700 Diag(IILoc, diag::err_unknown_typename) << II; 701 else if (DeclContext *DC = computeDeclContext(*SS, false)) 702 Diag(IILoc, diag::err_typename_nested_not_found) 703 << II << DC << SS->getRange(); 704 else if (isDependentScopeSpecifier(*SS)) { 705 unsigned DiagID = diag::err_typename_missing; 706 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 707 DiagID = diag::ext_typename_missing; 708 709 Diag(SS->getRange().getBegin(), DiagID) 710 << SS->getScopeRep() << II->getName() 711 << SourceRange(SS->getRange().getBegin(), IILoc) 712 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 713 SuggestedType = ActOnTypenameType(S, SourceLocation(), 714 *SS, *II, IILoc).get(); 715 } else { 716 assert(SS && SS->isInvalid() && 717 "Invalid scope specifier has already been diagnosed"); 718 } 719 } 720 721 /// \brief Determine whether the given result set contains either a type name 722 /// or 723 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 724 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 725 NextToken.is(tok::less); 726 727 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 728 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 729 return true; 730 731 if (CheckTemplate && isa<TemplateDecl>(*I)) 732 return true; 733 } 734 735 return false; 736 } 737 738 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 739 Scope *S, CXXScopeSpec &SS, 740 IdentifierInfo *&Name, 741 SourceLocation NameLoc) { 742 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 743 SemaRef.LookupParsedName(R, S, &SS); 744 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 745 StringRef FixItTagName; 746 switch (Tag->getTagKind()) { 747 case TTK_Class: 748 FixItTagName = "class "; 749 break; 750 751 case TTK_Enum: 752 FixItTagName = "enum "; 753 break; 754 755 case TTK_Struct: 756 FixItTagName = "struct "; 757 break; 758 759 case TTK_Interface: 760 FixItTagName = "__interface "; 761 break; 762 763 case TTK_Union: 764 FixItTagName = "union "; 765 break; 766 } 767 768 StringRef TagName = FixItTagName.drop_back(); 769 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 770 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 771 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 772 773 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 774 I != IEnd; ++I) 775 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 776 << Name << TagName; 777 778 // Replace lookup results with just the tag decl. 779 Result.clear(Sema::LookupTagName); 780 SemaRef.LookupParsedName(Result, S, &SS); 781 return true; 782 } 783 784 return false; 785 } 786 787 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 788 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 789 QualType T, SourceLocation NameLoc) { 790 ASTContext &Context = S.Context; 791 792 TypeLocBuilder Builder; 793 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 794 795 T = S.getElaboratedType(ETK_None, SS, T); 796 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 797 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 798 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 799 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 800 } 801 802 Sema::NameClassification 803 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 804 SourceLocation NameLoc, const Token &NextToken, 805 bool IsAddressOfOperand, 806 std::unique_ptr<CorrectionCandidateCallback> CCC) { 807 DeclarationNameInfo NameInfo(Name, NameLoc); 808 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 809 810 if (NextToken.is(tok::coloncolon)) { 811 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 812 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 813 } else if (getLangOpts().CPlusPlus && SS.isSet() && 814 isCurrentClassName(*Name, S, &SS)) { 815 // Per [class.qual]p2, this names the constructors of SS, not the 816 // injected-class-name. We don't have a classification for that. 817 // There's not much point caching this result, since the parser 818 // will reject it later. 819 return NameClassification::Unknown(); 820 } 821 822 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 823 LookupParsedName(Result, S, &SS, !CurMethod); 824 825 // For unqualified lookup in a class template in MSVC mode, look into 826 // dependent base classes where the primary class template is known. 827 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 828 if (ParsedType TypeInBase = 829 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 830 return TypeInBase; 831 } 832 833 // Perform lookup for Objective-C instance variables (including automatically 834 // synthesized instance variables), if we're in an Objective-C method. 835 // FIXME: This lookup really, really needs to be folded in to the normal 836 // unqualified lookup mechanism. 837 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 838 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 839 if (E.get() || E.isInvalid()) 840 return E; 841 } 842 843 bool SecondTry = false; 844 bool IsFilteredTemplateName = false; 845 846 Corrected: 847 switch (Result.getResultKind()) { 848 case LookupResult::NotFound: 849 // If an unqualified-id is followed by a '(', then we have a function 850 // call. 851 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 852 // In C++, this is an ADL-only call. 853 // FIXME: Reference? 854 if (getLangOpts().CPlusPlus) 855 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 856 857 // C90 6.3.2.2: 858 // If the expression that precedes the parenthesized argument list in a 859 // function call consists solely of an identifier, and if no 860 // declaration is visible for this identifier, the identifier is 861 // implicitly declared exactly as if, in the innermost block containing 862 // the function call, the declaration 863 // 864 // extern int identifier (); 865 // 866 // appeared. 867 // 868 // We also allow this in C99 as an extension. 869 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 870 Result.addDecl(D); 871 Result.resolveKind(); 872 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 873 } 874 } 875 876 // In C, we first see whether there is a tag type by the same name, in 877 // which case it's likely that the user just forgot to write "enum", 878 // "struct", or "union". 879 if (!getLangOpts().CPlusPlus && !SecondTry && 880 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 881 break; 882 } 883 884 // Perform typo correction to determine if there is another name that is 885 // close to this name. 886 if (!SecondTry && CCC) { 887 SecondTry = true; 888 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 889 Result.getLookupKind(), S, 890 &SS, std::move(CCC), 891 CTK_ErrorRecovery)) { 892 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 893 unsigned QualifiedDiag = diag::err_no_member_suggest; 894 895 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 896 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 897 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 898 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 899 UnqualifiedDiag = diag::err_no_template_suggest; 900 QualifiedDiag = diag::err_no_member_template_suggest; 901 } else if (UnderlyingFirstDecl && 902 (isa<TypeDecl>(UnderlyingFirstDecl) || 903 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 904 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 905 UnqualifiedDiag = diag::err_unknown_typename_suggest; 906 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 907 } 908 909 if (SS.isEmpty()) { 910 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 911 } else {// FIXME: is this even reachable? Test it. 912 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 913 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 914 Name->getName().equals(CorrectedStr); 915 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 916 << Name << computeDeclContext(SS, false) 917 << DroppedSpecifier << SS.getRange()); 918 } 919 920 // Update the name, so that the caller has the new name. 921 Name = Corrected.getCorrectionAsIdentifierInfo(); 922 923 // Typo correction corrected to a keyword. 924 if (Corrected.isKeyword()) 925 return Name; 926 927 // Also update the LookupResult... 928 // FIXME: This should probably go away at some point 929 Result.clear(); 930 Result.setLookupName(Corrected.getCorrection()); 931 if (FirstDecl) 932 Result.addDecl(FirstDecl); 933 934 // If we found an Objective-C instance variable, let 935 // LookupInObjCMethod build the appropriate expression to 936 // reference the ivar. 937 // FIXME: This is a gross hack. 938 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 939 Result.clear(); 940 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 941 return E; 942 } 943 944 goto Corrected; 945 } 946 } 947 948 // We failed to correct; just fall through and let the parser deal with it. 949 Result.suppressDiagnostics(); 950 return NameClassification::Unknown(); 951 952 case LookupResult::NotFoundInCurrentInstantiation: { 953 // We performed name lookup into the current instantiation, and there were 954 // dependent bases, so we treat this result the same way as any other 955 // dependent nested-name-specifier. 956 957 // C++ [temp.res]p2: 958 // A name used in a template declaration or definition and that is 959 // dependent on a template-parameter is assumed not to name a type 960 // unless the applicable name lookup finds a type name or the name is 961 // qualified by the keyword typename. 962 // 963 // FIXME: If the next token is '<', we might want to ask the parser to 964 // perform some heroics to see if we actually have a 965 // template-argument-list, which would indicate a missing 'template' 966 // keyword here. 967 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 968 NameInfo, IsAddressOfOperand, 969 /*TemplateArgs=*/nullptr); 970 } 971 972 case LookupResult::Found: 973 case LookupResult::FoundOverloaded: 974 case LookupResult::FoundUnresolvedValue: 975 break; 976 977 case LookupResult::Ambiguous: 978 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 979 hasAnyAcceptableTemplateNames(Result)) { 980 // C++ [temp.local]p3: 981 // A lookup that finds an injected-class-name (10.2) can result in an 982 // ambiguity in certain cases (for example, if it is found in more than 983 // one base class). If all of the injected-class-names that are found 984 // refer to specializations of the same class template, and if the name 985 // is followed by a template-argument-list, the reference refers to the 986 // class template itself and not a specialization thereof, and is not 987 // ambiguous. 988 // 989 // This filtering can make an ambiguous result into an unambiguous one, 990 // so try again after filtering out template names. 991 FilterAcceptableTemplateNames(Result); 992 if (!Result.isAmbiguous()) { 993 IsFilteredTemplateName = true; 994 break; 995 } 996 } 997 998 // Diagnose the ambiguity and return an error. 999 return NameClassification::Error(); 1000 } 1001 1002 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1003 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1004 // C++ [temp.names]p3: 1005 // After name lookup (3.4) finds that a name is a template-name or that 1006 // an operator-function-id or a literal- operator-id refers to a set of 1007 // overloaded functions any member of which is a function template if 1008 // this is followed by a <, the < is always taken as the delimiter of a 1009 // template-argument-list and never as the less-than operator. 1010 if (!IsFilteredTemplateName) 1011 FilterAcceptableTemplateNames(Result); 1012 1013 if (!Result.empty()) { 1014 bool IsFunctionTemplate; 1015 bool IsVarTemplate; 1016 TemplateName Template; 1017 if (Result.end() - Result.begin() > 1) { 1018 IsFunctionTemplate = true; 1019 Template = Context.getOverloadedTemplateName(Result.begin(), 1020 Result.end()); 1021 } else { 1022 TemplateDecl *TD 1023 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1024 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1025 IsVarTemplate = isa<VarTemplateDecl>(TD); 1026 1027 if (SS.isSet() && !SS.isInvalid()) 1028 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1029 /*TemplateKeyword=*/false, 1030 TD); 1031 else 1032 Template = TemplateName(TD); 1033 } 1034 1035 if (IsFunctionTemplate) { 1036 // Function templates always go through overload resolution, at which 1037 // point we'll perform the various checks (e.g., accessibility) we need 1038 // to based on which function we selected. 1039 Result.suppressDiagnostics(); 1040 1041 return NameClassification::FunctionTemplate(Template); 1042 } 1043 1044 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1045 : NameClassification::TypeTemplate(Template); 1046 } 1047 } 1048 1049 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1050 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1051 DiagnoseUseOfDecl(Type, NameLoc); 1052 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1053 QualType T = Context.getTypeDeclType(Type); 1054 if (SS.isNotEmpty()) 1055 return buildNestedType(*this, SS, T, NameLoc); 1056 return ParsedType::make(T); 1057 } 1058 1059 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1060 if (!Class) { 1061 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1062 if (ObjCCompatibleAliasDecl *Alias = 1063 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1064 Class = Alias->getClassInterface(); 1065 } 1066 1067 if (Class) { 1068 DiagnoseUseOfDecl(Class, NameLoc); 1069 1070 if (NextToken.is(tok::period)) { 1071 // Interface. <something> is parsed as a property reference expression. 1072 // Just return "unknown" as a fall-through for now. 1073 Result.suppressDiagnostics(); 1074 return NameClassification::Unknown(); 1075 } 1076 1077 QualType T = Context.getObjCInterfaceType(Class); 1078 return ParsedType::make(T); 1079 } 1080 1081 // We can have a type template here if we're classifying a template argument. 1082 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1083 !isa<VarTemplateDecl>(FirstDecl)) 1084 return NameClassification::TypeTemplate( 1085 TemplateName(cast<TemplateDecl>(FirstDecl))); 1086 1087 // Check for a tag type hidden by a non-type decl in a few cases where it 1088 // seems likely a type is wanted instead of the non-type that was found. 1089 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1090 if ((NextToken.is(tok::identifier) || 1091 (NextIsOp && 1092 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1093 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1094 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1095 DiagnoseUseOfDecl(Type, NameLoc); 1096 QualType T = Context.getTypeDeclType(Type); 1097 if (SS.isNotEmpty()) 1098 return buildNestedType(*this, SS, T, NameLoc); 1099 return ParsedType::make(T); 1100 } 1101 1102 if (FirstDecl->isCXXClassMember()) 1103 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1104 nullptr, S); 1105 1106 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1107 return BuildDeclarationNameExpr(SS, Result, ADL); 1108 } 1109 1110 Sema::TemplateNameKindForDiagnostics 1111 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1112 auto *TD = Name.getAsTemplateDecl(); 1113 if (!TD) 1114 return TemplateNameKindForDiagnostics::DependentTemplate; 1115 if (isa<ClassTemplateDecl>(TD)) 1116 return TemplateNameKindForDiagnostics::ClassTemplate; 1117 if (isa<FunctionTemplateDecl>(TD)) 1118 return TemplateNameKindForDiagnostics::FunctionTemplate; 1119 if (isa<VarTemplateDecl>(TD)) 1120 return TemplateNameKindForDiagnostics::VarTemplate; 1121 if (isa<TypeAliasTemplateDecl>(TD)) 1122 return TemplateNameKindForDiagnostics::AliasTemplate; 1123 if (isa<TemplateTemplateParmDecl>(TD)) 1124 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1125 return TemplateNameKindForDiagnostics::DependentTemplate; 1126 } 1127 1128 // Determines the context to return to after temporarily entering a 1129 // context. This depends in an unnecessarily complicated way on the 1130 // exact ordering of callbacks from the parser. 1131 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1132 1133 // Functions defined inline within classes aren't parsed until we've 1134 // finished parsing the top-level class, so the top-level class is 1135 // the context we'll need to return to. 1136 // A Lambda call operator whose parent is a class must not be treated 1137 // as an inline member function. A Lambda can be used legally 1138 // either as an in-class member initializer or a default argument. These 1139 // are parsed once the class has been marked complete and so the containing 1140 // context would be the nested class (when the lambda is defined in one); 1141 // If the class is not complete, then the lambda is being used in an 1142 // ill-formed fashion (such as to specify the width of a bit-field, or 1143 // in an array-bound) - in which case we still want to return the 1144 // lexically containing DC (which could be a nested class). 1145 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1146 DC = DC->getLexicalParent(); 1147 1148 // A function not defined within a class will always return to its 1149 // lexical context. 1150 if (!isa<CXXRecordDecl>(DC)) 1151 return DC; 1152 1153 // A C++ inline method/friend is parsed *after* the topmost class 1154 // it was declared in is fully parsed ("complete"); the topmost 1155 // class is the context we need to return to. 1156 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1157 DC = RD; 1158 1159 // Return the declaration context of the topmost class the inline method is 1160 // declared in. 1161 return DC; 1162 } 1163 1164 return DC->getLexicalParent(); 1165 } 1166 1167 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1168 assert(getContainingDC(DC) == CurContext && 1169 "The next DeclContext should be lexically contained in the current one."); 1170 CurContext = DC; 1171 S->setEntity(DC); 1172 } 1173 1174 void Sema::PopDeclContext() { 1175 assert(CurContext && "DeclContext imbalance!"); 1176 1177 CurContext = getContainingDC(CurContext); 1178 assert(CurContext && "Popped translation unit!"); 1179 } 1180 1181 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1182 Decl *D) { 1183 // Unlike PushDeclContext, the context to which we return is not necessarily 1184 // the containing DC of TD, because the new context will be some pre-existing 1185 // TagDecl definition instead of a fresh one. 1186 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1187 CurContext = cast<TagDecl>(D)->getDefinition(); 1188 assert(CurContext && "skipping definition of undefined tag"); 1189 // Start lookups from the parent of the current context; we don't want to look 1190 // into the pre-existing complete definition. 1191 S->setEntity(CurContext->getLookupParent()); 1192 return Result; 1193 } 1194 1195 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1196 CurContext = static_cast<decltype(CurContext)>(Context); 1197 } 1198 1199 /// EnterDeclaratorContext - Used when we must lookup names in the context 1200 /// of a declarator's nested name specifier. 1201 /// 1202 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1203 // C++0x [basic.lookup.unqual]p13: 1204 // A name used in the definition of a static data member of class 1205 // X (after the qualified-id of the static member) is looked up as 1206 // if the name was used in a member function of X. 1207 // C++0x [basic.lookup.unqual]p14: 1208 // If a variable member of a namespace is defined outside of the 1209 // scope of its namespace then any name used in the definition of 1210 // the variable member (after the declarator-id) is looked up as 1211 // if the definition of the variable member occurred in its 1212 // namespace. 1213 // Both of these imply that we should push a scope whose context 1214 // is the semantic context of the declaration. We can't use 1215 // PushDeclContext here because that context is not necessarily 1216 // lexically contained in the current context. Fortunately, 1217 // the containing scope should have the appropriate information. 1218 1219 assert(!S->getEntity() && "scope already has entity"); 1220 1221 #ifndef NDEBUG 1222 Scope *Ancestor = S->getParent(); 1223 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1224 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1225 #endif 1226 1227 CurContext = DC; 1228 S->setEntity(DC); 1229 } 1230 1231 void Sema::ExitDeclaratorContext(Scope *S) { 1232 assert(S->getEntity() == CurContext && "Context imbalance!"); 1233 1234 // Switch back to the lexical context. The safety of this is 1235 // enforced by an assert in EnterDeclaratorContext. 1236 Scope *Ancestor = S->getParent(); 1237 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1238 CurContext = Ancestor->getEntity(); 1239 1240 // We don't need to do anything with the scope, which is going to 1241 // disappear. 1242 } 1243 1244 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1245 // We assume that the caller has already called 1246 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1247 FunctionDecl *FD = D->getAsFunction(); 1248 if (!FD) 1249 return; 1250 1251 // Same implementation as PushDeclContext, but enters the context 1252 // from the lexical parent, rather than the top-level class. 1253 assert(CurContext == FD->getLexicalParent() && 1254 "The next DeclContext should be lexically contained in the current one."); 1255 CurContext = FD; 1256 S->setEntity(CurContext); 1257 1258 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1259 ParmVarDecl *Param = FD->getParamDecl(P); 1260 // If the parameter has an identifier, then add it to the scope 1261 if (Param->getIdentifier()) { 1262 S->AddDecl(Param); 1263 IdResolver.AddDecl(Param); 1264 } 1265 } 1266 } 1267 1268 void Sema::ActOnExitFunctionContext() { 1269 // Same implementation as PopDeclContext, but returns to the lexical parent, 1270 // rather than the top-level class. 1271 assert(CurContext && "DeclContext imbalance!"); 1272 CurContext = CurContext->getLexicalParent(); 1273 assert(CurContext && "Popped translation unit!"); 1274 } 1275 1276 /// \brief Determine whether we allow overloading of the function 1277 /// PrevDecl with another declaration. 1278 /// 1279 /// This routine determines whether overloading is possible, not 1280 /// whether some new function is actually an overload. It will return 1281 /// true in C++ (where we can always provide overloads) or, as an 1282 /// extension, in C when the previous function is already an 1283 /// overloaded function declaration or has the "overloadable" 1284 /// attribute. 1285 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1286 ASTContext &Context) { 1287 if (Context.getLangOpts().CPlusPlus) 1288 return true; 1289 1290 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1291 return true; 1292 1293 return (Previous.getResultKind() == LookupResult::Found 1294 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1295 } 1296 1297 /// Add this decl to the scope shadowed decl chains. 1298 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1299 // Move up the scope chain until we find the nearest enclosing 1300 // non-transparent context. The declaration will be introduced into this 1301 // scope. 1302 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1303 S = S->getParent(); 1304 1305 // Add scoped declarations into their context, so that they can be 1306 // found later. Declarations without a context won't be inserted 1307 // into any context. 1308 if (AddToContext) 1309 CurContext->addDecl(D); 1310 1311 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1312 // are function-local declarations. 1313 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1314 !D->getDeclContext()->getRedeclContext()->Equals( 1315 D->getLexicalDeclContext()->getRedeclContext()) && 1316 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1317 return; 1318 1319 // Template instantiations should also not be pushed into scope. 1320 if (isa<FunctionDecl>(D) && 1321 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1322 return; 1323 1324 // If this replaces anything in the current scope, 1325 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1326 IEnd = IdResolver.end(); 1327 for (; I != IEnd; ++I) { 1328 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1329 S->RemoveDecl(*I); 1330 IdResolver.RemoveDecl(*I); 1331 1332 // Should only need to replace one decl. 1333 break; 1334 } 1335 } 1336 1337 S->AddDecl(D); 1338 1339 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1340 // Implicitly-generated labels may end up getting generated in an order that 1341 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1342 // the label at the appropriate place in the identifier chain. 1343 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1344 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1345 if (IDC == CurContext) { 1346 if (!S->isDeclScope(*I)) 1347 continue; 1348 } else if (IDC->Encloses(CurContext)) 1349 break; 1350 } 1351 1352 IdResolver.InsertDeclAfter(I, D); 1353 } else { 1354 IdResolver.AddDecl(D); 1355 } 1356 } 1357 1358 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1359 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1360 TUScope->AddDecl(D); 1361 } 1362 1363 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1364 bool AllowInlineNamespace) { 1365 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1366 } 1367 1368 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1369 DeclContext *TargetDC = DC->getPrimaryContext(); 1370 do { 1371 if (DeclContext *ScopeDC = S->getEntity()) 1372 if (ScopeDC->getPrimaryContext() == TargetDC) 1373 return S; 1374 } while ((S = S->getParent())); 1375 1376 return nullptr; 1377 } 1378 1379 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1380 DeclContext*, 1381 ASTContext&); 1382 1383 /// Filters out lookup results that don't fall within the given scope 1384 /// as determined by isDeclInScope. 1385 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1386 bool ConsiderLinkage, 1387 bool AllowInlineNamespace) { 1388 LookupResult::Filter F = R.makeFilter(); 1389 while (F.hasNext()) { 1390 NamedDecl *D = F.next(); 1391 1392 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1393 continue; 1394 1395 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1396 continue; 1397 1398 F.erase(); 1399 } 1400 1401 F.done(); 1402 } 1403 1404 static bool isUsingDecl(NamedDecl *D) { 1405 return isa<UsingShadowDecl>(D) || 1406 isa<UnresolvedUsingTypenameDecl>(D) || 1407 isa<UnresolvedUsingValueDecl>(D); 1408 } 1409 1410 /// Removes using shadow declarations from the lookup results. 1411 static void RemoveUsingDecls(LookupResult &R) { 1412 LookupResult::Filter F = R.makeFilter(); 1413 while (F.hasNext()) 1414 if (isUsingDecl(F.next())) 1415 F.erase(); 1416 1417 F.done(); 1418 } 1419 1420 /// \brief Check for this common pattern: 1421 /// @code 1422 /// class S { 1423 /// S(const S&); // DO NOT IMPLEMENT 1424 /// void operator=(const S&); // DO NOT IMPLEMENT 1425 /// }; 1426 /// @endcode 1427 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1428 // FIXME: Should check for private access too but access is set after we get 1429 // the decl here. 1430 if (D->doesThisDeclarationHaveABody()) 1431 return false; 1432 1433 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1434 return CD->isCopyConstructor(); 1435 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1436 return Method->isCopyAssignmentOperator(); 1437 return false; 1438 } 1439 1440 // We need this to handle 1441 // 1442 // typedef struct { 1443 // void *foo() { return 0; } 1444 // } A; 1445 // 1446 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1447 // for example. If 'A', foo will have external linkage. If we have '*A', 1448 // foo will have no linkage. Since we can't know until we get to the end 1449 // of the typedef, this function finds out if D might have non-external linkage. 1450 // Callers should verify at the end of the TU if it D has external linkage or 1451 // not. 1452 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1453 const DeclContext *DC = D->getDeclContext(); 1454 while (!DC->isTranslationUnit()) { 1455 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1456 if (!RD->hasNameForLinkage()) 1457 return true; 1458 } 1459 DC = DC->getParent(); 1460 } 1461 1462 return !D->isExternallyVisible(); 1463 } 1464 1465 // FIXME: This needs to be refactored; some other isInMainFile users want 1466 // these semantics. 1467 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1468 if (S.TUKind != TU_Complete) 1469 return false; 1470 return S.SourceMgr.isInMainFile(Loc); 1471 } 1472 1473 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1474 assert(D); 1475 1476 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1477 return false; 1478 1479 // Ignore all entities declared within templates, and out-of-line definitions 1480 // of members of class templates. 1481 if (D->getDeclContext()->isDependentContext() || 1482 D->getLexicalDeclContext()->isDependentContext()) 1483 return false; 1484 1485 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1486 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1487 return false; 1488 1489 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1490 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1491 return false; 1492 } else { 1493 // 'static inline' functions are defined in headers; don't warn. 1494 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1495 return false; 1496 } 1497 1498 if (FD->doesThisDeclarationHaveABody() && 1499 Context.DeclMustBeEmitted(FD)) 1500 return false; 1501 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1502 // Constants and utility variables are defined in headers with internal 1503 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1504 // like "inline".) 1505 if (!isMainFileLoc(*this, VD->getLocation())) 1506 return false; 1507 1508 if (Context.DeclMustBeEmitted(VD)) 1509 return false; 1510 1511 if (VD->isStaticDataMember() && 1512 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1513 return false; 1514 1515 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1516 return false; 1517 } else { 1518 return false; 1519 } 1520 1521 // Only warn for unused decls internal to the translation unit. 1522 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1523 // for inline functions defined in the main source file, for instance. 1524 return mightHaveNonExternalLinkage(D); 1525 } 1526 1527 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1528 if (!D) 1529 return; 1530 1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1532 const FunctionDecl *First = FD->getFirstDecl(); 1533 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1534 return; // First should already be in the vector. 1535 } 1536 1537 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1538 const VarDecl *First = VD->getFirstDecl(); 1539 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1540 return; // First should already be in the vector. 1541 } 1542 1543 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1544 UnusedFileScopedDecls.push_back(D); 1545 } 1546 1547 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1548 if (D->isInvalidDecl()) 1549 return false; 1550 1551 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1552 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1553 return false; 1554 1555 if (isa<LabelDecl>(D)) 1556 return true; 1557 1558 // Except for labels, we only care about unused decls that are local to 1559 // functions. 1560 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1561 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1562 // For dependent types, the diagnostic is deferred. 1563 WithinFunction = 1564 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1565 if (!WithinFunction) 1566 return false; 1567 1568 if (isa<TypedefNameDecl>(D)) 1569 return true; 1570 1571 // White-list anything that isn't a local variable. 1572 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1573 return false; 1574 1575 // Types of valid local variables should be complete, so this should succeed. 1576 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1577 1578 // White-list anything with an __attribute__((unused)) type. 1579 const auto *Ty = VD->getType().getTypePtr(); 1580 1581 // Only look at the outermost level of typedef. 1582 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1583 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1584 return false; 1585 } 1586 1587 // If we failed to complete the type for some reason, or if the type is 1588 // dependent, don't diagnose the variable. 1589 if (Ty->isIncompleteType() || Ty->isDependentType()) 1590 return false; 1591 1592 // Look at the element type to ensure that the warning behaviour is 1593 // consistent for both scalars and arrays. 1594 Ty = Ty->getBaseElementTypeUnsafe(); 1595 1596 if (const TagType *TT = Ty->getAs<TagType>()) { 1597 const TagDecl *Tag = TT->getDecl(); 1598 if (Tag->hasAttr<UnusedAttr>()) 1599 return false; 1600 1601 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1602 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1603 return false; 1604 1605 if (const Expr *Init = VD->getInit()) { 1606 if (const ExprWithCleanups *Cleanups = 1607 dyn_cast<ExprWithCleanups>(Init)) 1608 Init = Cleanups->getSubExpr(); 1609 const CXXConstructExpr *Construct = 1610 dyn_cast<CXXConstructExpr>(Init); 1611 if (Construct && !Construct->isElidable()) { 1612 CXXConstructorDecl *CD = Construct->getConstructor(); 1613 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1614 return false; 1615 } 1616 } 1617 } 1618 } 1619 1620 // TODO: __attribute__((unused)) templates? 1621 } 1622 1623 return true; 1624 } 1625 1626 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1627 FixItHint &Hint) { 1628 if (isa<LabelDecl>(D)) { 1629 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1630 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1631 if (AfterColon.isInvalid()) 1632 return; 1633 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1634 getCharRange(D->getLocStart(), AfterColon)); 1635 } 1636 } 1637 1638 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1639 if (D->getTypeForDecl()->isDependentType()) 1640 return; 1641 1642 for (auto *TmpD : D->decls()) { 1643 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1644 DiagnoseUnusedDecl(T); 1645 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1646 DiagnoseUnusedNestedTypedefs(R); 1647 } 1648 } 1649 1650 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1651 /// unless they are marked attr(unused). 1652 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1653 if (!ShouldDiagnoseUnusedDecl(D)) 1654 return; 1655 1656 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1657 // typedefs can be referenced later on, so the diagnostics are emitted 1658 // at end-of-translation-unit. 1659 UnusedLocalTypedefNameCandidates.insert(TD); 1660 return; 1661 } 1662 1663 FixItHint Hint; 1664 GenerateFixForUnusedDecl(D, Context, Hint); 1665 1666 unsigned DiagID; 1667 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1668 DiagID = diag::warn_unused_exception_param; 1669 else if (isa<LabelDecl>(D)) 1670 DiagID = diag::warn_unused_label; 1671 else 1672 DiagID = diag::warn_unused_variable; 1673 1674 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1675 } 1676 1677 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1678 // Verify that we have no forward references left. If so, there was a goto 1679 // or address of a label taken, but no definition of it. Label fwd 1680 // definitions are indicated with a null substmt which is also not a resolved 1681 // MS inline assembly label name. 1682 bool Diagnose = false; 1683 if (L->isMSAsmLabel()) 1684 Diagnose = !L->isResolvedMSAsmLabel(); 1685 else 1686 Diagnose = L->getStmt() == nullptr; 1687 if (Diagnose) 1688 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1689 } 1690 1691 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1692 S->mergeNRVOIntoParent(); 1693 1694 if (S->decl_empty()) return; 1695 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1696 "Scope shouldn't contain decls!"); 1697 1698 for (auto *TmpD : S->decls()) { 1699 assert(TmpD && "This decl didn't get pushed??"); 1700 1701 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1702 NamedDecl *D = cast<NamedDecl>(TmpD); 1703 1704 if (!D->getDeclName()) continue; 1705 1706 // Diagnose unused variables in this scope. 1707 if (!S->hasUnrecoverableErrorOccurred()) { 1708 DiagnoseUnusedDecl(D); 1709 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1710 DiagnoseUnusedNestedTypedefs(RD); 1711 } 1712 1713 // If this was a forward reference to a label, verify it was defined. 1714 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1715 CheckPoppedLabel(LD, *this); 1716 1717 // Remove this name from our lexical scope, and warn on it if we haven't 1718 // already. 1719 IdResolver.RemoveDecl(D); 1720 auto ShadowI = ShadowingDecls.find(D); 1721 if (ShadowI != ShadowingDecls.end()) { 1722 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1723 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1724 << D << FD << FD->getParent(); 1725 Diag(FD->getLocation(), diag::note_previous_declaration); 1726 } 1727 ShadowingDecls.erase(ShadowI); 1728 } 1729 } 1730 } 1731 1732 /// \brief Look for an Objective-C class in the translation unit. 1733 /// 1734 /// \param Id The name of the Objective-C class we're looking for. If 1735 /// typo-correction fixes this name, the Id will be updated 1736 /// to the fixed name. 1737 /// 1738 /// \param IdLoc The location of the name in the translation unit. 1739 /// 1740 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1741 /// if there is no class with the given name. 1742 /// 1743 /// \returns The declaration of the named Objective-C class, or NULL if the 1744 /// class could not be found. 1745 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1746 SourceLocation IdLoc, 1747 bool DoTypoCorrection) { 1748 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1749 // creation from this context. 1750 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1751 1752 if (!IDecl && DoTypoCorrection) { 1753 // Perform typo correction at the given location, but only if we 1754 // find an Objective-C class name. 1755 if (TypoCorrection C = CorrectTypo( 1756 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1757 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1758 CTK_ErrorRecovery)) { 1759 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1760 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1761 Id = IDecl->getIdentifier(); 1762 } 1763 } 1764 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1765 // This routine must always return a class definition, if any. 1766 if (Def && Def->getDefinition()) 1767 Def = Def->getDefinition(); 1768 return Def; 1769 } 1770 1771 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1772 /// from S, where a non-field would be declared. This routine copes 1773 /// with the difference between C and C++ scoping rules in structs and 1774 /// unions. For example, the following code is well-formed in C but 1775 /// ill-formed in C++: 1776 /// @code 1777 /// struct S6 { 1778 /// enum { BAR } e; 1779 /// }; 1780 /// 1781 /// void test_S6() { 1782 /// struct S6 a; 1783 /// a.e = BAR; 1784 /// } 1785 /// @endcode 1786 /// For the declaration of BAR, this routine will return a different 1787 /// scope. The scope S will be the scope of the unnamed enumeration 1788 /// within S6. In C++, this routine will return the scope associated 1789 /// with S6, because the enumeration's scope is a transparent 1790 /// context but structures can contain non-field names. In C, this 1791 /// routine will return the translation unit scope, since the 1792 /// enumeration's scope is a transparent context and structures cannot 1793 /// contain non-field names. 1794 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1795 while (((S->getFlags() & Scope::DeclScope) == 0) || 1796 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1797 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1798 S = S->getParent(); 1799 return S; 1800 } 1801 1802 /// \brief Looks up the declaration of "struct objc_super" and 1803 /// saves it for later use in building builtin declaration of 1804 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1805 /// pre-existing declaration exists no action takes place. 1806 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1807 IdentifierInfo *II) { 1808 if (!II->isStr("objc_msgSendSuper")) 1809 return; 1810 ASTContext &Context = ThisSema.Context; 1811 1812 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1813 SourceLocation(), Sema::LookupTagName); 1814 ThisSema.LookupName(Result, S); 1815 if (Result.getResultKind() == LookupResult::Found) 1816 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1817 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1818 } 1819 1820 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1821 switch (Error) { 1822 case ASTContext::GE_None: 1823 return ""; 1824 case ASTContext::GE_Missing_stdio: 1825 return "stdio.h"; 1826 case ASTContext::GE_Missing_setjmp: 1827 return "setjmp.h"; 1828 case ASTContext::GE_Missing_ucontext: 1829 return "ucontext.h"; 1830 } 1831 llvm_unreachable("unhandled error kind"); 1832 } 1833 1834 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1835 /// file scope. lazily create a decl for it. ForRedeclaration is true 1836 /// if we're creating this built-in in anticipation of redeclaring the 1837 /// built-in. 1838 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1839 Scope *S, bool ForRedeclaration, 1840 SourceLocation Loc) { 1841 LookupPredefedObjCSuperType(*this, S, II); 1842 1843 ASTContext::GetBuiltinTypeError Error; 1844 QualType R = Context.GetBuiltinType(ID, Error); 1845 if (Error) { 1846 if (ForRedeclaration) 1847 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1848 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1849 return nullptr; 1850 } 1851 1852 if (!ForRedeclaration && 1853 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1854 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1855 Diag(Loc, diag::ext_implicit_lib_function_decl) 1856 << Context.BuiltinInfo.getName(ID) << R; 1857 if (Context.BuiltinInfo.getHeaderName(ID) && 1858 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1859 Diag(Loc, diag::note_include_header_or_declare) 1860 << Context.BuiltinInfo.getHeaderName(ID) 1861 << Context.BuiltinInfo.getName(ID); 1862 } 1863 1864 if (R.isNull()) 1865 return nullptr; 1866 1867 DeclContext *Parent = Context.getTranslationUnitDecl(); 1868 if (getLangOpts().CPlusPlus) { 1869 LinkageSpecDecl *CLinkageDecl = 1870 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1871 LinkageSpecDecl::lang_c, false); 1872 CLinkageDecl->setImplicit(); 1873 Parent->addDecl(CLinkageDecl); 1874 Parent = CLinkageDecl; 1875 } 1876 1877 FunctionDecl *New = FunctionDecl::Create(Context, 1878 Parent, 1879 Loc, Loc, II, R, /*TInfo=*/nullptr, 1880 SC_Extern, 1881 false, 1882 R->isFunctionProtoType()); 1883 New->setImplicit(); 1884 1885 // Create Decl objects for each parameter, adding them to the 1886 // FunctionDecl. 1887 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1888 SmallVector<ParmVarDecl*, 16> Params; 1889 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1890 ParmVarDecl *parm = 1891 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1892 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1893 SC_None, nullptr); 1894 parm->setScopeInfo(0, i); 1895 Params.push_back(parm); 1896 } 1897 New->setParams(Params); 1898 } 1899 1900 AddKnownFunctionAttributes(New); 1901 RegisterLocallyScopedExternCDecl(New, S); 1902 1903 // TUScope is the translation-unit scope to insert this function into. 1904 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1905 // relate Scopes to DeclContexts, and probably eliminate CurContext 1906 // entirely, but we're not there yet. 1907 DeclContext *SavedContext = CurContext; 1908 CurContext = Parent; 1909 PushOnScopeChains(New, TUScope); 1910 CurContext = SavedContext; 1911 return New; 1912 } 1913 1914 /// Typedef declarations don't have linkage, but they still denote the same 1915 /// entity if their types are the same. 1916 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1917 /// isSameEntity. 1918 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1919 TypedefNameDecl *Decl, 1920 LookupResult &Previous) { 1921 // This is only interesting when modules are enabled. 1922 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1923 return; 1924 1925 // Empty sets are uninteresting. 1926 if (Previous.empty()) 1927 return; 1928 1929 LookupResult::Filter Filter = Previous.makeFilter(); 1930 while (Filter.hasNext()) { 1931 NamedDecl *Old = Filter.next(); 1932 1933 // Non-hidden declarations are never ignored. 1934 if (S.isVisible(Old)) 1935 continue; 1936 1937 // Declarations of the same entity are not ignored, even if they have 1938 // different linkages. 1939 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1940 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1941 Decl->getUnderlyingType())) 1942 continue; 1943 1944 // If both declarations give a tag declaration a typedef name for linkage 1945 // purposes, then they declare the same entity. 1946 if (S.getLangOpts().CPlusPlus && 1947 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1948 Decl->getAnonDeclWithTypedefName()) 1949 continue; 1950 } 1951 1952 Filter.erase(); 1953 } 1954 1955 Filter.done(); 1956 } 1957 1958 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1959 QualType OldType; 1960 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1961 OldType = OldTypedef->getUnderlyingType(); 1962 else 1963 OldType = Context.getTypeDeclType(Old); 1964 QualType NewType = New->getUnderlyingType(); 1965 1966 if (NewType->isVariablyModifiedType()) { 1967 // Must not redefine a typedef with a variably-modified type. 1968 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1969 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1970 << Kind << NewType; 1971 if (Old->getLocation().isValid()) 1972 Diag(Old->getLocation(), diag::note_previous_definition); 1973 New->setInvalidDecl(); 1974 return true; 1975 } 1976 1977 if (OldType != NewType && 1978 !OldType->isDependentType() && 1979 !NewType->isDependentType() && 1980 !Context.hasSameType(OldType, NewType)) { 1981 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1982 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1983 << Kind << NewType << OldType; 1984 if (Old->getLocation().isValid()) 1985 Diag(Old->getLocation(), diag::note_previous_definition); 1986 New->setInvalidDecl(); 1987 return true; 1988 } 1989 return false; 1990 } 1991 1992 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1993 /// same name and scope as a previous declaration 'Old'. Figure out 1994 /// how to resolve this situation, merging decls or emitting 1995 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1996 /// 1997 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1998 LookupResult &OldDecls) { 1999 // If the new decl is known invalid already, don't bother doing any 2000 // merging checks. 2001 if (New->isInvalidDecl()) return; 2002 2003 // Allow multiple definitions for ObjC built-in typedefs. 2004 // FIXME: Verify the underlying types are equivalent! 2005 if (getLangOpts().ObjC1) { 2006 const IdentifierInfo *TypeID = New->getIdentifier(); 2007 switch (TypeID->getLength()) { 2008 default: break; 2009 case 2: 2010 { 2011 if (!TypeID->isStr("id")) 2012 break; 2013 QualType T = New->getUnderlyingType(); 2014 if (!T->isPointerType()) 2015 break; 2016 if (!T->isVoidPointerType()) { 2017 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2018 if (!PT->isStructureType()) 2019 break; 2020 } 2021 Context.setObjCIdRedefinitionType(T); 2022 // Install the built-in type for 'id', ignoring the current definition. 2023 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2024 return; 2025 } 2026 case 5: 2027 if (!TypeID->isStr("Class")) 2028 break; 2029 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2030 // Install the built-in type for 'Class', ignoring the current definition. 2031 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2032 return; 2033 case 3: 2034 if (!TypeID->isStr("SEL")) 2035 break; 2036 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2037 // Install the built-in type for 'SEL', ignoring the current definition. 2038 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2039 return; 2040 } 2041 // Fall through - the typedef name was not a builtin type. 2042 } 2043 2044 // Verify the old decl was also a type. 2045 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2046 if (!Old) { 2047 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2048 << New->getDeclName(); 2049 2050 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2051 if (OldD->getLocation().isValid()) 2052 Diag(OldD->getLocation(), diag::note_previous_definition); 2053 2054 return New->setInvalidDecl(); 2055 } 2056 2057 // If the old declaration is invalid, just give up here. 2058 if (Old->isInvalidDecl()) 2059 return New->setInvalidDecl(); 2060 2061 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2062 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2063 auto *NewTag = New->getAnonDeclWithTypedefName(); 2064 NamedDecl *Hidden = nullptr; 2065 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2066 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2067 !hasVisibleDefinition(OldTag, &Hidden)) { 2068 // There is a definition of this tag, but it is not visible. Use it 2069 // instead of our tag. 2070 New->setTypeForDecl(OldTD->getTypeForDecl()); 2071 if (OldTD->isModed()) 2072 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2073 OldTD->getUnderlyingType()); 2074 else 2075 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2076 2077 // Make the old tag definition visible. 2078 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2079 2080 // If this was an unscoped enumeration, yank all of its enumerators 2081 // out of the scope. 2082 if (isa<EnumDecl>(NewTag)) { 2083 Scope *EnumScope = getNonFieldDeclScope(S); 2084 for (auto *D : NewTag->decls()) { 2085 auto *ED = cast<EnumConstantDecl>(D); 2086 assert(EnumScope->isDeclScope(ED)); 2087 EnumScope->RemoveDecl(ED); 2088 IdResolver.RemoveDecl(ED); 2089 ED->getLexicalDeclContext()->removeDecl(ED); 2090 } 2091 } 2092 } 2093 } 2094 2095 // If the typedef types are not identical, reject them in all languages and 2096 // with any extensions enabled. 2097 if (isIncompatibleTypedef(Old, New)) 2098 return; 2099 2100 // The types match. Link up the redeclaration chain and merge attributes if 2101 // the old declaration was a typedef. 2102 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2103 New->setPreviousDecl(Typedef); 2104 mergeDeclAttributes(New, Old); 2105 } 2106 2107 if (getLangOpts().MicrosoftExt) 2108 return; 2109 2110 if (getLangOpts().CPlusPlus) { 2111 // C++ [dcl.typedef]p2: 2112 // In a given non-class scope, a typedef specifier can be used to 2113 // redefine the name of any type declared in that scope to refer 2114 // to the type to which it already refers. 2115 if (!isa<CXXRecordDecl>(CurContext)) 2116 return; 2117 2118 // C++0x [dcl.typedef]p4: 2119 // In a given class scope, a typedef specifier can be used to redefine 2120 // any class-name declared in that scope that is not also a typedef-name 2121 // to refer to the type to which it already refers. 2122 // 2123 // This wording came in via DR424, which was a correction to the 2124 // wording in DR56, which accidentally banned code like: 2125 // 2126 // struct S { 2127 // typedef struct A { } A; 2128 // }; 2129 // 2130 // in the C++03 standard. We implement the C++0x semantics, which 2131 // allow the above but disallow 2132 // 2133 // struct S { 2134 // typedef int I; 2135 // typedef int I; 2136 // }; 2137 // 2138 // since that was the intent of DR56. 2139 if (!isa<TypedefNameDecl>(Old)) 2140 return; 2141 2142 Diag(New->getLocation(), diag::err_redefinition) 2143 << New->getDeclName(); 2144 Diag(Old->getLocation(), diag::note_previous_definition); 2145 return New->setInvalidDecl(); 2146 } 2147 2148 // Modules always permit redefinition of typedefs, as does C11. 2149 if (getLangOpts().Modules || getLangOpts().C11) 2150 return; 2151 2152 // If we have a redefinition of a typedef in C, emit a warning. This warning 2153 // is normally mapped to an error, but can be controlled with 2154 // -Wtypedef-redefinition. If either the original or the redefinition is 2155 // in a system header, don't emit this for compatibility with GCC. 2156 if (getDiagnostics().getSuppressSystemWarnings() && 2157 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2158 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2159 return; 2160 2161 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2162 << New->getDeclName(); 2163 Diag(Old->getLocation(), diag::note_previous_definition); 2164 } 2165 2166 /// DeclhasAttr - returns true if decl Declaration already has the target 2167 /// attribute. 2168 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2169 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2170 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2171 for (const auto *i : D->attrs()) 2172 if (i->getKind() == A->getKind()) { 2173 if (Ann) { 2174 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2175 return true; 2176 continue; 2177 } 2178 // FIXME: Don't hardcode this check 2179 if (OA && isa<OwnershipAttr>(i)) 2180 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2181 return true; 2182 } 2183 2184 return false; 2185 } 2186 2187 static bool isAttributeTargetADefinition(Decl *D) { 2188 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2189 return VD->isThisDeclarationADefinition(); 2190 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2191 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2192 return true; 2193 } 2194 2195 /// Merge alignment attributes from \p Old to \p New, taking into account the 2196 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2197 /// 2198 /// \return \c true if any attributes were added to \p New. 2199 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2200 // Look for alignas attributes on Old, and pick out whichever attribute 2201 // specifies the strictest alignment requirement. 2202 AlignedAttr *OldAlignasAttr = nullptr; 2203 AlignedAttr *OldStrictestAlignAttr = nullptr; 2204 unsigned OldAlign = 0; 2205 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2206 // FIXME: We have no way of representing inherited dependent alignments 2207 // in a case like: 2208 // template<int A, int B> struct alignas(A) X; 2209 // template<int A, int B> struct alignas(B) X {}; 2210 // For now, we just ignore any alignas attributes which are not on the 2211 // definition in such a case. 2212 if (I->isAlignmentDependent()) 2213 return false; 2214 2215 if (I->isAlignas()) 2216 OldAlignasAttr = I; 2217 2218 unsigned Align = I->getAlignment(S.Context); 2219 if (Align > OldAlign) { 2220 OldAlign = Align; 2221 OldStrictestAlignAttr = I; 2222 } 2223 } 2224 2225 // Look for alignas attributes on New. 2226 AlignedAttr *NewAlignasAttr = nullptr; 2227 unsigned NewAlign = 0; 2228 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2229 if (I->isAlignmentDependent()) 2230 return false; 2231 2232 if (I->isAlignas()) 2233 NewAlignasAttr = I; 2234 2235 unsigned Align = I->getAlignment(S.Context); 2236 if (Align > NewAlign) 2237 NewAlign = Align; 2238 } 2239 2240 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2241 // Both declarations have 'alignas' attributes. We require them to match. 2242 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2243 // fall short. (If two declarations both have alignas, they must both match 2244 // every definition, and so must match each other if there is a definition.) 2245 2246 // If either declaration only contains 'alignas(0)' specifiers, then it 2247 // specifies the natural alignment for the type. 2248 if (OldAlign == 0 || NewAlign == 0) { 2249 QualType Ty; 2250 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2251 Ty = VD->getType(); 2252 else 2253 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2254 2255 if (OldAlign == 0) 2256 OldAlign = S.Context.getTypeAlign(Ty); 2257 if (NewAlign == 0) 2258 NewAlign = S.Context.getTypeAlign(Ty); 2259 } 2260 2261 if (OldAlign != NewAlign) { 2262 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2263 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2264 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2265 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2266 } 2267 } 2268 2269 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2270 // C++11 [dcl.align]p6: 2271 // if any declaration of an entity has an alignment-specifier, 2272 // every defining declaration of that entity shall specify an 2273 // equivalent alignment. 2274 // C11 6.7.5/7: 2275 // If the definition of an object does not have an alignment 2276 // specifier, any other declaration of that object shall also 2277 // have no alignment specifier. 2278 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2279 << OldAlignasAttr; 2280 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2281 << OldAlignasAttr; 2282 } 2283 2284 bool AnyAdded = false; 2285 2286 // Ensure we have an attribute representing the strictest alignment. 2287 if (OldAlign > NewAlign) { 2288 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2289 Clone->setInherited(true); 2290 New->addAttr(Clone); 2291 AnyAdded = true; 2292 } 2293 2294 // Ensure we have an alignas attribute if the old declaration had one. 2295 if (OldAlignasAttr && !NewAlignasAttr && 2296 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2297 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2298 Clone->setInherited(true); 2299 New->addAttr(Clone); 2300 AnyAdded = true; 2301 } 2302 2303 return AnyAdded; 2304 } 2305 2306 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2307 const InheritableAttr *Attr, 2308 Sema::AvailabilityMergeKind AMK) { 2309 // This function copies an attribute Attr from a previous declaration to the 2310 // new declaration D if the new declaration doesn't itself have that attribute 2311 // yet or if that attribute allows duplicates. 2312 // If you're adding a new attribute that requires logic different from 2313 // "use explicit attribute on decl if present, else use attribute from 2314 // previous decl", for example if the attribute needs to be consistent 2315 // between redeclarations, you need to call a custom merge function here. 2316 InheritableAttr *NewAttr = nullptr; 2317 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2318 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2319 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2320 AA->isImplicit(), AA->getIntroduced(), 2321 AA->getDeprecated(), 2322 AA->getObsoleted(), AA->getUnavailable(), 2323 AA->getMessage(), AA->getStrict(), 2324 AA->getReplacement(), AMK, 2325 AttrSpellingListIndex); 2326 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2327 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2328 AttrSpellingListIndex); 2329 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2330 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2331 AttrSpellingListIndex); 2332 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2333 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2334 AttrSpellingListIndex); 2335 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2336 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2337 AttrSpellingListIndex); 2338 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2339 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2340 FA->getFormatIdx(), FA->getFirstArg(), 2341 AttrSpellingListIndex); 2342 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2343 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2344 AttrSpellingListIndex); 2345 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2346 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2347 AttrSpellingListIndex, 2348 IA->getSemanticSpelling()); 2349 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2350 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2351 &S.Context.Idents.get(AA->getSpelling()), 2352 AttrSpellingListIndex); 2353 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2354 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2355 isa<CUDAGlobalAttr>(Attr))) { 2356 // CUDA target attributes are part of function signature for 2357 // overloading purposes and must not be merged. 2358 return false; 2359 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2360 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2361 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2362 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2363 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2364 NewAttr = S.mergeInternalLinkageAttr( 2365 D, InternalLinkageA->getRange(), 2366 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2367 AttrSpellingListIndex); 2368 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2369 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2370 &S.Context.Idents.get(CommonA->getSpelling()), 2371 AttrSpellingListIndex); 2372 else if (isa<AlignedAttr>(Attr)) 2373 // AlignedAttrs are handled separately, because we need to handle all 2374 // such attributes on a declaration at the same time. 2375 NewAttr = nullptr; 2376 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2377 (AMK == Sema::AMK_Override || 2378 AMK == Sema::AMK_ProtocolImplementation)) 2379 NewAttr = nullptr; 2380 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2381 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2382 UA->getGuid()); 2383 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2384 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2385 2386 if (NewAttr) { 2387 NewAttr->setInherited(true); 2388 D->addAttr(NewAttr); 2389 if (isa<MSInheritanceAttr>(NewAttr)) 2390 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2391 return true; 2392 } 2393 2394 return false; 2395 } 2396 2397 static const Decl *getDefinition(const Decl *D) { 2398 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2399 return TD->getDefinition(); 2400 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2401 const VarDecl *Def = VD->getDefinition(); 2402 if (Def) 2403 return Def; 2404 return VD->getActingDefinition(); 2405 } 2406 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2407 return FD->getDefinition(); 2408 return nullptr; 2409 } 2410 2411 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2412 for (const auto *Attribute : D->attrs()) 2413 if (Attribute->getKind() == Kind) 2414 return true; 2415 return false; 2416 } 2417 2418 /// checkNewAttributesAfterDef - If we already have a definition, check that 2419 /// there are no new attributes in this declaration. 2420 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2421 if (!New->hasAttrs()) 2422 return; 2423 2424 const Decl *Def = getDefinition(Old); 2425 if (!Def || Def == New) 2426 return; 2427 2428 AttrVec &NewAttributes = New->getAttrs(); 2429 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2430 const Attr *NewAttribute = NewAttributes[I]; 2431 2432 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2433 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2434 Sema::SkipBodyInfo SkipBody; 2435 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2436 2437 // If we're skipping this definition, drop the "alias" attribute. 2438 if (SkipBody.ShouldSkip) { 2439 NewAttributes.erase(NewAttributes.begin() + I); 2440 --E; 2441 continue; 2442 } 2443 } else { 2444 VarDecl *VD = cast<VarDecl>(New); 2445 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2446 VarDecl::TentativeDefinition 2447 ? diag::err_alias_after_tentative 2448 : diag::err_redefinition; 2449 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2450 S.Diag(Def->getLocation(), diag::note_previous_definition); 2451 VD->setInvalidDecl(); 2452 } 2453 ++I; 2454 continue; 2455 } 2456 2457 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2458 // Tentative definitions are only interesting for the alias check above. 2459 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2460 ++I; 2461 continue; 2462 } 2463 } 2464 2465 if (hasAttribute(Def, NewAttribute->getKind())) { 2466 ++I; 2467 continue; // regular attr merging will take care of validating this. 2468 } 2469 2470 if (isa<C11NoReturnAttr>(NewAttribute)) { 2471 // C's _Noreturn is allowed to be added to a function after it is defined. 2472 ++I; 2473 continue; 2474 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2475 if (AA->isAlignas()) { 2476 // C++11 [dcl.align]p6: 2477 // if any declaration of an entity has an alignment-specifier, 2478 // every defining declaration of that entity shall specify an 2479 // equivalent alignment. 2480 // C11 6.7.5/7: 2481 // If the definition of an object does not have an alignment 2482 // specifier, any other declaration of that object shall also 2483 // have no alignment specifier. 2484 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2485 << AA; 2486 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2487 << AA; 2488 NewAttributes.erase(NewAttributes.begin() + I); 2489 --E; 2490 continue; 2491 } 2492 } 2493 2494 S.Diag(NewAttribute->getLocation(), 2495 diag::warn_attribute_precede_definition); 2496 S.Diag(Def->getLocation(), diag::note_previous_definition); 2497 NewAttributes.erase(NewAttributes.begin() + I); 2498 --E; 2499 } 2500 } 2501 2502 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2503 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2504 AvailabilityMergeKind AMK) { 2505 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2506 UsedAttr *NewAttr = OldAttr->clone(Context); 2507 NewAttr->setInherited(true); 2508 New->addAttr(NewAttr); 2509 } 2510 2511 if (!Old->hasAttrs() && !New->hasAttrs()) 2512 return; 2513 2514 // Attributes declared post-definition are currently ignored. 2515 checkNewAttributesAfterDef(*this, New, Old); 2516 2517 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2518 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2519 if (OldA->getLabel() != NewA->getLabel()) { 2520 // This redeclaration changes __asm__ label. 2521 Diag(New->getLocation(), diag::err_different_asm_label); 2522 Diag(OldA->getLocation(), diag::note_previous_declaration); 2523 } 2524 } else if (Old->isUsed()) { 2525 // This redeclaration adds an __asm__ label to a declaration that has 2526 // already been ODR-used. 2527 Diag(New->getLocation(), diag::err_late_asm_label_name) 2528 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2529 } 2530 } 2531 2532 // Re-declaration cannot add abi_tag's. 2533 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2534 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2535 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2536 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2537 NewTag) == OldAbiTagAttr->tags_end()) { 2538 Diag(NewAbiTagAttr->getLocation(), 2539 diag::err_new_abi_tag_on_redeclaration) 2540 << NewTag; 2541 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2542 } 2543 } 2544 } else { 2545 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2546 Diag(Old->getLocation(), diag::note_previous_declaration); 2547 } 2548 } 2549 2550 if (!Old->hasAttrs()) 2551 return; 2552 2553 bool foundAny = New->hasAttrs(); 2554 2555 // Ensure that any moving of objects within the allocated map is done before 2556 // we process them. 2557 if (!foundAny) New->setAttrs(AttrVec()); 2558 2559 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2560 // Ignore deprecated/unavailable/availability attributes if requested. 2561 AvailabilityMergeKind LocalAMK = AMK_None; 2562 if (isa<DeprecatedAttr>(I) || 2563 isa<UnavailableAttr>(I) || 2564 isa<AvailabilityAttr>(I)) { 2565 switch (AMK) { 2566 case AMK_None: 2567 continue; 2568 2569 case AMK_Redeclaration: 2570 case AMK_Override: 2571 case AMK_ProtocolImplementation: 2572 LocalAMK = AMK; 2573 break; 2574 } 2575 } 2576 2577 // Already handled. 2578 if (isa<UsedAttr>(I)) 2579 continue; 2580 2581 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2582 foundAny = true; 2583 } 2584 2585 if (mergeAlignedAttrs(*this, New, Old)) 2586 foundAny = true; 2587 2588 if (!foundAny) New->dropAttrs(); 2589 } 2590 2591 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2592 /// to the new one. 2593 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2594 const ParmVarDecl *oldDecl, 2595 Sema &S) { 2596 // C++11 [dcl.attr.depend]p2: 2597 // The first declaration of a function shall specify the 2598 // carries_dependency attribute for its declarator-id if any declaration 2599 // of the function specifies the carries_dependency attribute. 2600 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2601 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2602 S.Diag(CDA->getLocation(), 2603 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2604 // Find the first declaration of the parameter. 2605 // FIXME: Should we build redeclaration chains for function parameters? 2606 const FunctionDecl *FirstFD = 2607 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2608 const ParmVarDecl *FirstVD = 2609 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2610 S.Diag(FirstVD->getLocation(), 2611 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2612 } 2613 2614 if (!oldDecl->hasAttrs()) 2615 return; 2616 2617 bool foundAny = newDecl->hasAttrs(); 2618 2619 // Ensure that any moving of objects within the allocated map is 2620 // done before we process them. 2621 if (!foundAny) newDecl->setAttrs(AttrVec()); 2622 2623 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2624 if (!DeclHasAttr(newDecl, I)) { 2625 InheritableAttr *newAttr = 2626 cast<InheritableParamAttr>(I->clone(S.Context)); 2627 newAttr->setInherited(true); 2628 newDecl->addAttr(newAttr); 2629 foundAny = true; 2630 } 2631 } 2632 2633 if (!foundAny) newDecl->dropAttrs(); 2634 } 2635 2636 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2637 const ParmVarDecl *OldParam, 2638 Sema &S) { 2639 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2640 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2641 if (*Oldnullability != *Newnullability) { 2642 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2643 << DiagNullabilityKind( 2644 *Newnullability, 2645 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2646 != 0)) 2647 << DiagNullabilityKind( 2648 *Oldnullability, 2649 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2650 != 0)); 2651 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2652 } 2653 } else { 2654 QualType NewT = NewParam->getType(); 2655 NewT = S.Context.getAttributedType( 2656 AttributedType::getNullabilityAttrKind(*Oldnullability), 2657 NewT, NewT); 2658 NewParam->setType(NewT); 2659 } 2660 } 2661 } 2662 2663 namespace { 2664 2665 /// Used in MergeFunctionDecl to keep track of function parameters in 2666 /// C. 2667 struct GNUCompatibleParamWarning { 2668 ParmVarDecl *OldParm; 2669 ParmVarDecl *NewParm; 2670 QualType PromotedType; 2671 }; 2672 2673 } // end anonymous namespace 2674 2675 /// getSpecialMember - get the special member enum for a method. 2676 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2677 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2678 if (Ctor->isDefaultConstructor()) 2679 return Sema::CXXDefaultConstructor; 2680 2681 if (Ctor->isCopyConstructor()) 2682 return Sema::CXXCopyConstructor; 2683 2684 if (Ctor->isMoveConstructor()) 2685 return Sema::CXXMoveConstructor; 2686 } else if (isa<CXXDestructorDecl>(MD)) { 2687 return Sema::CXXDestructor; 2688 } else if (MD->isCopyAssignmentOperator()) { 2689 return Sema::CXXCopyAssignment; 2690 } else if (MD->isMoveAssignmentOperator()) { 2691 return Sema::CXXMoveAssignment; 2692 } 2693 2694 return Sema::CXXInvalid; 2695 } 2696 2697 // Determine whether the previous declaration was a definition, implicit 2698 // declaration, or a declaration. 2699 template <typename T> 2700 static std::pair<diag::kind, SourceLocation> 2701 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2702 diag::kind PrevDiag; 2703 SourceLocation OldLocation = Old->getLocation(); 2704 if (Old->isThisDeclarationADefinition()) 2705 PrevDiag = diag::note_previous_definition; 2706 else if (Old->isImplicit()) { 2707 PrevDiag = diag::note_previous_implicit_declaration; 2708 if (OldLocation.isInvalid()) 2709 OldLocation = New->getLocation(); 2710 } else 2711 PrevDiag = diag::note_previous_declaration; 2712 return std::make_pair(PrevDiag, OldLocation); 2713 } 2714 2715 /// canRedefineFunction - checks if a function can be redefined. Currently, 2716 /// only extern inline functions can be redefined, and even then only in 2717 /// GNU89 mode. 2718 static bool canRedefineFunction(const FunctionDecl *FD, 2719 const LangOptions& LangOpts) { 2720 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2721 !LangOpts.CPlusPlus && 2722 FD->isInlineSpecified() && 2723 FD->getStorageClass() == SC_Extern); 2724 } 2725 2726 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2727 const AttributedType *AT = T->getAs<AttributedType>(); 2728 while (AT && !AT->isCallingConv()) 2729 AT = AT->getModifiedType()->getAs<AttributedType>(); 2730 return AT; 2731 } 2732 2733 template <typename T> 2734 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2735 const DeclContext *DC = Old->getDeclContext(); 2736 if (DC->isRecord()) 2737 return false; 2738 2739 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2740 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2741 return true; 2742 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2743 return true; 2744 return false; 2745 } 2746 2747 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2748 static bool isExternC(VarTemplateDecl *) { return false; } 2749 2750 /// \brief Check whether a redeclaration of an entity introduced by a 2751 /// using-declaration is valid, given that we know it's not an overload 2752 /// (nor a hidden tag declaration). 2753 template<typename ExpectedDecl> 2754 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2755 ExpectedDecl *New) { 2756 // C++11 [basic.scope.declarative]p4: 2757 // Given a set of declarations in a single declarative region, each of 2758 // which specifies the same unqualified name, 2759 // -- they shall all refer to the same entity, or all refer to functions 2760 // and function templates; or 2761 // -- exactly one declaration shall declare a class name or enumeration 2762 // name that is not a typedef name and the other declarations shall all 2763 // refer to the same variable or enumerator, or all refer to functions 2764 // and function templates; in this case the class name or enumeration 2765 // name is hidden (3.3.10). 2766 2767 // C++11 [namespace.udecl]p14: 2768 // If a function declaration in namespace scope or block scope has the 2769 // same name and the same parameter-type-list as a function introduced 2770 // by a using-declaration, and the declarations do not declare the same 2771 // function, the program is ill-formed. 2772 2773 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2774 if (Old && 2775 !Old->getDeclContext()->getRedeclContext()->Equals( 2776 New->getDeclContext()->getRedeclContext()) && 2777 !(isExternC(Old) && isExternC(New))) 2778 Old = nullptr; 2779 2780 if (!Old) { 2781 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2782 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2783 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2784 return true; 2785 } 2786 return false; 2787 } 2788 2789 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2790 const FunctionDecl *B) { 2791 assert(A->getNumParams() == B->getNumParams()); 2792 2793 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2794 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2795 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2796 if (AttrA == AttrB) 2797 return true; 2798 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2799 }; 2800 2801 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2802 } 2803 2804 /// MergeFunctionDecl - We just parsed a function 'New' from 2805 /// declarator D which has the same name and scope as a previous 2806 /// declaration 'Old'. Figure out how to resolve this situation, 2807 /// merging decls or emitting diagnostics as appropriate. 2808 /// 2809 /// In C++, New and Old must be declarations that are not 2810 /// overloaded. Use IsOverload to determine whether New and Old are 2811 /// overloaded, and to select the Old declaration that New should be 2812 /// merged with. 2813 /// 2814 /// Returns true if there was an error, false otherwise. 2815 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2816 Scope *S, bool MergeTypeWithOld) { 2817 // Verify the old decl was also a function. 2818 FunctionDecl *Old = OldD->getAsFunction(); 2819 if (!Old) { 2820 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2821 if (New->getFriendObjectKind()) { 2822 Diag(New->getLocation(), diag::err_using_decl_friend); 2823 Diag(Shadow->getTargetDecl()->getLocation(), 2824 diag::note_using_decl_target); 2825 Diag(Shadow->getUsingDecl()->getLocation(), 2826 diag::note_using_decl) << 0; 2827 return true; 2828 } 2829 2830 // Check whether the two declarations might declare the same function. 2831 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2832 return true; 2833 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2834 } else { 2835 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2836 << New->getDeclName(); 2837 Diag(OldD->getLocation(), diag::note_previous_definition); 2838 return true; 2839 } 2840 } 2841 2842 // If the old declaration is invalid, just give up here. 2843 if (Old->isInvalidDecl()) 2844 return true; 2845 2846 diag::kind PrevDiag; 2847 SourceLocation OldLocation; 2848 std::tie(PrevDiag, OldLocation) = 2849 getNoteDiagForInvalidRedeclaration(Old, New); 2850 2851 // Don't complain about this if we're in GNU89 mode and the old function 2852 // is an extern inline function. 2853 // Don't complain about specializations. They are not supposed to have 2854 // storage classes. 2855 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2856 New->getStorageClass() == SC_Static && 2857 Old->hasExternalFormalLinkage() && 2858 !New->getTemplateSpecializationInfo() && 2859 !canRedefineFunction(Old, getLangOpts())) { 2860 if (getLangOpts().MicrosoftExt) { 2861 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2862 Diag(OldLocation, PrevDiag); 2863 } else { 2864 Diag(New->getLocation(), diag::err_static_non_static) << New; 2865 Diag(OldLocation, PrevDiag); 2866 return true; 2867 } 2868 } 2869 2870 if (New->hasAttr<InternalLinkageAttr>() && 2871 !Old->hasAttr<InternalLinkageAttr>()) { 2872 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2873 << New->getDeclName(); 2874 Diag(Old->getLocation(), diag::note_previous_definition); 2875 New->dropAttr<InternalLinkageAttr>(); 2876 } 2877 2878 // If a function is first declared with a calling convention, but is later 2879 // declared or defined without one, all following decls assume the calling 2880 // convention of the first. 2881 // 2882 // It's OK if a function is first declared without a calling convention, 2883 // but is later declared or defined with the default calling convention. 2884 // 2885 // To test if either decl has an explicit calling convention, we look for 2886 // AttributedType sugar nodes on the type as written. If they are missing or 2887 // were canonicalized away, we assume the calling convention was implicit. 2888 // 2889 // Note also that we DO NOT return at this point, because we still have 2890 // other tests to run. 2891 QualType OldQType = Context.getCanonicalType(Old->getType()); 2892 QualType NewQType = Context.getCanonicalType(New->getType()); 2893 const FunctionType *OldType = cast<FunctionType>(OldQType); 2894 const FunctionType *NewType = cast<FunctionType>(NewQType); 2895 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2896 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2897 bool RequiresAdjustment = false; 2898 2899 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2900 FunctionDecl *First = Old->getFirstDecl(); 2901 const FunctionType *FT = 2902 First->getType().getCanonicalType()->castAs<FunctionType>(); 2903 FunctionType::ExtInfo FI = FT->getExtInfo(); 2904 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2905 if (!NewCCExplicit) { 2906 // Inherit the CC from the previous declaration if it was specified 2907 // there but not here. 2908 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2909 RequiresAdjustment = true; 2910 } else { 2911 // Calling conventions aren't compatible, so complain. 2912 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2913 Diag(New->getLocation(), diag::err_cconv_change) 2914 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2915 << !FirstCCExplicit 2916 << (!FirstCCExplicit ? "" : 2917 FunctionType::getNameForCallConv(FI.getCC())); 2918 2919 // Put the note on the first decl, since it is the one that matters. 2920 Diag(First->getLocation(), diag::note_previous_declaration); 2921 return true; 2922 } 2923 } 2924 2925 // FIXME: diagnose the other way around? 2926 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2927 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2928 RequiresAdjustment = true; 2929 } 2930 2931 // Merge regparm attribute. 2932 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2933 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2934 if (NewTypeInfo.getHasRegParm()) { 2935 Diag(New->getLocation(), diag::err_regparm_mismatch) 2936 << NewType->getRegParmType() 2937 << OldType->getRegParmType(); 2938 Diag(OldLocation, diag::note_previous_declaration); 2939 return true; 2940 } 2941 2942 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2943 RequiresAdjustment = true; 2944 } 2945 2946 // Merge ns_returns_retained attribute. 2947 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2948 if (NewTypeInfo.getProducesResult()) { 2949 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2950 Diag(OldLocation, diag::note_previous_declaration); 2951 return true; 2952 } 2953 2954 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2955 RequiresAdjustment = true; 2956 } 2957 2958 if (RequiresAdjustment) { 2959 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2960 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2961 New->setType(QualType(AdjustedType, 0)); 2962 NewQType = Context.getCanonicalType(New->getType()); 2963 NewType = cast<FunctionType>(NewQType); 2964 } 2965 2966 // If this redeclaration makes the function inline, we may need to add it to 2967 // UndefinedButUsed. 2968 if (!Old->isInlined() && New->isInlined() && 2969 !New->hasAttr<GNUInlineAttr>() && 2970 !getLangOpts().GNUInline && 2971 Old->isUsed(false) && 2972 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2973 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2974 SourceLocation())); 2975 2976 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2977 // about it. 2978 if (New->hasAttr<GNUInlineAttr>() && 2979 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2980 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2981 } 2982 2983 // If pass_object_size params don't match up perfectly, this isn't a valid 2984 // redeclaration. 2985 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2986 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2987 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2988 << New->getDeclName(); 2989 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2990 return true; 2991 } 2992 2993 if (getLangOpts().CPlusPlus) { 2994 // C++1z [over.load]p2 2995 // Certain function declarations cannot be overloaded: 2996 // -- Function declarations that differ only in the return type, 2997 // the exception specification, or both cannot be overloaded. 2998 2999 // Check the exception specifications match. This may recompute the type of 3000 // both Old and New if it resolved exception specifications, so grab the 3001 // types again after this. Because this updates the type, we do this before 3002 // any of the other checks below, which may update the "de facto" NewQType 3003 // but do not necessarily update the type of New. 3004 if (CheckEquivalentExceptionSpec(Old, New)) 3005 return true; 3006 OldQType = Context.getCanonicalType(Old->getType()); 3007 NewQType = Context.getCanonicalType(New->getType()); 3008 3009 // Go back to the type source info to compare the declared return types, 3010 // per C++1y [dcl.type.auto]p13: 3011 // Redeclarations or specializations of a function or function template 3012 // with a declared return type that uses a placeholder type shall also 3013 // use that placeholder, not a deduced type. 3014 QualType OldDeclaredReturnType = 3015 (Old->getTypeSourceInfo() 3016 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3017 : OldType)->getReturnType(); 3018 QualType NewDeclaredReturnType = 3019 (New->getTypeSourceInfo() 3020 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3021 : NewType)->getReturnType(); 3022 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3023 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3024 New->isLocalExternDecl())) { 3025 QualType ResQT; 3026 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3027 OldDeclaredReturnType->isObjCObjectPointerType()) 3028 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3029 if (ResQT.isNull()) { 3030 if (New->isCXXClassMember() && New->isOutOfLine()) 3031 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3032 << New << New->getReturnTypeSourceRange(); 3033 else 3034 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3035 << New->getReturnTypeSourceRange(); 3036 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3037 << Old->getReturnTypeSourceRange(); 3038 return true; 3039 } 3040 else 3041 NewQType = ResQT; 3042 } 3043 3044 QualType OldReturnType = OldType->getReturnType(); 3045 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3046 if (OldReturnType != NewReturnType) { 3047 // If this function has a deduced return type and has already been 3048 // defined, copy the deduced value from the old declaration. 3049 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3050 if (OldAT && OldAT->isDeduced()) { 3051 New->setType( 3052 SubstAutoType(New->getType(), 3053 OldAT->isDependentType() ? Context.DependentTy 3054 : OldAT->getDeducedType())); 3055 NewQType = Context.getCanonicalType( 3056 SubstAutoType(NewQType, 3057 OldAT->isDependentType() ? Context.DependentTy 3058 : OldAT->getDeducedType())); 3059 } 3060 } 3061 3062 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3063 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3064 if (OldMethod && NewMethod) { 3065 // Preserve triviality. 3066 NewMethod->setTrivial(OldMethod->isTrivial()); 3067 3068 // MSVC allows explicit template specialization at class scope: 3069 // 2 CXXMethodDecls referring to the same function will be injected. 3070 // We don't want a redeclaration error. 3071 bool IsClassScopeExplicitSpecialization = 3072 OldMethod->isFunctionTemplateSpecialization() && 3073 NewMethod->isFunctionTemplateSpecialization(); 3074 bool isFriend = NewMethod->getFriendObjectKind(); 3075 3076 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3077 !IsClassScopeExplicitSpecialization) { 3078 // -- Member function declarations with the same name and the 3079 // same parameter types cannot be overloaded if any of them 3080 // is a static member function declaration. 3081 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3082 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3083 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3084 return true; 3085 } 3086 3087 // C++ [class.mem]p1: 3088 // [...] A member shall not be declared twice in the 3089 // member-specification, except that a nested class or member 3090 // class template can be declared and then later defined. 3091 if (!inTemplateInstantiation()) { 3092 unsigned NewDiag; 3093 if (isa<CXXConstructorDecl>(OldMethod)) 3094 NewDiag = diag::err_constructor_redeclared; 3095 else if (isa<CXXDestructorDecl>(NewMethod)) 3096 NewDiag = diag::err_destructor_redeclared; 3097 else if (isa<CXXConversionDecl>(NewMethod)) 3098 NewDiag = diag::err_conv_function_redeclared; 3099 else 3100 NewDiag = diag::err_member_redeclared; 3101 3102 Diag(New->getLocation(), NewDiag); 3103 } else { 3104 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3105 << New << New->getType(); 3106 } 3107 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3108 return true; 3109 3110 // Complain if this is an explicit declaration of a special 3111 // member that was initially declared implicitly. 3112 // 3113 // As an exception, it's okay to befriend such methods in order 3114 // to permit the implicit constructor/destructor/operator calls. 3115 } else if (OldMethod->isImplicit()) { 3116 if (isFriend) { 3117 NewMethod->setImplicit(); 3118 } else { 3119 Diag(NewMethod->getLocation(), 3120 diag::err_definition_of_implicitly_declared_member) 3121 << New << getSpecialMember(OldMethod); 3122 return true; 3123 } 3124 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3125 Diag(NewMethod->getLocation(), 3126 diag::err_definition_of_explicitly_defaulted_member) 3127 << getSpecialMember(OldMethod); 3128 return true; 3129 } 3130 } 3131 3132 // C++11 [dcl.attr.noreturn]p1: 3133 // The first declaration of a function shall specify the noreturn 3134 // attribute if any declaration of that function specifies the noreturn 3135 // attribute. 3136 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3137 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3138 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3139 Diag(Old->getFirstDecl()->getLocation(), 3140 diag::note_noreturn_missing_first_decl); 3141 } 3142 3143 // C++11 [dcl.attr.depend]p2: 3144 // The first declaration of a function shall specify the 3145 // carries_dependency attribute for its declarator-id if any declaration 3146 // of the function specifies the carries_dependency attribute. 3147 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3148 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3149 Diag(CDA->getLocation(), 3150 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3151 Diag(Old->getFirstDecl()->getLocation(), 3152 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3153 } 3154 3155 // (C++98 8.3.5p3): 3156 // All declarations for a function shall agree exactly in both the 3157 // return type and the parameter-type-list. 3158 // We also want to respect all the extended bits except noreturn. 3159 3160 // noreturn should now match unless the old type info didn't have it. 3161 QualType OldQTypeForComparison = OldQType; 3162 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3163 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3164 const FunctionType *OldTypeForComparison 3165 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3166 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3167 assert(OldQTypeForComparison.isCanonical()); 3168 } 3169 3170 if (haveIncompatibleLanguageLinkages(Old, New)) { 3171 // As a special case, retain the language linkage from previous 3172 // declarations of a friend function as an extension. 3173 // 3174 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3175 // and is useful because there's otherwise no way to specify language 3176 // linkage within class scope. 3177 // 3178 // Check cautiously as the friend object kind isn't yet complete. 3179 if (New->getFriendObjectKind() != Decl::FOK_None) { 3180 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3181 Diag(OldLocation, PrevDiag); 3182 } else { 3183 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3184 Diag(OldLocation, PrevDiag); 3185 return true; 3186 } 3187 } 3188 3189 if (OldQTypeForComparison == NewQType) 3190 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3191 3192 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3193 New->isLocalExternDecl()) { 3194 // It's OK if we couldn't merge types for a local function declaraton 3195 // if either the old or new type is dependent. We'll merge the types 3196 // when we instantiate the function. 3197 return false; 3198 } 3199 3200 // Fall through for conflicting redeclarations and redefinitions. 3201 } 3202 3203 // C: Function types need to be compatible, not identical. This handles 3204 // duplicate function decls like "void f(int); void f(enum X);" properly. 3205 if (!getLangOpts().CPlusPlus && 3206 Context.typesAreCompatible(OldQType, NewQType)) { 3207 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3208 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3209 const FunctionProtoType *OldProto = nullptr; 3210 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3211 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3212 // The old declaration provided a function prototype, but the 3213 // new declaration does not. Merge in the prototype. 3214 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3215 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3216 NewQType = 3217 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3218 OldProto->getExtProtoInfo()); 3219 New->setType(NewQType); 3220 New->setHasInheritedPrototype(); 3221 3222 // Synthesize parameters with the same types. 3223 SmallVector<ParmVarDecl*, 16> Params; 3224 for (const auto &ParamType : OldProto->param_types()) { 3225 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3226 SourceLocation(), nullptr, 3227 ParamType, /*TInfo=*/nullptr, 3228 SC_None, nullptr); 3229 Param->setScopeInfo(0, Params.size()); 3230 Param->setImplicit(); 3231 Params.push_back(Param); 3232 } 3233 3234 New->setParams(Params); 3235 } 3236 3237 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3238 } 3239 3240 // GNU C permits a K&R definition to follow a prototype declaration 3241 // if the declared types of the parameters in the K&R definition 3242 // match the types in the prototype declaration, even when the 3243 // promoted types of the parameters from the K&R definition differ 3244 // from the types in the prototype. GCC then keeps the types from 3245 // the prototype. 3246 // 3247 // If a variadic prototype is followed by a non-variadic K&R definition, 3248 // the K&R definition becomes variadic. This is sort of an edge case, but 3249 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3250 // C99 6.9.1p8. 3251 if (!getLangOpts().CPlusPlus && 3252 Old->hasPrototype() && !New->hasPrototype() && 3253 New->getType()->getAs<FunctionProtoType>() && 3254 Old->getNumParams() == New->getNumParams()) { 3255 SmallVector<QualType, 16> ArgTypes; 3256 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3257 const FunctionProtoType *OldProto 3258 = Old->getType()->getAs<FunctionProtoType>(); 3259 const FunctionProtoType *NewProto 3260 = New->getType()->getAs<FunctionProtoType>(); 3261 3262 // Determine whether this is the GNU C extension. 3263 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3264 NewProto->getReturnType()); 3265 bool LooseCompatible = !MergedReturn.isNull(); 3266 for (unsigned Idx = 0, End = Old->getNumParams(); 3267 LooseCompatible && Idx != End; ++Idx) { 3268 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3269 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3270 if (Context.typesAreCompatible(OldParm->getType(), 3271 NewProto->getParamType(Idx))) { 3272 ArgTypes.push_back(NewParm->getType()); 3273 } else if (Context.typesAreCompatible(OldParm->getType(), 3274 NewParm->getType(), 3275 /*CompareUnqualified=*/true)) { 3276 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3277 NewProto->getParamType(Idx) }; 3278 Warnings.push_back(Warn); 3279 ArgTypes.push_back(NewParm->getType()); 3280 } else 3281 LooseCompatible = false; 3282 } 3283 3284 if (LooseCompatible) { 3285 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3286 Diag(Warnings[Warn].NewParm->getLocation(), 3287 diag::ext_param_promoted_not_compatible_with_prototype) 3288 << Warnings[Warn].PromotedType 3289 << Warnings[Warn].OldParm->getType(); 3290 if (Warnings[Warn].OldParm->getLocation().isValid()) 3291 Diag(Warnings[Warn].OldParm->getLocation(), 3292 diag::note_previous_declaration); 3293 } 3294 3295 if (MergeTypeWithOld) 3296 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3297 OldProto->getExtProtoInfo())); 3298 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3299 } 3300 3301 // Fall through to diagnose conflicting types. 3302 } 3303 3304 // A function that has already been declared has been redeclared or 3305 // defined with a different type; show an appropriate diagnostic. 3306 3307 // If the previous declaration was an implicitly-generated builtin 3308 // declaration, then at the very least we should use a specialized note. 3309 unsigned BuiltinID; 3310 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3311 // If it's actually a library-defined builtin function like 'malloc' 3312 // or 'printf', just warn about the incompatible redeclaration. 3313 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3314 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3315 Diag(OldLocation, diag::note_previous_builtin_declaration) 3316 << Old << Old->getType(); 3317 3318 // If this is a global redeclaration, just forget hereafter 3319 // about the "builtin-ness" of the function. 3320 // 3321 // Doing this for local extern declarations is problematic. If 3322 // the builtin declaration remains visible, a second invalid 3323 // local declaration will produce a hard error; if it doesn't 3324 // remain visible, a single bogus local redeclaration (which is 3325 // actually only a warning) could break all the downstream code. 3326 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3327 New->getIdentifier()->revertBuiltin(); 3328 3329 return false; 3330 } 3331 3332 PrevDiag = diag::note_previous_builtin_declaration; 3333 } 3334 3335 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3336 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3337 return true; 3338 } 3339 3340 /// \brief Completes the merge of two function declarations that are 3341 /// known to be compatible. 3342 /// 3343 /// This routine handles the merging of attributes and other 3344 /// properties of function declarations from the old declaration to 3345 /// the new declaration, once we know that New is in fact a 3346 /// redeclaration of Old. 3347 /// 3348 /// \returns false 3349 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3350 Scope *S, bool MergeTypeWithOld) { 3351 // Merge the attributes 3352 mergeDeclAttributes(New, Old); 3353 3354 // Merge "pure" flag. 3355 if (Old->isPure()) 3356 New->setPure(); 3357 3358 // Merge "used" flag. 3359 if (Old->getMostRecentDecl()->isUsed(false)) 3360 New->setIsUsed(); 3361 3362 // Merge attributes from the parameters. These can mismatch with K&R 3363 // declarations. 3364 if (New->getNumParams() == Old->getNumParams()) 3365 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3366 ParmVarDecl *NewParam = New->getParamDecl(i); 3367 ParmVarDecl *OldParam = Old->getParamDecl(i); 3368 mergeParamDeclAttributes(NewParam, OldParam, *this); 3369 mergeParamDeclTypes(NewParam, OldParam, *this); 3370 } 3371 3372 if (getLangOpts().CPlusPlus) 3373 return MergeCXXFunctionDecl(New, Old, S); 3374 3375 // Merge the function types so the we get the composite types for the return 3376 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3377 // was visible. 3378 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3379 if (!Merged.isNull() && MergeTypeWithOld) 3380 New->setType(Merged); 3381 3382 return false; 3383 } 3384 3385 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3386 ObjCMethodDecl *oldMethod) { 3387 // Merge the attributes, including deprecated/unavailable 3388 AvailabilityMergeKind MergeKind = 3389 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3390 ? AMK_ProtocolImplementation 3391 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3392 : AMK_Override; 3393 3394 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3395 3396 // Merge attributes from the parameters. 3397 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3398 oe = oldMethod->param_end(); 3399 for (ObjCMethodDecl::param_iterator 3400 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3401 ni != ne && oi != oe; ++ni, ++oi) 3402 mergeParamDeclAttributes(*ni, *oi, *this); 3403 3404 CheckObjCMethodOverride(newMethod, oldMethod); 3405 } 3406 3407 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3408 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3409 3410 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3411 ? diag::err_redefinition_different_type 3412 : diag::err_redeclaration_different_type) 3413 << New->getDeclName() << New->getType() << Old->getType(); 3414 3415 diag::kind PrevDiag; 3416 SourceLocation OldLocation; 3417 std::tie(PrevDiag, OldLocation) 3418 = getNoteDiagForInvalidRedeclaration(Old, New); 3419 S.Diag(OldLocation, PrevDiag); 3420 New->setInvalidDecl(); 3421 } 3422 3423 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3424 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3425 /// emitting diagnostics as appropriate. 3426 /// 3427 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3428 /// to here in AddInitializerToDecl. We can't check them before the initializer 3429 /// is attached. 3430 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3431 bool MergeTypeWithOld) { 3432 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3433 return; 3434 3435 QualType MergedT; 3436 if (getLangOpts().CPlusPlus) { 3437 if (New->getType()->isUndeducedType()) { 3438 // We don't know what the new type is until the initializer is attached. 3439 return; 3440 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3441 // These could still be something that needs exception specs checked. 3442 return MergeVarDeclExceptionSpecs(New, Old); 3443 } 3444 // C++ [basic.link]p10: 3445 // [...] the types specified by all declarations referring to a given 3446 // object or function shall be identical, except that declarations for an 3447 // array object can specify array types that differ by the presence or 3448 // absence of a major array bound (8.3.4). 3449 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3450 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3451 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3452 3453 // We are merging a variable declaration New into Old. If it has an array 3454 // bound, and that bound differs from Old's bound, we should diagnose the 3455 // mismatch. 3456 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3457 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3458 PrevVD = PrevVD->getPreviousDecl()) { 3459 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3460 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3461 continue; 3462 3463 if (!Context.hasSameType(NewArray, PrevVDTy)) 3464 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3465 } 3466 } 3467 3468 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3469 if (Context.hasSameType(OldArray->getElementType(), 3470 NewArray->getElementType())) 3471 MergedT = New->getType(); 3472 } 3473 // FIXME: Check visibility. New is hidden but has a complete type. If New 3474 // has no array bound, it should not inherit one from Old, if Old is not 3475 // visible. 3476 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3477 if (Context.hasSameType(OldArray->getElementType(), 3478 NewArray->getElementType())) 3479 MergedT = Old->getType(); 3480 } 3481 } 3482 else if (New->getType()->isObjCObjectPointerType() && 3483 Old->getType()->isObjCObjectPointerType()) { 3484 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3485 Old->getType()); 3486 } 3487 } else { 3488 // C 6.2.7p2: 3489 // All declarations that refer to the same object or function shall have 3490 // compatible type. 3491 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3492 } 3493 if (MergedT.isNull()) { 3494 // It's OK if we couldn't merge types if either type is dependent, for a 3495 // block-scope variable. In other cases (static data members of class 3496 // templates, variable templates, ...), we require the types to be 3497 // equivalent. 3498 // FIXME: The C++ standard doesn't say anything about this. 3499 if ((New->getType()->isDependentType() || 3500 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3501 // If the old type was dependent, we can't merge with it, so the new type 3502 // becomes dependent for now. We'll reproduce the original type when we 3503 // instantiate the TypeSourceInfo for the variable. 3504 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3505 New->setType(Context.DependentTy); 3506 return; 3507 } 3508 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3509 } 3510 3511 // Don't actually update the type on the new declaration if the old 3512 // declaration was an extern declaration in a different scope. 3513 if (MergeTypeWithOld) 3514 New->setType(MergedT); 3515 } 3516 3517 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3518 LookupResult &Previous) { 3519 // C11 6.2.7p4: 3520 // For an identifier with internal or external linkage declared 3521 // in a scope in which a prior declaration of that identifier is 3522 // visible, if the prior declaration specifies internal or 3523 // external linkage, the type of the identifier at the later 3524 // declaration becomes the composite type. 3525 // 3526 // If the variable isn't visible, we do not merge with its type. 3527 if (Previous.isShadowed()) 3528 return false; 3529 3530 if (S.getLangOpts().CPlusPlus) { 3531 // C++11 [dcl.array]p3: 3532 // If there is a preceding declaration of the entity in the same 3533 // scope in which the bound was specified, an omitted array bound 3534 // is taken to be the same as in that earlier declaration. 3535 return NewVD->isPreviousDeclInSameBlockScope() || 3536 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3537 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3538 } else { 3539 // If the old declaration was function-local, don't merge with its 3540 // type unless we're in the same function. 3541 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3542 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3543 } 3544 } 3545 3546 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3547 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3548 /// situation, merging decls or emitting diagnostics as appropriate. 3549 /// 3550 /// Tentative definition rules (C99 6.9.2p2) are checked by 3551 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3552 /// definitions here, since the initializer hasn't been attached. 3553 /// 3554 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3555 // If the new decl is already invalid, don't do any other checking. 3556 if (New->isInvalidDecl()) 3557 return; 3558 3559 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3560 return; 3561 3562 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3563 3564 // Verify the old decl was also a variable or variable template. 3565 VarDecl *Old = nullptr; 3566 VarTemplateDecl *OldTemplate = nullptr; 3567 if (Previous.isSingleResult()) { 3568 if (NewTemplate) { 3569 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3570 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3571 3572 if (auto *Shadow = 3573 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3574 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3575 return New->setInvalidDecl(); 3576 } else { 3577 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3578 3579 if (auto *Shadow = 3580 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3581 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3582 return New->setInvalidDecl(); 3583 } 3584 } 3585 if (!Old) { 3586 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3587 << New->getDeclName(); 3588 Diag(Previous.getRepresentativeDecl()->getLocation(), 3589 diag::note_previous_definition); 3590 return New->setInvalidDecl(); 3591 } 3592 3593 // Ensure the template parameters are compatible. 3594 if (NewTemplate && 3595 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3596 OldTemplate->getTemplateParameters(), 3597 /*Complain=*/true, TPL_TemplateMatch)) 3598 return New->setInvalidDecl(); 3599 3600 // C++ [class.mem]p1: 3601 // A member shall not be declared twice in the member-specification [...] 3602 // 3603 // Here, we need only consider static data members. 3604 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3605 Diag(New->getLocation(), diag::err_duplicate_member) 3606 << New->getIdentifier(); 3607 Diag(Old->getLocation(), diag::note_previous_declaration); 3608 New->setInvalidDecl(); 3609 } 3610 3611 mergeDeclAttributes(New, Old); 3612 // Warn if an already-declared variable is made a weak_import in a subsequent 3613 // declaration 3614 if (New->hasAttr<WeakImportAttr>() && 3615 Old->getStorageClass() == SC_None && 3616 !Old->hasAttr<WeakImportAttr>()) { 3617 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3618 Diag(Old->getLocation(), diag::note_previous_definition); 3619 // Remove weak_import attribute on new declaration. 3620 New->dropAttr<WeakImportAttr>(); 3621 } 3622 3623 if (New->hasAttr<InternalLinkageAttr>() && 3624 !Old->hasAttr<InternalLinkageAttr>()) { 3625 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3626 << New->getDeclName(); 3627 Diag(Old->getLocation(), diag::note_previous_definition); 3628 New->dropAttr<InternalLinkageAttr>(); 3629 } 3630 3631 // Merge the types. 3632 VarDecl *MostRecent = Old->getMostRecentDecl(); 3633 if (MostRecent != Old) { 3634 MergeVarDeclTypes(New, MostRecent, 3635 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3636 if (New->isInvalidDecl()) 3637 return; 3638 } 3639 3640 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3641 if (New->isInvalidDecl()) 3642 return; 3643 3644 diag::kind PrevDiag; 3645 SourceLocation OldLocation; 3646 std::tie(PrevDiag, OldLocation) = 3647 getNoteDiagForInvalidRedeclaration(Old, New); 3648 3649 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3650 if (New->getStorageClass() == SC_Static && 3651 !New->isStaticDataMember() && 3652 Old->hasExternalFormalLinkage()) { 3653 if (getLangOpts().MicrosoftExt) { 3654 Diag(New->getLocation(), diag::ext_static_non_static) 3655 << New->getDeclName(); 3656 Diag(OldLocation, PrevDiag); 3657 } else { 3658 Diag(New->getLocation(), diag::err_static_non_static) 3659 << New->getDeclName(); 3660 Diag(OldLocation, PrevDiag); 3661 return New->setInvalidDecl(); 3662 } 3663 } 3664 // C99 6.2.2p4: 3665 // For an identifier declared with the storage-class specifier 3666 // extern in a scope in which a prior declaration of that 3667 // identifier is visible,23) if the prior declaration specifies 3668 // internal or external linkage, the linkage of the identifier at 3669 // the later declaration is the same as the linkage specified at 3670 // the prior declaration. If no prior declaration is visible, or 3671 // if the prior declaration specifies no linkage, then the 3672 // identifier has external linkage. 3673 if (New->hasExternalStorage() && Old->hasLinkage()) 3674 /* Okay */; 3675 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3676 !New->isStaticDataMember() && 3677 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3678 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3679 Diag(OldLocation, PrevDiag); 3680 return New->setInvalidDecl(); 3681 } 3682 3683 // Check if extern is followed by non-extern and vice-versa. 3684 if (New->hasExternalStorage() && 3685 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3686 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3687 Diag(OldLocation, PrevDiag); 3688 return New->setInvalidDecl(); 3689 } 3690 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3691 !New->hasExternalStorage()) { 3692 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3693 Diag(OldLocation, PrevDiag); 3694 return New->setInvalidDecl(); 3695 } 3696 3697 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3698 3699 // FIXME: The test for external storage here seems wrong? We still 3700 // need to check for mismatches. 3701 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3702 // Don't complain about out-of-line definitions of static members. 3703 !(Old->getLexicalDeclContext()->isRecord() && 3704 !New->getLexicalDeclContext()->isRecord())) { 3705 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3706 Diag(OldLocation, PrevDiag); 3707 return New->setInvalidDecl(); 3708 } 3709 3710 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3711 if (VarDecl *Def = Old->getDefinition()) { 3712 // C++1z [dcl.fcn.spec]p4: 3713 // If the definition of a variable appears in a translation unit before 3714 // its first declaration as inline, the program is ill-formed. 3715 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3716 Diag(Def->getLocation(), diag::note_previous_definition); 3717 } 3718 } 3719 3720 // If this redeclaration makes the function inline, we may need to add it to 3721 // UndefinedButUsed. 3722 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3723 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3724 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3725 SourceLocation())); 3726 3727 if (New->getTLSKind() != Old->getTLSKind()) { 3728 if (!Old->getTLSKind()) { 3729 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3730 Diag(OldLocation, PrevDiag); 3731 } else if (!New->getTLSKind()) { 3732 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3733 Diag(OldLocation, PrevDiag); 3734 } else { 3735 // Do not allow redeclaration to change the variable between requiring 3736 // static and dynamic initialization. 3737 // FIXME: GCC allows this, but uses the TLS keyword on the first 3738 // declaration to determine the kind. Do we need to be compatible here? 3739 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3740 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3741 Diag(OldLocation, PrevDiag); 3742 } 3743 } 3744 3745 // C++ doesn't have tentative definitions, so go right ahead and check here. 3746 if (getLangOpts().CPlusPlus && 3747 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3748 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3749 Old->getCanonicalDecl()->isConstexpr()) { 3750 // This definition won't be a definition any more once it's been merged. 3751 Diag(New->getLocation(), 3752 diag::warn_deprecated_redundant_constexpr_static_def); 3753 } else if (VarDecl *Def = Old->getDefinition()) { 3754 if (checkVarDeclRedefinition(Def, New)) 3755 return; 3756 } 3757 } 3758 3759 if (haveIncompatibleLanguageLinkages(Old, New)) { 3760 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3761 Diag(OldLocation, PrevDiag); 3762 New->setInvalidDecl(); 3763 return; 3764 } 3765 3766 // Merge "used" flag. 3767 if (Old->getMostRecentDecl()->isUsed(false)) 3768 New->setIsUsed(); 3769 3770 // Keep a chain of previous declarations. 3771 New->setPreviousDecl(Old); 3772 if (NewTemplate) 3773 NewTemplate->setPreviousDecl(OldTemplate); 3774 3775 // Inherit access appropriately. 3776 New->setAccess(Old->getAccess()); 3777 if (NewTemplate) 3778 NewTemplate->setAccess(New->getAccess()); 3779 3780 if (Old->isInline()) 3781 New->setImplicitlyInline(); 3782 } 3783 3784 /// We've just determined that \p Old and \p New both appear to be definitions 3785 /// of the same variable. Either diagnose or fix the problem. 3786 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3787 if (!hasVisibleDefinition(Old) && 3788 (New->getFormalLinkage() == InternalLinkage || 3789 New->isInline() || 3790 New->getDescribedVarTemplate() || 3791 New->getNumTemplateParameterLists() || 3792 New->getDeclContext()->isDependentContext())) { 3793 // The previous definition is hidden, and multiple definitions are 3794 // permitted (in separate TUs). Demote this to a declaration. 3795 New->demoteThisDefinitionToDeclaration(); 3796 3797 // Make the canonical definition visible. 3798 if (auto *OldTD = Old->getDescribedVarTemplate()) 3799 makeMergedDefinitionVisible(OldTD, New->getLocation()); 3800 makeMergedDefinitionVisible(Old, New->getLocation()); 3801 return false; 3802 } else { 3803 Diag(New->getLocation(), diag::err_redefinition) << New; 3804 Diag(Old->getLocation(), diag::note_previous_definition); 3805 New->setInvalidDecl(); 3806 return true; 3807 } 3808 } 3809 3810 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3811 /// no declarator (e.g. "struct foo;") is parsed. 3812 Decl * 3813 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3814 RecordDecl *&AnonRecord) { 3815 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3816 AnonRecord); 3817 } 3818 3819 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3820 // disambiguate entities defined in different scopes. 3821 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3822 // compatibility. 3823 // We will pick our mangling number depending on which version of MSVC is being 3824 // targeted. 3825 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3826 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3827 ? S->getMSCurManglingNumber() 3828 : S->getMSLastManglingNumber(); 3829 } 3830 3831 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3832 if (!Context.getLangOpts().CPlusPlus) 3833 return; 3834 3835 if (isa<CXXRecordDecl>(Tag->getParent())) { 3836 // If this tag is the direct child of a class, number it if 3837 // it is anonymous. 3838 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3839 return; 3840 MangleNumberingContext &MCtx = 3841 Context.getManglingNumberContext(Tag->getParent()); 3842 Context.setManglingNumber( 3843 Tag, MCtx.getManglingNumber( 3844 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3845 return; 3846 } 3847 3848 // If this tag isn't a direct child of a class, number it if it is local. 3849 Decl *ManglingContextDecl; 3850 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3851 Tag->getDeclContext(), ManglingContextDecl)) { 3852 Context.setManglingNumber( 3853 Tag, MCtx->getManglingNumber( 3854 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3855 } 3856 } 3857 3858 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3859 TypedefNameDecl *NewTD) { 3860 if (TagFromDeclSpec->isInvalidDecl()) 3861 return; 3862 3863 // Do nothing if the tag already has a name for linkage purposes. 3864 if (TagFromDeclSpec->hasNameForLinkage()) 3865 return; 3866 3867 // A well-formed anonymous tag must always be a TUK_Definition. 3868 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3869 3870 // The type must match the tag exactly; no qualifiers allowed. 3871 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3872 Context.getTagDeclType(TagFromDeclSpec))) { 3873 if (getLangOpts().CPlusPlus) 3874 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3875 return; 3876 } 3877 3878 // If we've already computed linkage for the anonymous tag, then 3879 // adding a typedef name for the anonymous decl can change that 3880 // linkage, which might be a serious problem. Diagnose this as 3881 // unsupported and ignore the typedef name. TODO: we should 3882 // pursue this as a language defect and establish a formal rule 3883 // for how to handle it. 3884 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3885 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3886 3887 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3888 tagLoc = getLocForEndOfToken(tagLoc); 3889 3890 llvm::SmallString<40> textToInsert; 3891 textToInsert += ' '; 3892 textToInsert += NewTD->getIdentifier()->getName(); 3893 Diag(tagLoc, diag::note_typedef_changes_linkage) 3894 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3895 return; 3896 } 3897 3898 // Otherwise, set this is the anon-decl typedef for the tag. 3899 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3900 } 3901 3902 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3903 switch (T) { 3904 case DeclSpec::TST_class: 3905 return 0; 3906 case DeclSpec::TST_struct: 3907 return 1; 3908 case DeclSpec::TST_interface: 3909 return 2; 3910 case DeclSpec::TST_union: 3911 return 3; 3912 case DeclSpec::TST_enum: 3913 return 4; 3914 default: 3915 llvm_unreachable("unexpected type specifier"); 3916 } 3917 } 3918 3919 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3920 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3921 /// parameters to cope with template friend declarations. 3922 Decl * 3923 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3924 MultiTemplateParamsArg TemplateParams, 3925 bool IsExplicitInstantiation, 3926 RecordDecl *&AnonRecord) { 3927 Decl *TagD = nullptr; 3928 TagDecl *Tag = nullptr; 3929 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3930 DS.getTypeSpecType() == DeclSpec::TST_struct || 3931 DS.getTypeSpecType() == DeclSpec::TST_interface || 3932 DS.getTypeSpecType() == DeclSpec::TST_union || 3933 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3934 TagD = DS.getRepAsDecl(); 3935 3936 if (!TagD) // We probably had an error 3937 return nullptr; 3938 3939 // Note that the above type specs guarantee that the 3940 // type rep is a Decl, whereas in many of the others 3941 // it's a Type. 3942 if (isa<TagDecl>(TagD)) 3943 Tag = cast<TagDecl>(TagD); 3944 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3945 Tag = CTD->getTemplatedDecl(); 3946 } 3947 3948 if (Tag) { 3949 handleTagNumbering(Tag, S); 3950 Tag->setFreeStanding(); 3951 if (Tag->isInvalidDecl()) 3952 return Tag; 3953 } 3954 3955 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3956 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3957 // or incomplete types shall not be restrict-qualified." 3958 if (TypeQuals & DeclSpec::TQ_restrict) 3959 Diag(DS.getRestrictSpecLoc(), 3960 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3961 << DS.getSourceRange(); 3962 } 3963 3964 if (DS.isInlineSpecified()) 3965 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3966 << getLangOpts().CPlusPlus1z; 3967 3968 if (DS.isConstexprSpecified()) { 3969 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3970 // and definitions of functions and variables. 3971 if (Tag) 3972 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3973 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3974 else 3975 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3976 // Don't emit warnings after this error. 3977 return TagD; 3978 } 3979 3980 if (DS.isConceptSpecified()) { 3981 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3982 // either a function concept and its definition or a variable concept and 3983 // its initializer. 3984 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3985 return TagD; 3986 } 3987 3988 DiagnoseFunctionSpecifiers(DS); 3989 3990 if (DS.isFriendSpecified()) { 3991 // If we're dealing with a decl but not a TagDecl, assume that 3992 // whatever routines created it handled the friendship aspect. 3993 if (TagD && !Tag) 3994 return nullptr; 3995 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3996 } 3997 3998 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3999 bool IsExplicitSpecialization = 4000 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4001 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4002 !IsExplicitInstantiation && !IsExplicitSpecialization && 4003 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4004 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4005 // nested-name-specifier unless it is an explicit instantiation 4006 // or an explicit specialization. 4007 // 4008 // FIXME: We allow class template partial specializations here too, per the 4009 // obvious intent of DR1819. 4010 // 4011 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4012 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4013 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4014 return nullptr; 4015 } 4016 4017 // Track whether this decl-specifier declares anything. 4018 bool DeclaresAnything = true; 4019 4020 // Handle anonymous struct definitions. 4021 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4022 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4023 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4024 if (getLangOpts().CPlusPlus || 4025 Record->getDeclContext()->isRecord()) { 4026 // If CurContext is a DeclContext that can contain statements, 4027 // RecursiveASTVisitor won't visit the decls that 4028 // BuildAnonymousStructOrUnion() will put into CurContext. 4029 // Also store them here so that they can be part of the 4030 // DeclStmt that gets created in this case. 4031 // FIXME: Also return the IndirectFieldDecls created by 4032 // BuildAnonymousStructOr union, for the same reason? 4033 if (CurContext->isFunctionOrMethod()) 4034 AnonRecord = Record; 4035 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4036 Context.getPrintingPolicy()); 4037 } 4038 4039 DeclaresAnything = false; 4040 } 4041 } 4042 4043 // C11 6.7.2.1p2: 4044 // A struct-declaration that does not declare an anonymous structure or 4045 // anonymous union shall contain a struct-declarator-list. 4046 // 4047 // This rule also existed in C89 and C99; the grammar for struct-declaration 4048 // did not permit a struct-declaration without a struct-declarator-list. 4049 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4050 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4051 // Check for Microsoft C extension: anonymous struct/union member. 4052 // Handle 2 kinds of anonymous struct/union: 4053 // struct STRUCT; 4054 // union UNION; 4055 // and 4056 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4057 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4058 if ((Tag && Tag->getDeclName()) || 4059 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4060 RecordDecl *Record = nullptr; 4061 if (Tag) 4062 Record = dyn_cast<RecordDecl>(Tag); 4063 else if (const RecordType *RT = 4064 DS.getRepAsType().get()->getAsStructureType()) 4065 Record = RT->getDecl(); 4066 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4067 Record = UT->getDecl(); 4068 4069 if (Record && getLangOpts().MicrosoftExt) { 4070 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4071 << Record->isUnion() << DS.getSourceRange(); 4072 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4073 } 4074 4075 DeclaresAnything = false; 4076 } 4077 } 4078 4079 // Skip all the checks below if we have a type error. 4080 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4081 (TagD && TagD->isInvalidDecl())) 4082 return TagD; 4083 4084 if (getLangOpts().CPlusPlus && 4085 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4086 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4087 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4088 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4089 DeclaresAnything = false; 4090 4091 if (!DS.isMissingDeclaratorOk()) { 4092 // Customize diagnostic for a typedef missing a name. 4093 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4094 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4095 << DS.getSourceRange(); 4096 else 4097 DeclaresAnything = false; 4098 } 4099 4100 if (DS.isModulePrivateSpecified() && 4101 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4102 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4103 << Tag->getTagKind() 4104 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4105 4106 ActOnDocumentableDecl(TagD); 4107 4108 // C 6.7/2: 4109 // A declaration [...] shall declare at least a declarator [...], a tag, 4110 // or the members of an enumeration. 4111 // C++ [dcl.dcl]p3: 4112 // [If there are no declarators], and except for the declaration of an 4113 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4114 // names into the program, or shall redeclare a name introduced by a 4115 // previous declaration. 4116 if (!DeclaresAnything) { 4117 // In C, we allow this as a (popular) extension / bug. Don't bother 4118 // producing further diagnostics for redundant qualifiers after this. 4119 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4120 return TagD; 4121 } 4122 4123 // C++ [dcl.stc]p1: 4124 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4125 // init-declarator-list of the declaration shall not be empty. 4126 // C++ [dcl.fct.spec]p1: 4127 // If a cv-qualifier appears in a decl-specifier-seq, the 4128 // init-declarator-list of the declaration shall not be empty. 4129 // 4130 // Spurious qualifiers here appear to be valid in C. 4131 unsigned DiagID = diag::warn_standalone_specifier; 4132 if (getLangOpts().CPlusPlus) 4133 DiagID = diag::ext_standalone_specifier; 4134 4135 // Note that a linkage-specification sets a storage class, but 4136 // 'extern "C" struct foo;' is actually valid and not theoretically 4137 // useless. 4138 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4139 if (SCS == DeclSpec::SCS_mutable) 4140 // Since mutable is not a viable storage class specifier in C, there is 4141 // no reason to treat it as an extension. Instead, diagnose as an error. 4142 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4143 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4144 Diag(DS.getStorageClassSpecLoc(), DiagID) 4145 << DeclSpec::getSpecifierName(SCS); 4146 } 4147 4148 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4149 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4150 << DeclSpec::getSpecifierName(TSCS); 4151 if (DS.getTypeQualifiers()) { 4152 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4153 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4154 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4155 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4156 // Restrict is covered above. 4157 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4158 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4159 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4160 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4161 } 4162 4163 // Warn about ignored type attributes, for example: 4164 // __attribute__((aligned)) struct A; 4165 // Attributes should be placed after tag to apply to type declaration. 4166 if (!DS.getAttributes().empty()) { 4167 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4168 if (TypeSpecType == DeclSpec::TST_class || 4169 TypeSpecType == DeclSpec::TST_struct || 4170 TypeSpecType == DeclSpec::TST_interface || 4171 TypeSpecType == DeclSpec::TST_union || 4172 TypeSpecType == DeclSpec::TST_enum) { 4173 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4174 attrs = attrs->getNext()) 4175 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4176 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4177 } 4178 } 4179 4180 return TagD; 4181 } 4182 4183 /// We are trying to inject an anonymous member into the given scope; 4184 /// check if there's an existing declaration that can't be overloaded. 4185 /// 4186 /// \return true if this is a forbidden redeclaration 4187 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4188 Scope *S, 4189 DeclContext *Owner, 4190 DeclarationName Name, 4191 SourceLocation NameLoc, 4192 bool IsUnion) { 4193 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4194 Sema::ForRedeclaration); 4195 if (!SemaRef.LookupName(R, S)) return false; 4196 4197 // Pick a representative declaration. 4198 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4199 assert(PrevDecl && "Expected a non-null Decl"); 4200 4201 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4202 return false; 4203 4204 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4205 << IsUnion << Name; 4206 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4207 4208 return true; 4209 } 4210 4211 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4212 /// anonymous struct or union AnonRecord into the owning context Owner 4213 /// and scope S. This routine will be invoked just after we realize 4214 /// that an unnamed union or struct is actually an anonymous union or 4215 /// struct, e.g., 4216 /// 4217 /// @code 4218 /// union { 4219 /// int i; 4220 /// float f; 4221 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4222 /// // f into the surrounding scope.x 4223 /// @endcode 4224 /// 4225 /// This routine is recursive, injecting the names of nested anonymous 4226 /// structs/unions into the owning context and scope as well. 4227 static bool 4228 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4229 RecordDecl *AnonRecord, AccessSpecifier AS, 4230 SmallVectorImpl<NamedDecl *> &Chaining) { 4231 bool Invalid = false; 4232 4233 // Look every FieldDecl and IndirectFieldDecl with a name. 4234 for (auto *D : AnonRecord->decls()) { 4235 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4236 cast<NamedDecl>(D)->getDeclName()) { 4237 ValueDecl *VD = cast<ValueDecl>(D); 4238 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4239 VD->getLocation(), 4240 AnonRecord->isUnion())) { 4241 // C++ [class.union]p2: 4242 // The names of the members of an anonymous union shall be 4243 // distinct from the names of any other entity in the 4244 // scope in which the anonymous union is declared. 4245 Invalid = true; 4246 } else { 4247 // C++ [class.union]p2: 4248 // For the purpose of name lookup, after the anonymous union 4249 // definition, the members of the anonymous union are 4250 // considered to have been defined in the scope in which the 4251 // anonymous union is declared. 4252 unsigned OldChainingSize = Chaining.size(); 4253 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4254 Chaining.append(IF->chain_begin(), IF->chain_end()); 4255 else 4256 Chaining.push_back(VD); 4257 4258 assert(Chaining.size() >= 2); 4259 NamedDecl **NamedChain = 4260 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4261 for (unsigned i = 0; i < Chaining.size(); i++) 4262 NamedChain[i] = Chaining[i]; 4263 4264 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4265 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4266 VD->getType(), {NamedChain, Chaining.size()}); 4267 4268 for (const auto *Attr : VD->attrs()) 4269 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4270 4271 IndirectField->setAccess(AS); 4272 IndirectField->setImplicit(); 4273 SemaRef.PushOnScopeChains(IndirectField, S); 4274 4275 // That includes picking up the appropriate access specifier. 4276 if (AS != AS_none) IndirectField->setAccess(AS); 4277 4278 Chaining.resize(OldChainingSize); 4279 } 4280 } 4281 } 4282 4283 return Invalid; 4284 } 4285 4286 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4287 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4288 /// illegal input values are mapped to SC_None. 4289 static StorageClass 4290 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4291 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4292 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4293 "Parser allowed 'typedef' as storage class VarDecl."); 4294 switch (StorageClassSpec) { 4295 case DeclSpec::SCS_unspecified: return SC_None; 4296 case DeclSpec::SCS_extern: 4297 if (DS.isExternInLinkageSpec()) 4298 return SC_None; 4299 return SC_Extern; 4300 case DeclSpec::SCS_static: return SC_Static; 4301 case DeclSpec::SCS_auto: return SC_Auto; 4302 case DeclSpec::SCS_register: return SC_Register; 4303 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4304 // Illegal SCSs map to None: error reporting is up to the caller. 4305 case DeclSpec::SCS_mutable: // Fall through. 4306 case DeclSpec::SCS_typedef: return SC_None; 4307 } 4308 llvm_unreachable("unknown storage class specifier"); 4309 } 4310 4311 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4312 assert(Record->hasInClassInitializer()); 4313 4314 for (const auto *I : Record->decls()) { 4315 const auto *FD = dyn_cast<FieldDecl>(I); 4316 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4317 FD = IFD->getAnonField(); 4318 if (FD && FD->hasInClassInitializer()) 4319 return FD->getLocation(); 4320 } 4321 4322 llvm_unreachable("couldn't find in-class initializer"); 4323 } 4324 4325 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4326 SourceLocation DefaultInitLoc) { 4327 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4328 return; 4329 4330 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4331 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4332 } 4333 4334 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4335 CXXRecordDecl *AnonUnion) { 4336 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4337 return; 4338 4339 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4340 } 4341 4342 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4343 /// anonymous structure or union. Anonymous unions are a C++ feature 4344 /// (C++ [class.union]) and a C11 feature; anonymous structures 4345 /// are a C11 feature and GNU C++ extension. 4346 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4347 AccessSpecifier AS, 4348 RecordDecl *Record, 4349 const PrintingPolicy &Policy) { 4350 DeclContext *Owner = Record->getDeclContext(); 4351 4352 // Diagnose whether this anonymous struct/union is an extension. 4353 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4354 Diag(Record->getLocation(), diag::ext_anonymous_union); 4355 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4356 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4357 else if (!Record->isUnion() && !getLangOpts().C11) 4358 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4359 4360 // C and C++ require different kinds of checks for anonymous 4361 // structs/unions. 4362 bool Invalid = false; 4363 if (getLangOpts().CPlusPlus) { 4364 const char *PrevSpec = nullptr; 4365 unsigned DiagID; 4366 if (Record->isUnion()) { 4367 // C++ [class.union]p6: 4368 // Anonymous unions declared in a named namespace or in the 4369 // global namespace shall be declared static. 4370 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4371 (isa<TranslationUnitDecl>(Owner) || 4372 (isa<NamespaceDecl>(Owner) && 4373 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4374 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4375 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4376 4377 // Recover by adding 'static'. 4378 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4379 PrevSpec, DiagID, Policy); 4380 } 4381 // C++ [class.union]p6: 4382 // A storage class is not allowed in a declaration of an 4383 // anonymous union in a class scope. 4384 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4385 isa<RecordDecl>(Owner)) { 4386 Diag(DS.getStorageClassSpecLoc(), 4387 diag::err_anonymous_union_with_storage_spec) 4388 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4389 4390 // Recover by removing the storage specifier. 4391 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4392 SourceLocation(), 4393 PrevSpec, DiagID, Context.getPrintingPolicy()); 4394 } 4395 } 4396 4397 // Ignore const/volatile/restrict qualifiers. 4398 if (DS.getTypeQualifiers()) { 4399 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4400 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4401 << Record->isUnion() << "const" 4402 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4403 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4404 Diag(DS.getVolatileSpecLoc(), 4405 diag::ext_anonymous_struct_union_qualified) 4406 << Record->isUnion() << "volatile" 4407 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4408 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4409 Diag(DS.getRestrictSpecLoc(), 4410 diag::ext_anonymous_struct_union_qualified) 4411 << Record->isUnion() << "restrict" 4412 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4413 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4414 Diag(DS.getAtomicSpecLoc(), 4415 diag::ext_anonymous_struct_union_qualified) 4416 << Record->isUnion() << "_Atomic" 4417 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4418 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4419 Diag(DS.getUnalignedSpecLoc(), 4420 diag::ext_anonymous_struct_union_qualified) 4421 << Record->isUnion() << "__unaligned" 4422 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4423 4424 DS.ClearTypeQualifiers(); 4425 } 4426 4427 // C++ [class.union]p2: 4428 // The member-specification of an anonymous union shall only 4429 // define non-static data members. [Note: nested types and 4430 // functions cannot be declared within an anonymous union. ] 4431 for (auto *Mem : Record->decls()) { 4432 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4433 // C++ [class.union]p3: 4434 // An anonymous union shall not have private or protected 4435 // members (clause 11). 4436 assert(FD->getAccess() != AS_none); 4437 if (FD->getAccess() != AS_public) { 4438 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4439 << Record->isUnion() << (FD->getAccess() == AS_protected); 4440 Invalid = true; 4441 } 4442 4443 // C++ [class.union]p1 4444 // An object of a class with a non-trivial constructor, a non-trivial 4445 // copy constructor, a non-trivial destructor, or a non-trivial copy 4446 // assignment operator cannot be a member of a union, nor can an 4447 // array of such objects. 4448 if (CheckNontrivialField(FD)) 4449 Invalid = true; 4450 } else if (Mem->isImplicit()) { 4451 // Any implicit members are fine. 4452 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4453 // This is a type that showed up in an 4454 // elaborated-type-specifier inside the anonymous struct or 4455 // union, but which actually declares a type outside of the 4456 // anonymous struct or union. It's okay. 4457 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4458 if (!MemRecord->isAnonymousStructOrUnion() && 4459 MemRecord->getDeclName()) { 4460 // Visual C++ allows type definition in anonymous struct or union. 4461 if (getLangOpts().MicrosoftExt) 4462 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4463 << Record->isUnion(); 4464 else { 4465 // This is a nested type declaration. 4466 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4467 << Record->isUnion(); 4468 Invalid = true; 4469 } 4470 } else { 4471 // This is an anonymous type definition within another anonymous type. 4472 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4473 // not part of standard C++. 4474 Diag(MemRecord->getLocation(), 4475 diag::ext_anonymous_record_with_anonymous_type) 4476 << Record->isUnion(); 4477 } 4478 } else if (isa<AccessSpecDecl>(Mem)) { 4479 // Any access specifier is fine. 4480 } else if (isa<StaticAssertDecl>(Mem)) { 4481 // In C++1z, static_assert declarations are also fine. 4482 } else { 4483 // We have something that isn't a non-static data 4484 // member. Complain about it. 4485 unsigned DK = diag::err_anonymous_record_bad_member; 4486 if (isa<TypeDecl>(Mem)) 4487 DK = diag::err_anonymous_record_with_type; 4488 else if (isa<FunctionDecl>(Mem)) 4489 DK = diag::err_anonymous_record_with_function; 4490 else if (isa<VarDecl>(Mem)) 4491 DK = diag::err_anonymous_record_with_static; 4492 4493 // Visual C++ allows type definition in anonymous struct or union. 4494 if (getLangOpts().MicrosoftExt && 4495 DK == diag::err_anonymous_record_with_type) 4496 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4497 << Record->isUnion(); 4498 else { 4499 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4500 Invalid = true; 4501 } 4502 } 4503 } 4504 4505 // C++11 [class.union]p8 (DR1460): 4506 // At most one variant member of a union may have a 4507 // brace-or-equal-initializer. 4508 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4509 Owner->isRecord()) 4510 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4511 cast<CXXRecordDecl>(Record)); 4512 } 4513 4514 if (!Record->isUnion() && !Owner->isRecord()) { 4515 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4516 << getLangOpts().CPlusPlus; 4517 Invalid = true; 4518 } 4519 4520 // Mock up a declarator. 4521 Declarator Dc(DS, Declarator::MemberContext); 4522 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4523 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4524 4525 // Create a declaration for this anonymous struct/union. 4526 NamedDecl *Anon = nullptr; 4527 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4528 Anon = FieldDecl::Create(Context, OwningClass, 4529 DS.getLocStart(), 4530 Record->getLocation(), 4531 /*IdentifierInfo=*/nullptr, 4532 Context.getTypeDeclType(Record), 4533 TInfo, 4534 /*BitWidth=*/nullptr, /*Mutable=*/false, 4535 /*InitStyle=*/ICIS_NoInit); 4536 Anon->setAccess(AS); 4537 if (getLangOpts().CPlusPlus) 4538 FieldCollector->Add(cast<FieldDecl>(Anon)); 4539 } else { 4540 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4541 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4542 if (SCSpec == DeclSpec::SCS_mutable) { 4543 // mutable can only appear on non-static class members, so it's always 4544 // an error here 4545 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4546 Invalid = true; 4547 SC = SC_None; 4548 } 4549 4550 Anon = VarDecl::Create(Context, Owner, 4551 DS.getLocStart(), 4552 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4553 Context.getTypeDeclType(Record), 4554 TInfo, SC); 4555 4556 // Default-initialize the implicit variable. This initialization will be 4557 // trivial in almost all cases, except if a union member has an in-class 4558 // initializer: 4559 // union { int n = 0; }; 4560 ActOnUninitializedDecl(Anon); 4561 } 4562 Anon->setImplicit(); 4563 4564 // Mark this as an anonymous struct/union type. 4565 Record->setAnonymousStructOrUnion(true); 4566 4567 // Add the anonymous struct/union object to the current 4568 // context. We'll be referencing this object when we refer to one of 4569 // its members. 4570 Owner->addDecl(Anon); 4571 4572 // Inject the members of the anonymous struct/union into the owning 4573 // context and into the identifier resolver chain for name lookup 4574 // purposes. 4575 SmallVector<NamedDecl*, 2> Chain; 4576 Chain.push_back(Anon); 4577 4578 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4579 Invalid = true; 4580 4581 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4582 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4583 Decl *ManglingContextDecl; 4584 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4585 NewVD->getDeclContext(), ManglingContextDecl)) { 4586 Context.setManglingNumber( 4587 NewVD, MCtx->getManglingNumber( 4588 NewVD, getMSManglingNumber(getLangOpts(), S))); 4589 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4590 } 4591 } 4592 } 4593 4594 if (Invalid) 4595 Anon->setInvalidDecl(); 4596 4597 return Anon; 4598 } 4599 4600 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4601 /// Microsoft C anonymous structure. 4602 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4603 /// Example: 4604 /// 4605 /// struct A { int a; }; 4606 /// struct B { struct A; int b; }; 4607 /// 4608 /// void foo() { 4609 /// B var; 4610 /// var.a = 3; 4611 /// } 4612 /// 4613 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4614 RecordDecl *Record) { 4615 assert(Record && "expected a record!"); 4616 4617 // Mock up a declarator. 4618 Declarator Dc(DS, Declarator::TypeNameContext); 4619 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4620 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4621 4622 auto *ParentDecl = cast<RecordDecl>(CurContext); 4623 QualType RecTy = Context.getTypeDeclType(Record); 4624 4625 // Create a declaration for this anonymous struct. 4626 NamedDecl *Anon = FieldDecl::Create(Context, 4627 ParentDecl, 4628 DS.getLocStart(), 4629 DS.getLocStart(), 4630 /*IdentifierInfo=*/nullptr, 4631 RecTy, 4632 TInfo, 4633 /*BitWidth=*/nullptr, /*Mutable=*/false, 4634 /*InitStyle=*/ICIS_NoInit); 4635 Anon->setImplicit(); 4636 4637 // Add the anonymous struct object to the current context. 4638 CurContext->addDecl(Anon); 4639 4640 // Inject the members of the anonymous struct into the current 4641 // context and into the identifier resolver chain for name lookup 4642 // purposes. 4643 SmallVector<NamedDecl*, 2> Chain; 4644 Chain.push_back(Anon); 4645 4646 RecordDecl *RecordDef = Record->getDefinition(); 4647 if (RequireCompleteType(Anon->getLocation(), RecTy, 4648 diag::err_field_incomplete) || 4649 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4650 AS_none, Chain)) { 4651 Anon->setInvalidDecl(); 4652 ParentDecl->setInvalidDecl(); 4653 } 4654 4655 return Anon; 4656 } 4657 4658 /// GetNameForDeclarator - Determine the full declaration name for the 4659 /// given Declarator. 4660 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4661 return GetNameFromUnqualifiedId(D.getName()); 4662 } 4663 4664 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4665 DeclarationNameInfo 4666 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4667 DeclarationNameInfo NameInfo; 4668 NameInfo.setLoc(Name.StartLocation); 4669 4670 switch (Name.getKind()) { 4671 4672 case UnqualifiedId::IK_ImplicitSelfParam: 4673 case UnqualifiedId::IK_Identifier: 4674 NameInfo.setName(Name.Identifier); 4675 NameInfo.setLoc(Name.StartLocation); 4676 return NameInfo; 4677 4678 case UnqualifiedId::IK_DeductionGuideName: { 4679 // C++ [temp.deduct.guide]p3: 4680 // The simple-template-id shall name a class template specialization. 4681 // The template-name shall be the same identifier as the template-name 4682 // of the simple-template-id. 4683 // These together intend to imply that the template-name shall name a 4684 // class template. 4685 // FIXME: template<typename T> struct X {}; 4686 // template<typename T> using Y = X<T>; 4687 // Y(int) -> Y<int>; 4688 // satisfies these rules but does not name a class template. 4689 TemplateName TN = Name.TemplateName.get().get(); 4690 auto *Template = TN.getAsTemplateDecl(); 4691 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4692 Diag(Name.StartLocation, 4693 diag::err_deduction_guide_name_not_class_template) 4694 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4695 if (Template) 4696 Diag(Template->getLocation(), diag::note_template_decl_here); 4697 return DeclarationNameInfo(); 4698 } 4699 4700 NameInfo.setName( 4701 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4702 NameInfo.setLoc(Name.StartLocation); 4703 return NameInfo; 4704 } 4705 4706 case UnqualifiedId::IK_OperatorFunctionId: 4707 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4708 Name.OperatorFunctionId.Operator)); 4709 NameInfo.setLoc(Name.StartLocation); 4710 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4711 = Name.OperatorFunctionId.SymbolLocations[0]; 4712 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4713 = Name.EndLocation.getRawEncoding(); 4714 return NameInfo; 4715 4716 case UnqualifiedId::IK_LiteralOperatorId: 4717 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4718 Name.Identifier)); 4719 NameInfo.setLoc(Name.StartLocation); 4720 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4721 return NameInfo; 4722 4723 case UnqualifiedId::IK_ConversionFunctionId: { 4724 TypeSourceInfo *TInfo; 4725 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4726 if (Ty.isNull()) 4727 return DeclarationNameInfo(); 4728 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4729 Context.getCanonicalType(Ty))); 4730 NameInfo.setLoc(Name.StartLocation); 4731 NameInfo.setNamedTypeInfo(TInfo); 4732 return NameInfo; 4733 } 4734 4735 case UnqualifiedId::IK_ConstructorName: { 4736 TypeSourceInfo *TInfo; 4737 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4738 if (Ty.isNull()) 4739 return DeclarationNameInfo(); 4740 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4741 Context.getCanonicalType(Ty))); 4742 NameInfo.setLoc(Name.StartLocation); 4743 NameInfo.setNamedTypeInfo(TInfo); 4744 return NameInfo; 4745 } 4746 4747 case UnqualifiedId::IK_ConstructorTemplateId: { 4748 // In well-formed code, we can only have a constructor 4749 // template-id that refers to the current context, so go there 4750 // to find the actual type being constructed. 4751 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4752 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4753 return DeclarationNameInfo(); 4754 4755 // Determine the type of the class being constructed. 4756 QualType CurClassType = Context.getTypeDeclType(CurClass); 4757 4758 // FIXME: Check two things: that the template-id names the same type as 4759 // CurClassType, and that the template-id does not occur when the name 4760 // was qualified. 4761 4762 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4763 Context.getCanonicalType(CurClassType))); 4764 NameInfo.setLoc(Name.StartLocation); 4765 // FIXME: should we retrieve TypeSourceInfo? 4766 NameInfo.setNamedTypeInfo(nullptr); 4767 return NameInfo; 4768 } 4769 4770 case UnqualifiedId::IK_DestructorName: { 4771 TypeSourceInfo *TInfo; 4772 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4773 if (Ty.isNull()) 4774 return DeclarationNameInfo(); 4775 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4776 Context.getCanonicalType(Ty))); 4777 NameInfo.setLoc(Name.StartLocation); 4778 NameInfo.setNamedTypeInfo(TInfo); 4779 return NameInfo; 4780 } 4781 4782 case UnqualifiedId::IK_TemplateId: { 4783 TemplateName TName = Name.TemplateId->Template.get(); 4784 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4785 return Context.getNameForTemplate(TName, TNameLoc); 4786 } 4787 4788 } // switch (Name.getKind()) 4789 4790 llvm_unreachable("Unknown name kind"); 4791 } 4792 4793 static QualType getCoreType(QualType Ty) { 4794 do { 4795 if (Ty->isPointerType() || Ty->isReferenceType()) 4796 Ty = Ty->getPointeeType(); 4797 else if (Ty->isArrayType()) 4798 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4799 else 4800 return Ty.withoutLocalFastQualifiers(); 4801 } while (true); 4802 } 4803 4804 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4805 /// and Definition have "nearly" matching parameters. This heuristic is 4806 /// used to improve diagnostics in the case where an out-of-line function 4807 /// definition doesn't match any declaration within the class or namespace. 4808 /// Also sets Params to the list of indices to the parameters that differ 4809 /// between the declaration and the definition. If hasSimilarParameters 4810 /// returns true and Params is empty, then all of the parameters match. 4811 static bool hasSimilarParameters(ASTContext &Context, 4812 FunctionDecl *Declaration, 4813 FunctionDecl *Definition, 4814 SmallVectorImpl<unsigned> &Params) { 4815 Params.clear(); 4816 if (Declaration->param_size() != Definition->param_size()) 4817 return false; 4818 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4819 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4820 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4821 4822 // The parameter types are identical 4823 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4824 continue; 4825 4826 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4827 QualType DefParamBaseTy = getCoreType(DefParamTy); 4828 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4829 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4830 4831 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4832 (DeclTyName && DeclTyName == DefTyName)) 4833 Params.push_back(Idx); 4834 else // The two parameters aren't even close 4835 return false; 4836 } 4837 4838 return true; 4839 } 4840 4841 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4842 /// declarator needs to be rebuilt in the current instantiation. 4843 /// Any bits of declarator which appear before the name are valid for 4844 /// consideration here. That's specifically the type in the decl spec 4845 /// and the base type in any member-pointer chunks. 4846 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4847 DeclarationName Name) { 4848 // The types we specifically need to rebuild are: 4849 // - typenames, typeofs, and decltypes 4850 // - types which will become injected class names 4851 // Of course, we also need to rebuild any type referencing such a 4852 // type. It's safest to just say "dependent", but we call out a 4853 // few cases here. 4854 4855 DeclSpec &DS = D.getMutableDeclSpec(); 4856 switch (DS.getTypeSpecType()) { 4857 case DeclSpec::TST_typename: 4858 case DeclSpec::TST_typeofType: 4859 case DeclSpec::TST_underlyingType: 4860 case DeclSpec::TST_atomic: { 4861 // Grab the type from the parser. 4862 TypeSourceInfo *TSI = nullptr; 4863 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4864 if (T.isNull() || !T->isDependentType()) break; 4865 4866 // Make sure there's a type source info. This isn't really much 4867 // of a waste; most dependent types should have type source info 4868 // attached already. 4869 if (!TSI) 4870 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4871 4872 // Rebuild the type in the current instantiation. 4873 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4874 if (!TSI) return true; 4875 4876 // Store the new type back in the decl spec. 4877 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4878 DS.UpdateTypeRep(LocType); 4879 break; 4880 } 4881 4882 case DeclSpec::TST_decltype: 4883 case DeclSpec::TST_typeofExpr: { 4884 Expr *E = DS.getRepAsExpr(); 4885 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4886 if (Result.isInvalid()) return true; 4887 DS.UpdateExprRep(Result.get()); 4888 break; 4889 } 4890 4891 default: 4892 // Nothing to do for these decl specs. 4893 break; 4894 } 4895 4896 // It doesn't matter what order we do this in. 4897 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4898 DeclaratorChunk &Chunk = D.getTypeObject(I); 4899 4900 // The only type information in the declarator which can come 4901 // before the declaration name is the base type of a member 4902 // pointer. 4903 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4904 continue; 4905 4906 // Rebuild the scope specifier in-place. 4907 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4908 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4909 return true; 4910 } 4911 4912 return false; 4913 } 4914 4915 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4916 D.setFunctionDefinitionKind(FDK_Declaration); 4917 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4918 4919 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4920 Dcl && Dcl->getDeclContext()->isFileContext()) 4921 Dcl->setTopLevelDeclInObjCContainer(); 4922 4923 if (getLangOpts().OpenCL) 4924 setCurrentOpenCLExtensionForDecl(Dcl); 4925 4926 return Dcl; 4927 } 4928 4929 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4930 /// If T is the name of a class, then each of the following shall have a 4931 /// name different from T: 4932 /// - every static data member of class T; 4933 /// - every member function of class T 4934 /// - every member of class T that is itself a type; 4935 /// \returns true if the declaration name violates these rules. 4936 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4937 DeclarationNameInfo NameInfo) { 4938 DeclarationName Name = NameInfo.getName(); 4939 4940 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4941 while (Record && Record->isAnonymousStructOrUnion()) 4942 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4943 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4944 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4945 return true; 4946 } 4947 4948 return false; 4949 } 4950 4951 /// \brief Diagnose a declaration whose declarator-id has the given 4952 /// nested-name-specifier. 4953 /// 4954 /// \param SS The nested-name-specifier of the declarator-id. 4955 /// 4956 /// \param DC The declaration context to which the nested-name-specifier 4957 /// resolves. 4958 /// 4959 /// \param Name The name of the entity being declared. 4960 /// 4961 /// \param Loc The location of the name of the entity being declared. 4962 /// 4963 /// \returns true if we cannot safely recover from this error, false otherwise. 4964 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4965 DeclarationName Name, 4966 SourceLocation Loc) { 4967 DeclContext *Cur = CurContext; 4968 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4969 Cur = Cur->getParent(); 4970 4971 // If the user provided a superfluous scope specifier that refers back to the 4972 // class in which the entity is already declared, diagnose and ignore it. 4973 // 4974 // class X { 4975 // void X::f(); 4976 // }; 4977 // 4978 // Note, it was once ill-formed to give redundant qualification in all 4979 // contexts, but that rule was removed by DR482. 4980 if (Cur->Equals(DC)) { 4981 if (Cur->isRecord()) { 4982 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4983 : diag::err_member_extra_qualification) 4984 << Name << FixItHint::CreateRemoval(SS.getRange()); 4985 SS.clear(); 4986 } else { 4987 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4988 } 4989 return false; 4990 } 4991 4992 // Check whether the qualifying scope encloses the scope of the original 4993 // declaration. 4994 if (!Cur->Encloses(DC)) { 4995 if (Cur->isRecord()) 4996 Diag(Loc, diag::err_member_qualification) 4997 << Name << SS.getRange(); 4998 else if (isa<TranslationUnitDecl>(DC)) 4999 Diag(Loc, diag::err_invalid_declarator_global_scope) 5000 << Name << SS.getRange(); 5001 else if (isa<FunctionDecl>(Cur)) 5002 Diag(Loc, diag::err_invalid_declarator_in_function) 5003 << Name << SS.getRange(); 5004 else if (isa<BlockDecl>(Cur)) 5005 Diag(Loc, diag::err_invalid_declarator_in_block) 5006 << Name << SS.getRange(); 5007 else 5008 Diag(Loc, diag::err_invalid_declarator_scope) 5009 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5010 5011 return true; 5012 } 5013 5014 if (Cur->isRecord()) { 5015 // Cannot qualify members within a class. 5016 Diag(Loc, diag::err_member_qualification) 5017 << Name << SS.getRange(); 5018 SS.clear(); 5019 5020 // C++ constructors and destructors with incorrect scopes can break 5021 // our AST invariants by having the wrong underlying types. If 5022 // that's the case, then drop this declaration entirely. 5023 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5024 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5025 !Context.hasSameType(Name.getCXXNameType(), 5026 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5027 return true; 5028 5029 return false; 5030 } 5031 5032 // C++11 [dcl.meaning]p1: 5033 // [...] "The nested-name-specifier of the qualified declarator-id shall 5034 // not begin with a decltype-specifer" 5035 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5036 while (SpecLoc.getPrefix()) 5037 SpecLoc = SpecLoc.getPrefix(); 5038 if (dyn_cast_or_null<DecltypeType>( 5039 SpecLoc.getNestedNameSpecifier()->getAsType())) 5040 Diag(Loc, diag::err_decltype_in_declarator) 5041 << SpecLoc.getTypeLoc().getSourceRange(); 5042 5043 return false; 5044 } 5045 5046 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5047 MultiTemplateParamsArg TemplateParamLists) { 5048 // TODO: consider using NameInfo for diagnostic. 5049 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5050 DeclarationName Name = NameInfo.getName(); 5051 5052 // All of these full declarators require an identifier. If it doesn't have 5053 // one, the ParsedFreeStandingDeclSpec action should be used. 5054 if (D.isDecompositionDeclarator()) { 5055 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5056 } else if (!Name) { 5057 if (!D.isInvalidType()) // Reject this if we think it is valid. 5058 Diag(D.getDeclSpec().getLocStart(), 5059 diag::err_declarator_need_ident) 5060 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5061 return nullptr; 5062 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5063 return nullptr; 5064 5065 // The scope passed in may not be a decl scope. Zip up the scope tree until 5066 // we find one that is. 5067 while ((S->getFlags() & Scope::DeclScope) == 0 || 5068 (S->getFlags() & Scope::TemplateParamScope) != 0) 5069 S = S->getParent(); 5070 5071 DeclContext *DC = CurContext; 5072 if (D.getCXXScopeSpec().isInvalid()) 5073 D.setInvalidType(); 5074 else if (D.getCXXScopeSpec().isSet()) { 5075 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5076 UPPC_DeclarationQualifier)) 5077 return nullptr; 5078 5079 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5080 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5081 if (!DC || isa<EnumDecl>(DC)) { 5082 // If we could not compute the declaration context, it's because the 5083 // declaration context is dependent but does not refer to a class, 5084 // class template, or class template partial specialization. Complain 5085 // and return early, to avoid the coming semantic disaster. 5086 Diag(D.getIdentifierLoc(), 5087 diag::err_template_qualified_declarator_no_match) 5088 << D.getCXXScopeSpec().getScopeRep() 5089 << D.getCXXScopeSpec().getRange(); 5090 return nullptr; 5091 } 5092 bool IsDependentContext = DC->isDependentContext(); 5093 5094 if (!IsDependentContext && 5095 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5096 return nullptr; 5097 5098 // If a class is incomplete, do not parse entities inside it. 5099 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5100 Diag(D.getIdentifierLoc(), 5101 diag::err_member_def_undefined_record) 5102 << Name << DC << D.getCXXScopeSpec().getRange(); 5103 return nullptr; 5104 } 5105 if (!D.getDeclSpec().isFriendSpecified()) { 5106 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5107 Name, D.getIdentifierLoc())) { 5108 if (DC->isRecord()) 5109 return nullptr; 5110 5111 D.setInvalidType(); 5112 } 5113 } 5114 5115 // Check whether we need to rebuild the type of the given 5116 // declaration in the current instantiation. 5117 if (EnteringContext && IsDependentContext && 5118 TemplateParamLists.size() != 0) { 5119 ContextRAII SavedContext(*this, DC); 5120 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5121 D.setInvalidType(); 5122 } 5123 } 5124 5125 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5126 QualType R = TInfo->getType(); 5127 5128 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5129 // If this is a typedef, we'll end up spewing multiple diagnostics. 5130 // Just return early; it's safer. If this is a function, let the 5131 // "constructor cannot have a return type" diagnostic handle it. 5132 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5133 return nullptr; 5134 5135 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5136 UPPC_DeclarationType)) 5137 D.setInvalidType(); 5138 5139 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5140 ForRedeclaration); 5141 5142 // See if this is a redefinition of a variable in the same scope. 5143 if (!D.getCXXScopeSpec().isSet()) { 5144 bool IsLinkageLookup = false; 5145 bool CreateBuiltins = false; 5146 5147 // If the declaration we're planning to build will be a function 5148 // or object with linkage, then look for another declaration with 5149 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5150 // 5151 // If the declaration we're planning to build will be declared with 5152 // external linkage in the translation unit, create any builtin with 5153 // the same name. 5154 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5155 /* Do nothing*/; 5156 else if (CurContext->isFunctionOrMethod() && 5157 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5158 R->isFunctionType())) { 5159 IsLinkageLookup = true; 5160 CreateBuiltins = 5161 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5162 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5163 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5164 CreateBuiltins = true; 5165 5166 if (IsLinkageLookup) 5167 Previous.clear(LookupRedeclarationWithLinkage); 5168 5169 LookupName(Previous, S, CreateBuiltins); 5170 } else { // Something like "int foo::x;" 5171 LookupQualifiedName(Previous, DC); 5172 5173 // C++ [dcl.meaning]p1: 5174 // When the declarator-id is qualified, the declaration shall refer to a 5175 // previously declared member of the class or namespace to which the 5176 // qualifier refers (or, in the case of a namespace, of an element of the 5177 // inline namespace set of that namespace (7.3.1)) or to a specialization 5178 // thereof; [...] 5179 // 5180 // Note that we already checked the context above, and that we do not have 5181 // enough information to make sure that Previous contains the declaration 5182 // we want to match. For example, given: 5183 // 5184 // class X { 5185 // void f(); 5186 // void f(float); 5187 // }; 5188 // 5189 // void X::f(int) { } // ill-formed 5190 // 5191 // In this case, Previous will point to the overload set 5192 // containing the two f's declared in X, but neither of them 5193 // matches. 5194 5195 // C++ [dcl.meaning]p1: 5196 // [...] the member shall not merely have been introduced by a 5197 // using-declaration in the scope of the class or namespace nominated by 5198 // the nested-name-specifier of the declarator-id. 5199 RemoveUsingDecls(Previous); 5200 } 5201 5202 if (Previous.isSingleResult() && 5203 Previous.getFoundDecl()->isTemplateParameter()) { 5204 // Maybe we will complain about the shadowed template parameter. 5205 if (!D.isInvalidType()) 5206 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5207 Previous.getFoundDecl()); 5208 5209 // Just pretend that we didn't see the previous declaration. 5210 Previous.clear(); 5211 } 5212 5213 // In C++, the previous declaration we find might be a tag type 5214 // (class or enum). In this case, the new declaration will hide the 5215 // tag type. Note that this does does not apply if we're declaring a 5216 // typedef (C++ [dcl.typedef]p4). 5217 if (Previous.isSingleTagDecl() && 5218 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5219 Previous.clear(); 5220 5221 // Check that there are no default arguments other than in the parameters 5222 // of a function declaration (C++ only). 5223 if (getLangOpts().CPlusPlus) 5224 CheckExtraCXXDefaultArguments(D); 5225 5226 if (D.getDeclSpec().isConceptSpecified()) { 5227 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5228 // applied only to the definition of a function template or variable 5229 // template, declared in namespace scope 5230 if (!TemplateParamLists.size()) { 5231 Diag(D.getDeclSpec().getConceptSpecLoc(), 5232 diag:: err_concept_wrong_decl_kind); 5233 return nullptr; 5234 } 5235 5236 if (!DC->getRedeclContext()->isFileContext()) { 5237 Diag(D.getIdentifierLoc(), 5238 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5239 return nullptr; 5240 } 5241 } 5242 5243 NamedDecl *New; 5244 5245 bool AddToScope = true; 5246 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5247 if (TemplateParamLists.size()) { 5248 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5249 return nullptr; 5250 } 5251 5252 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5253 } else if (R->isFunctionType()) { 5254 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5255 TemplateParamLists, 5256 AddToScope); 5257 } else { 5258 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5259 AddToScope); 5260 } 5261 5262 if (!New) 5263 return nullptr; 5264 5265 // If this has an identifier and is not a function template specialization, 5266 // add it to the scope stack. 5267 if (New->getDeclName() && AddToScope) { 5268 // Only make a locally-scoped extern declaration visible if it is the first 5269 // declaration of this entity. Qualified lookup for such an entity should 5270 // only find this declaration if there is no visible declaration of it. 5271 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5272 PushOnScopeChains(New, S, AddToContext); 5273 if (!AddToContext) 5274 CurContext->addHiddenDecl(New); 5275 } 5276 5277 if (isInOpenMPDeclareTargetContext()) 5278 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5279 5280 return New; 5281 } 5282 5283 /// Helper method to turn variable array types into constant array 5284 /// types in certain situations which would otherwise be errors (for 5285 /// GCC compatibility). 5286 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5287 ASTContext &Context, 5288 bool &SizeIsNegative, 5289 llvm::APSInt &Oversized) { 5290 // This method tries to turn a variable array into a constant 5291 // array even when the size isn't an ICE. This is necessary 5292 // for compatibility with code that depends on gcc's buggy 5293 // constant expression folding, like struct {char x[(int)(char*)2];} 5294 SizeIsNegative = false; 5295 Oversized = 0; 5296 5297 if (T->isDependentType()) 5298 return QualType(); 5299 5300 QualifierCollector Qs; 5301 const Type *Ty = Qs.strip(T); 5302 5303 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5304 QualType Pointee = PTy->getPointeeType(); 5305 QualType FixedType = 5306 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5307 Oversized); 5308 if (FixedType.isNull()) return FixedType; 5309 FixedType = Context.getPointerType(FixedType); 5310 return Qs.apply(Context, FixedType); 5311 } 5312 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5313 QualType Inner = PTy->getInnerType(); 5314 QualType FixedType = 5315 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5316 Oversized); 5317 if (FixedType.isNull()) return FixedType; 5318 FixedType = Context.getParenType(FixedType); 5319 return Qs.apply(Context, FixedType); 5320 } 5321 5322 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5323 if (!VLATy) 5324 return QualType(); 5325 // FIXME: We should probably handle this case 5326 if (VLATy->getElementType()->isVariablyModifiedType()) 5327 return QualType(); 5328 5329 llvm::APSInt Res; 5330 if (!VLATy->getSizeExpr() || 5331 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5332 return QualType(); 5333 5334 // Check whether the array size is negative. 5335 if (Res.isSigned() && Res.isNegative()) { 5336 SizeIsNegative = true; 5337 return QualType(); 5338 } 5339 5340 // Check whether the array is too large to be addressed. 5341 unsigned ActiveSizeBits 5342 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5343 Res); 5344 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5345 Oversized = Res; 5346 return QualType(); 5347 } 5348 5349 return Context.getConstantArrayType(VLATy->getElementType(), 5350 Res, ArrayType::Normal, 0); 5351 } 5352 5353 static void 5354 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5355 SrcTL = SrcTL.getUnqualifiedLoc(); 5356 DstTL = DstTL.getUnqualifiedLoc(); 5357 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5358 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5359 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5360 DstPTL.getPointeeLoc()); 5361 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5362 return; 5363 } 5364 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5365 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5366 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5367 DstPTL.getInnerLoc()); 5368 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5369 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5370 return; 5371 } 5372 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5373 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5374 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5375 TypeLoc DstElemTL = DstATL.getElementLoc(); 5376 DstElemTL.initializeFullCopy(SrcElemTL); 5377 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5378 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5379 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5380 } 5381 5382 /// Helper method to turn variable array types into constant array 5383 /// types in certain situations which would otherwise be errors (for 5384 /// GCC compatibility). 5385 static TypeSourceInfo* 5386 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5387 ASTContext &Context, 5388 bool &SizeIsNegative, 5389 llvm::APSInt &Oversized) { 5390 QualType FixedTy 5391 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5392 SizeIsNegative, Oversized); 5393 if (FixedTy.isNull()) 5394 return nullptr; 5395 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5396 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5397 FixedTInfo->getTypeLoc()); 5398 return FixedTInfo; 5399 } 5400 5401 /// \brief Register the given locally-scoped extern "C" declaration so 5402 /// that it can be found later for redeclarations. We include any extern "C" 5403 /// declaration that is not visible in the translation unit here, not just 5404 /// function-scope declarations. 5405 void 5406 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5407 if (!getLangOpts().CPlusPlus && 5408 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5409 // Don't need to track declarations in the TU in C. 5410 return; 5411 5412 // Note that we have a locally-scoped external with this name. 5413 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5414 } 5415 5416 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5417 // FIXME: We can have multiple results via __attribute__((overloadable)). 5418 auto Result = Context.getExternCContextDecl()->lookup(Name); 5419 return Result.empty() ? nullptr : *Result.begin(); 5420 } 5421 5422 /// \brief Diagnose function specifiers on a declaration of an identifier that 5423 /// does not identify a function. 5424 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5425 // FIXME: We should probably indicate the identifier in question to avoid 5426 // confusion for constructs like "virtual int a(), b;" 5427 if (DS.isVirtualSpecified()) 5428 Diag(DS.getVirtualSpecLoc(), 5429 diag::err_virtual_non_function); 5430 5431 if (DS.isExplicitSpecified()) 5432 Diag(DS.getExplicitSpecLoc(), 5433 diag::err_explicit_non_function); 5434 5435 if (DS.isNoreturnSpecified()) 5436 Diag(DS.getNoreturnSpecLoc(), 5437 diag::err_noreturn_non_function); 5438 } 5439 5440 NamedDecl* 5441 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5442 TypeSourceInfo *TInfo, LookupResult &Previous) { 5443 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5444 if (D.getCXXScopeSpec().isSet()) { 5445 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5446 << D.getCXXScopeSpec().getRange(); 5447 D.setInvalidType(); 5448 // Pretend we didn't see the scope specifier. 5449 DC = CurContext; 5450 Previous.clear(); 5451 } 5452 5453 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5454 5455 if (D.getDeclSpec().isInlineSpecified()) 5456 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5457 << getLangOpts().CPlusPlus1z; 5458 if (D.getDeclSpec().isConstexprSpecified()) 5459 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5460 << 1; 5461 if (D.getDeclSpec().isConceptSpecified()) 5462 Diag(D.getDeclSpec().getConceptSpecLoc(), 5463 diag::err_concept_wrong_decl_kind); 5464 5465 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5466 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5467 Diag(D.getName().StartLocation, 5468 diag::err_deduction_guide_invalid_specifier) 5469 << "typedef"; 5470 else 5471 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5472 << D.getName().getSourceRange(); 5473 return nullptr; 5474 } 5475 5476 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5477 if (!NewTD) return nullptr; 5478 5479 // Handle attributes prior to checking for duplicates in MergeVarDecl 5480 ProcessDeclAttributes(S, NewTD, D); 5481 5482 CheckTypedefForVariablyModifiedType(S, NewTD); 5483 5484 bool Redeclaration = D.isRedeclaration(); 5485 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5486 D.setRedeclaration(Redeclaration); 5487 return ND; 5488 } 5489 5490 void 5491 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5492 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5493 // then it shall have block scope. 5494 // Note that variably modified types must be fixed before merging the decl so 5495 // that redeclarations will match. 5496 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5497 QualType T = TInfo->getType(); 5498 if (T->isVariablyModifiedType()) { 5499 getCurFunction()->setHasBranchProtectedScope(); 5500 5501 if (S->getFnParent() == nullptr) { 5502 bool SizeIsNegative; 5503 llvm::APSInt Oversized; 5504 TypeSourceInfo *FixedTInfo = 5505 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5506 SizeIsNegative, 5507 Oversized); 5508 if (FixedTInfo) { 5509 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5510 NewTD->setTypeSourceInfo(FixedTInfo); 5511 } else { 5512 if (SizeIsNegative) 5513 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5514 else if (T->isVariableArrayType()) 5515 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5516 else if (Oversized.getBoolValue()) 5517 Diag(NewTD->getLocation(), diag::err_array_too_large) 5518 << Oversized.toString(10); 5519 else 5520 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5521 NewTD->setInvalidDecl(); 5522 } 5523 } 5524 } 5525 } 5526 5527 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5528 /// declares a typedef-name, either using the 'typedef' type specifier or via 5529 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5530 NamedDecl* 5531 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5532 LookupResult &Previous, bool &Redeclaration) { 5533 // Merge the decl with the existing one if appropriate. If the decl is 5534 // in an outer scope, it isn't the same thing. 5535 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5536 /*AllowInlineNamespace*/false); 5537 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5538 if (!Previous.empty()) { 5539 Redeclaration = true; 5540 MergeTypedefNameDecl(S, NewTD, Previous); 5541 } 5542 5543 // If this is the C FILE type, notify the AST context. 5544 if (IdentifierInfo *II = NewTD->getIdentifier()) 5545 if (!NewTD->isInvalidDecl() && 5546 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5547 if (II->isStr("FILE")) 5548 Context.setFILEDecl(NewTD); 5549 else if (II->isStr("jmp_buf")) 5550 Context.setjmp_bufDecl(NewTD); 5551 else if (II->isStr("sigjmp_buf")) 5552 Context.setsigjmp_bufDecl(NewTD); 5553 else if (II->isStr("ucontext_t")) 5554 Context.setucontext_tDecl(NewTD); 5555 } 5556 5557 return NewTD; 5558 } 5559 5560 /// \brief Determines whether the given declaration is an out-of-scope 5561 /// previous declaration. 5562 /// 5563 /// This routine should be invoked when name lookup has found a 5564 /// previous declaration (PrevDecl) that is not in the scope where a 5565 /// new declaration by the same name is being introduced. If the new 5566 /// declaration occurs in a local scope, previous declarations with 5567 /// linkage may still be considered previous declarations (C99 5568 /// 6.2.2p4-5, C++ [basic.link]p6). 5569 /// 5570 /// \param PrevDecl the previous declaration found by name 5571 /// lookup 5572 /// 5573 /// \param DC the context in which the new declaration is being 5574 /// declared. 5575 /// 5576 /// \returns true if PrevDecl is an out-of-scope previous declaration 5577 /// for a new delcaration with the same name. 5578 static bool 5579 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5580 ASTContext &Context) { 5581 if (!PrevDecl) 5582 return false; 5583 5584 if (!PrevDecl->hasLinkage()) 5585 return false; 5586 5587 if (Context.getLangOpts().CPlusPlus) { 5588 // C++ [basic.link]p6: 5589 // If there is a visible declaration of an entity with linkage 5590 // having the same name and type, ignoring entities declared 5591 // outside the innermost enclosing namespace scope, the block 5592 // scope declaration declares that same entity and receives the 5593 // linkage of the previous declaration. 5594 DeclContext *OuterContext = DC->getRedeclContext(); 5595 if (!OuterContext->isFunctionOrMethod()) 5596 // This rule only applies to block-scope declarations. 5597 return false; 5598 5599 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5600 if (PrevOuterContext->isRecord()) 5601 // We found a member function: ignore it. 5602 return false; 5603 5604 // Find the innermost enclosing namespace for the new and 5605 // previous declarations. 5606 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5607 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5608 5609 // The previous declaration is in a different namespace, so it 5610 // isn't the same function. 5611 if (!OuterContext->Equals(PrevOuterContext)) 5612 return false; 5613 } 5614 5615 return true; 5616 } 5617 5618 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5619 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5620 if (!SS.isSet()) return; 5621 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5622 } 5623 5624 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5625 QualType type = decl->getType(); 5626 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5627 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5628 // Various kinds of declaration aren't allowed to be __autoreleasing. 5629 unsigned kind = -1U; 5630 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5631 if (var->hasAttr<BlocksAttr>()) 5632 kind = 0; // __block 5633 else if (!var->hasLocalStorage()) 5634 kind = 1; // global 5635 } else if (isa<ObjCIvarDecl>(decl)) { 5636 kind = 3; // ivar 5637 } else if (isa<FieldDecl>(decl)) { 5638 kind = 2; // field 5639 } 5640 5641 if (kind != -1U) { 5642 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5643 << kind; 5644 } 5645 } else if (lifetime == Qualifiers::OCL_None) { 5646 // Try to infer lifetime. 5647 if (!type->isObjCLifetimeType()) 5648 return false; 5649 5650 lifetime = type->getObjCARCImplicitLifetime(); 5651 type = Context.getLifetimeQualifiedType(type, lifetime); 5652 decl->setType(type); 5653 } 5654 5655 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5656 // Thread-local variables cannot have lifetime. 5657 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5658 var->getTLSKind()) { 5659 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5660 << var->getType(); 5661 return true; 5662 } 5663 } 5664 5665 return false; 5666 } 5667 5668 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5669 // Ensure that an auto decl is deduced otherwise the checks below might cache 5670 // the wrong linkage. 5671 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5672 5673 // 'weak' only applies to declarations with external linkage. 5674 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5675 if (!ND.isExternallyVisible()) { 5676 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5677 ND.dropAttr<WeakAttr>(); 5678 } 5679 } 5680 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5681 if (ND.isExternallyVisible()) { 5682 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5683 ND.dropAttr<WeakRefAttr>(); 5684 ND.dropAttr<AliasAttr>(); 5685 } 5686 } 5687 5688 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5689 if (VD->hasInit()) { 5690 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5691 assert(VD->isThisDeclarationADefinition() && 5692 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5693 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5694 VD->dropAttr<AliasAttr>(); 5695 } 5696 } 5697 } 5698 5699 // 'selectany' only applies to externally visible variable declarations. 5700 // It does not apply to functions. 5701 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5702 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5703 S.Diag(Attr->getLocation(), 5704 diag::err_attribute_selectany_non_extern_data); 5705 ND.dropAttr<SelectAnyAttr>(); 5706 } 5707 } 5708 5709 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5710 // dll attributes require external linkage. Static locals may have external 5711 // linkage but still cannot be explicitly imported or exported. 5712 auto *VD = dyn_cast<VarDecl>(&ND); 5713 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5714 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5715 << &ND << Attr; 5716 ND.setInvalidDecl(); 5717 } 5718 } 5719 5720 // Virtual functions cannot be marked as 'notail'. 5721 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5722 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5723 if (MD->isVirtual()) { 5724 S.Diag(ND.getLocation(), 5725 diag::err_invalid_attribute_on_virtual_function) 5726 << Attr; 5727 ND.dropAttr<NotTailCalledAttr>(); 5728 } 5729 } 5730 5731 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5732 NamedDecl *NewDecl, 5733 bool IsSpecialization, 5734 bool IsDefinition) { 5735 if (OldDecl->isInvalidDecl()) 5736 return; 5737 5738 bool IsTemplate = false; 5739 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5740 OldDecl = OldTD->getTemplatedDecl(); 5741 IsTemplate = true; 5742 if (!IsSpecialization) 5743 IsDefinition = false; 5744 } 5745 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5746 NewDecl = NewTD->getTemplatedDecl(); 5747 IsTemplate = true; 5748 } 5749 5750 if (!OldDecl || !NewDecl) 5751 return; 5752 5753 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5754 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5755 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5756 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5757 5758 // dllimport and dllexport are inheritable attributes so we have to exclude 5759 // inherited attribute instances. 5760 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5761 (NewExportAttr && !NewExportAttr->isInherited()); 5762 5763 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5764 // the only exception being explicit specializations. 5765 // Implicitly generated declarations are also excluded for now because there 5766 // is no other way to switch these to use dllimport or dllexport. 5767 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5768 5769 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5770 // Allow with a warning for free functions and global variables. 5771 bool JustWarn = false; 5772 if (!OldDecl->isCXXClassMember()) { 5773 auto *VD = dyn_cast<VarDecl>(OldDecl); 5774 if (VD && !VD->getDescribedVarTemplate()) 5775 JustWarn = true; 5776 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5777 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5778 JustWarn = true; 5779 } 5780 5781 // We cannot change a declaration that's been used because IR has already 5782 // been emitted. Dllimported functions will still work though (modulo 5783 // address equality) as they can use the thunk. 5784 if (OldDecl->isUsed()) 5785 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5786 JustWarn = false; 5787 5788 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5789 : diag::err_attribute_dll_redeclaration; 5790 S.Diag(NewDecl->getLocation(), DiagID) 5791 << NewDecl 5792 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5793 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5794 if (!JustWarn) { 5795 NewDecl->setInvalidDecl(); 5796 return; 5797 } 5798 } 5799 5800 // A redeclaration is not allowed to drop a dllimport attribute, the only 5801 // exceptions being inline function definitions (except for function 5802 // templates), local extern declarations, qualified friend declarations or 5803 // special MSVC extension: in the last case, the declaration is treated as if 5804 // it were marked dllexport. 5805 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5806 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5807 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5808 // Ignore static data because out-of-line definitions are diagnosed 5809 // separately. 5810 IsStaticDataMember = VD->isStaticDataMember(); 5811 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5812 VarDecl::DeclarationOnly; 5813 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5814 IsInline = FD->isInlined(); 5815 IsQualifiedFriend = FD->getQualifier() && 5816 FD->getFriendObjectKind() == Decl::FOK_Declared; 5817 } 5818 5819 if (OldImportAttr && !HasNewAttr && 5820 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5821 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5822 if (IsMicrosoft && IsDefinition) { 5823 S.Diag(NewDecl->getLocation(), 5824 diag::warn_redeclaration_without_import_attribute) 5825 << NewDecl; 5826 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5827 NewDecl->dropAttr<DLLImportAttr>(); 5828 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5829 NewImportAttr->getRange(), S.Context, 5830 NewImportAttr->getSpellingListIndex())); 5831 } else { 5832 S.Diag(NewDecl->getLocation(), 5833 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5834 << NewDecl << OldImportAttr; 5835 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5836 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5837 OldDecl->dropAttr<DLLImportAttr>(); 5838 NewDecl->dropAttr<DLLImportAttr>(); 5839 } 5840 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5841 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5842 OldDecl->dropAttr<DLLImportAttr>(); 5843 NewDecl->dropAttr<DLLImportAttr>(); 5844 S.Diag(NewDecl->getLocation(), 5845 diag::warn_dllimport_dropped_from_inline_function) 5846 << NewDecl << OldImportAttr; 5847 } 5848 } 5849 5850 /// Given that we are within the definition of the given function, 5851 /// will that definition behave like C99's 'inline', where the 5852 /// definition is discarded except for optimization purposes? 5853 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5854 // Try to avoid calling GetGVALinkageForFunction. 5855 5856 // All cases of this require the 'inline' keyword. 5857 if (!FD->isInlined()) return false; 5858 5859 // This is only possible in C++ with the gnu_inline attribute. 5860 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5861 return false; 5862 5863 // Okay, go ahead and call the relatively-more-expensive function. 5864 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5865 } 5866 5867 /// Determine whether a variable is extern "C" prior to attaching 5868 /// an initializer. We can't just call isExternC() here, because that 5869 /// will also compute and cache whether the declaration is externally 5870 /// visible, which might change when we attach the initializer. 5871 /// 5872 /// This can only be used if the declaration is known to not be a 5873 /// redeclaration of an internal linkage declaration. 5874 /// 5875 /// For instance: 5876 /// 5877 /// auto x = []{}; 5878 /// 5879 /// Attaching the initializer here makes this declaration not externally 5880 /// visible, because its type has internal linkage. 5881 /// 5882 /// FIXME: This is a hack. 5883 template<typename T> 5884 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5885 if (S.getLangOpts().CPlusPlus) { 5886 // In C++, the overloadable attribute negates the effects of extern "C". 5887 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5888 return false; 5889 5890 // So do CUDA's host/device attributes. 5891 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5892 D->template hasAttr<CUDAHostAttr>())) 5893 return false; 5894 } 5895 return D->isExternC(); 5896 } 5897 5898 static bool shouldConsiderLinkage(const VarDecl *VD) { 5899 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5900 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5901 return VD->hasExternalStorage(); 5902 if (DC->isFileContext()) 5903 return true; 5904 if (DC->isRecord()) 5905 return false; 5906 llvm_unreachable("Unexpected context"); 5907 } 5908 5909 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5910 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5911 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5912 isa<OMPDeclareReductionDecl>(DC)) 5913 return true; 5914 if (DC->isRecord()) 5915 return false; 5916 llvm_unreachable("Unexpected context"); 5917 } 5918 5919 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5920 AttributeList::Kind Kind) { 5921 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5922 if (L->getKind() == Kind) 5923 return true; 5924 return false; 5925 } 5926 5927 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5928 AttributeList::Kind Kind) { 5929 // Check decl attributes on the DeclSpec. 5930 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5931 return true; 5932 5933 // Walk the declarator structure, checking decl attributes that were in a type 5934 // position to the decl itself. 5935 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5936 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5937 return true; 5938 } 5939 5940 // Finally, check attributes on the decl itself. 5941 return hasParsedAttr(S, PD.getAttributes(), Kind); 5942 } 5943 5944 /// Adjust the \c DeclContext for a function or variable that might be a 5945 /// function-local external declaration. 5946 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5947 if (!DC->isFunctionOrMethod()) 5948 return false; 5949 5950 // If this is a local extern function or variable declared within a function 5951 // template, don't add it into the enclosing namespace scope until it is 5952 // instantiated; it might have a dependent type right now. 5953 if (DC->isDependentContext()) 5954 return true; 5955 5956 // C++11 [basic.link]p7: 5957 // When a block scope declaration of an entity with linkage is not found to 5958 // refer to some other declaration, then that entity is a member of the 5959 // innermost enclosing namespace. 5960 // 5961 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5962 // semantically-enclosing namespace, not a lexically-enclosing one. 5963 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5964 DC = DC->getParent(); 5965 return true; 5966 } 5967 5968 /// \brief Returns true if given declaration has external C language linkage. 5969 static bool isDeclExternC(const Decl *D) { 5970 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5971 return FD->isExternC(); 5972 if (const auto *VD = dyn_cast<VarDecl>(D)) 5973 return VD->isExternC(); 5974 5975 llvm_unreachable("Unknown type of decl!"); 5976 } 5977 5978 NamedDecl *Sema::ActOnVariableDeclarator( 5979 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5980 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5981 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5982 QualType R = TInfo->getType(); 5983 DeclarationName Name = GetNameForDeclarator(D).getName(); 5984 5985 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5986 5987 if (D.isDecompositionDeclarator()) { 5988 AddToScope = false; 5989 // Take the name of the first declarator as our name for diagnostic 5990 // purposes. 5991 auto &Decomp = D.getDecompositionDeclarator(); 5992 if (!Decomp.bindings().empty()) { 5993 II = Decomp.bindings()[0].Name; 5994 Name = II; 5995 } 5996 } else if (!II) { 5997 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 5998 return nullptr; 5999 } 6000 6001 if (getLangOpts().OpenCL) { 6002 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6003 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6004 // argument. 6005 if (R->isImageType() || R->isPipeType()) { 6006 Diag(D.getIdentifierLoc(), 6007 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6008 << R; 6009 D.setInvalidType(); 6010 return nullptr; 6011 } 6012 6013 // OpenCL v1.2 s6.9.r: 6014 // The event type cannot be used to declare a program scope variable. 6015 // OpenCL v2.0 s6.9.q: 6016 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6017 if (NULL == S->getParent()) { 6018 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6019 Diag(D.getIdentifierLoc(), 6020 diag::err_invalid_type_for_program_scope_var) << R; 6021 D.setInvalidType(); 6022 return nullptr; 6023 } 6024 } 6025 6026 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6027 QualType NR = R; 6028 while (NR->isPointerType()) { 6029 if (NR->isFunctionPointerType()) { 6030 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 6031 D.setInvalidType(); 6032 break; 6033 } 6034 NR = NR->getPointeeType(); 6035 } 6036 6037 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6038 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6039 // half array type (unless the cl_khr_fp16 extension is enabled). 6040 if (Context.getBaseElementType(R)->isHalfType()) { 6041 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6042 D.setInvalidType(); 6043 } 6044 } 6045 6046 // OpenCL v1.2 s6.9.b p4: 6047 // The sampler type cannot be used with the __local and __global address 6048 // space qualifiers. 6049 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 6050 R.getAddressSpace() == LangAS::opencl_global)) { 6051 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6052 } 6053 6054 // OpenCL v1.2 s6.9.r: 6055 // The event type cannot be used with the __local, __constant and __global 6056 // address space qualifiers. 6057 if (R->isEventT()) { 6058 if (R.getAddressSpace()) { 6059 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6060 D.setInvalidType(); 6061 } 6062 } 6063 } 6064 6065 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6066 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6067 6068 // dllimport globals without explicit storage class are treated as extern. We 6069 // have to change the storage class this early to get the right DeclContext. 6070 if (SC == SC_None && !DC->isRecord() && 6071 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6072 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6073 SC = SC_Extern; 6074 6075 DeclContext *OriginalDC = DC; 6076 bool IsLocalExternDecl = SC == SC_Extern && 6077 adjustContextForLocalExternDecl(DC); 6078 6079 if (SCSpec == DeclSpec::SCS_mutable) { 6080 // mutable can only appear on non-static class members, so it's always 6081 // an error here 6082 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6083 D.setInvalidType(); 6084 SC = SC_None; 6085 } 6086 6087 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6088 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6089 D.getDeclSpec().getStorageClassSpecLoc())) { 6090 // In C++11, the 'register' storage class specifier is deprecated. 6091 // Suppress the warning in system macros, it's used in macros in some 6092 // popular C system headers, such as in glibc's htonl() macro. 6093 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6094 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6095 : diag::warn_deprecated_register) 6096 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6097 } 6098 6099 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6100 6101 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6102 // C99 6.9p2: The storage-class specifiers auto and register shall not 6103 // appear in the declaration specifiers in an external declaration. 6104 // Global Register+Asm is a GNU extension we support. 6105 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6106 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6107 D.setInvalidType(); 6108 } 6109 } 6110 6111 bool IsMemberSpecialization = false; 6112 bool IsVariableTemplateSpecialization = false; 6113 bool IsPartialSpecialization = false; 6114 bool IsVariableTemplate = false; 6115 VarDecl *NewVD = nullptr; 6116 VarTemplateDecl *NewTemplate = nullptr; 6117 TemplateParameterList *TemplateParams = nullptr; 6118 if (!getLangOpts().CPlusPlus) { 6119 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6120 D.getIdentifierLoc(), II, 6121 R, TInfo, SC); 6122 6123 if (R->getContainedDeducedType()) 6124 ParsingInitForAutoVars.insert(NewVD); 6125 6126 if (D.isInvalidType()) 6127 NewVD->setInvalidDecl(); 6128 } else { 6129 bool Invalid = false; 6130 6131 if (DC->isRecord() && !CurContext->isRecord()) { 6132 // This is an out-of-line definition of a static data member. 6133 switch (SC) { 6134 case SC_None: 6135 break; 6136 case SC_Static: 6137 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6138 diag::err_static_out_of_line) 6139 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6140 break; 6141 case SC_Auto: 6142 case SC_Register: 6143 case SC_Extern: 6144 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6145 // to names of variables declared in a block or to function parameters. 6146 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6147 // of class members 6148 6149 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6150 diag::err_storage_class_for_static_member) 6151 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6152 break; 6153 case SC_PrivateExtern: 6154 llvm_unreachable("C storage class in c++!"); 6155 } 6156 } 6157 6158 if (SC == SC_Static && CurContext->isRecord()) { 6159 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6160 if (RD->isLocalClass()) 6161 Diag(D.getIdentifierLoc(), 6162 diag::err_static_data_member_not_allowed_in_local_class) 6163 << Name << RD->getDeclName(); 6164 6165 // C++98 [class.union]p1: If a union contains a static data member, 6166 // the program is ill-formed. C++11 drops this restriction. 6167 if (RD->isUnion()) 6168 Diag(D.getIdentifierLoc(), 6169 getLangOpts().CPlusPlus11 6170 ? diag::warn_cxx98_compat_static_data_member_in_union 6171 : diag::ext_static_data_member_in_union) << Name; 6172 // We conservatively disallow static data members in anonymous structs. 6173 else if (!RD->getDeclName()) 6174 Diag(D.getIdentifierLoc(), 6175 diag::err_static_data_member_not_allowed_in_anon_struct) 6176 << Name << RD->isUnion(); 6177 } 6178 } 6179 6180 // Match up the template parameter lists with the scope specifier, then 6181 // determine whether we have a template or a template specialization. 6182 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6183 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6184 D.getCXXScopeSpec(), 6185 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6186 ? D.getName().TemplateId 6187 : nullptr, 6188 TemplateParamLists, 6189 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6190 6191 if (TemplateParams) { 6192 if (!TemplateParams->size() && 6193 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6194 // There is an extraneous 'template<>' for this variable. Complain 6195 // about it, but allow the declaration of the variable. 6196 Diag(TemplateParams->getTemplateLoc(), 6197 diag::err_template_variable_noparams) 6198 << II 6199 << SourceRange(TemplateParams->getTemplateLoc(), 6200 TemplateParams->getRAngleLoc()); 6201 TemplateParams = nullptr; 6202 } else { 6203 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6204 // This is an explicit specialization or a partial specialization. 6205 // FIXME: Check that we can declare a specialization here. 6206 IsVariableTemplateSpecialization = true; 6207 IsPartialSpecialization = TemplateParams->size() > 0; 6208 } else { // if (TemplateParams->size() > 0) 6209 // This is a template declaration. 6210 IsVariableTemplate = true; 6211 6212 // Check that we can declare a template here. 6213 if (CheckTemplateDeclScope(S, TemplateParams)) 6214 return nullptr; 6215 6216 // Only C++1y supports variable templates (N3651). 6217 Diag(D.getIdentifierLoc(), 6218 getLangOpts().CPlusPlus14 6219 ? diag::warn_cxx11_compat_variable_template 6220 : diag::ext_variable_template); 6221 } 6222 } 6223 } else { 6224 assert( 6225 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6226 "should have a 'template<>' for this decl"); 6227 } 6228 6229 if (IsVariableTemplateSpecialization) { 6230 SourceLocation TemplateKWLoc = 6231 TemplateParamLists.size() > 0 6232 ? TemplateParamLists[0]->getTemplateLoc() 6233 : SourceLocation(); 6234 DeclResult Res = ActOnVarTemplateSpecialization( 6235 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6236 IsPartialSpecialization); 6237 if (Res.isInvalid()) 6238 return nullptr; 6239 NewVD = cast<VarDecl>(Res.get()); 6240 AddToScope = false; 6241 } else if (D.isDecompositionDeclarator()) { 6242 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6243 D.getIdentifierLoc(), R, TInfo, SC, 6244 Bindings); 6245 } else 6246 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6247 D.getIdentifierLoc(), II, R, TInfo, SC); 6248 6249 // If this is supposed to be a variable template, create it as such. 6250 if (IsVariableTemplate) { 6251 NewTemplate = 6252 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6253 TemplateParams, NewVD); 6254 NewVD->setDescribedVarTemplate(NewTemplate); 6255 } 6256 6257 // If this decl has an auto type in need of deduction, make a note of the 6258 // Decl so we can diagnose uses of it in its own initializer. 6259 if (R->getContainedDeducedType()) 6260 ParsingInitForAutoVars.insert(NewVD); 6261 6262 if (D.isInvalidType() || Invalid) { 6263 NewVD->setInvalidDecl(); 6264 if (NewTemplate) 6265 NewTemplate->setInvalidDecl(); 6266 } 6267 6268 SetNestedNameSpecifier(NewVD, D); 6269 6270 // If we have any template parameter lists that don't directly belong to 6271 // the variable (matching the scope specifier), store them. 6272 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6273 if (TemplateParamLists.size() > VDTemplateParamLists) 6274 NewVD->setTemplateParameterListsInfo( 6275 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6276 6277 if (D.getDeclSpec().isConstexprSpecified()) { 6278 NewVD->setConstexpr(true); 6279 // C++1z [dcl.spec.constexpr]p1: 6280 // A static data member declared with the constexpr specifier is 6281 // implicitly an inline variable. 6282 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6283 NewVD->setImplicitlyInline(); 6284 } 6285 6286 if (D.getDeclSpec().isConceptSpecified()) { 6287 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6288 VTD->setConcept(); 6289 6290 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6291 // be declared with the thread_local, inline, friend, or constexpr 6292 // specifiers, [...] 6293 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6294 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6295 diag::err_concept_decl_invalid_specifiers) 6296 << 0 << 0; 6297 NewVD->setInvalidDecl(true); 6298 } 6299 6300 if (D.getDeclSpec().isConstexprSpecified()) { 6301 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6302 diag::err_concept_decl_invalid_specifiers) 6303 << 0 << 3; 6304 NewVD->setInvalidDecl(true); 6305 } 6306 6307 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6308 // applied only to the definition of a function template or variable 6309 // template, declared in namespace scope. 6310 if (IsVariableTemplateSpecialization) { 6311 Diag(D.getDeclSpec().getConceptSpecLoc(), 6312 diag::err_concept_specified_specialization) 6313 << (IsPartialSpecialization ? 2 : 1); 6314 } 6315 6316 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6317 // following restrictions: 6318 // - The declared type shall have the type bool. 6319 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6320 !NewVD->isInvalidDecl()) { 6321 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6322 NewVD->setInvalidDecl(true); 6323 } 6324 } 6325 } 6326 6327 if (D.getDeclSpec().isInlineSpecified()) { 6328 if (!getLangOpts().CPlusPlus) { 6329 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6330 << 0; 6331 } else if (CurContext->isFunctionOrMethod()) { 6332 // 'inline' is not allowed on block scope variable declaration. 6333 Diag(D.getDeclSpec().getInlineSpecLoc(), 6334 diag::err_inline_declaration_block_scope) << Name 6335 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6336 } else { 6337 Diag(D.getDeclSpec().getInlineSpecLoc(), 6338 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6339 : diag::ext_inline_variable); 6340 NewVD->setInlineSpecified(); 6341 } 6342 } 6343 6344 // Set the lexical context. If the declarator has a C++ scope specifier, the 6345 // lexical context will be different from the semantic context. 6346 NewVD->setLexicalDeclContext(CurContext); 6347 if (NewTemplate) 6348 NewTemplate->setLexicalDeclContext(CurContext); 6349 6350 if (IsLocalExternDecl) { 6351 if (D.isDecompositionDeclarator()) 6352 for (auto *B : Bindings) 6353 B->setLocalExternDecl(); 6354 else 6355 NewVD->setLocalExternDecl(); 6356 } 6357 6358 bool EmitTLSUnsupportedError = false; 6359 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6360 // C++11 [dcl.stc]p4: 6361 // When thread_local is applied to a variable of block scope the 6362 // storage-class-specifier static is implied if it does not appear 6363 // explicitly. 6364 // Core issue: 'static' is not implied if the variable is declared 6365 // 'extern'. 6366 if (NewVD->hasLocalStorage() && 6367 (SCSpec != DeclSpec::SCS_unspecified || 6368 TSCS != DeclSpec::TSCS_thread_local || 6369 !DC->isFunctionOrMethod())) 6370 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6371 diag::err_thread_non_global) 6372 << DeclSpec::getSpecifierName(TSCS); 6373 else if (!Context.getTargetInfo().isTLSSupported()) { 6374 if (getLangOpts().CUDA) { 6375 // Postpone error emission until we've collected attributes required to 6376 // figure out whether it's a host or device variable and whether the 6377 // error should be ignored. 6378 EmitTLSUnsupportedError = true; 6379 // We still need to mark the variable as TLS so it shows up in AST with 6380 // proper storage class for other tools to use even if we're not going 6381 // to emit any code for it. 6382 NewVD->setTSCSpec(TSCS); 6383 } else 6384 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6385 diag::err_thread_unsupported); 6386 } else 6387 NewVD->setTSCSpec(TSCS); 6388 } 6389 6390 // C99 6.7.4p3 6391 // An inline definition of a function with external linkage shall 6392 // not contain a definition of a modifiable object with static or 6393 // thread storage duration... 6394 // We only apply this when the function is required to be defined 6395 // elsewhere, i.e. when the function is not 'extern inline'. Note 6396 // that a local variable with thread storage duration still has to 6397 // be marked 'static'. Also note that it's possible to get these 6398 // semantics in C++ using __attribute__((gnu_inline)). 6399 if (SC == SC_Static && S->getFnParent() != nullptr && 6400 !NewVD->getType().isConstQualified()) { 6401 FunctionDecl *CurFD = getCurFunctionDecl(); 6402 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6403 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6404 diag::warn_static_local_in_extern_inline); 6405 MaybeSuggestAddingStaticToDecl(CurFD); 6406 } 6407 } 6408 6409 if (D.getDeclSpec().isModulePrivateSpecified()) { 6410 if (IsVariableTemplateSpecialization) 6411 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6412 << (IsPartialSpecialization ? 1 : 0) 6413 << FixItHint::CreateRemoval( 6414 D.getDeclSpec().getModulePrivateSpecLoc()); 6415 else if (IsMemberSpecialization) 6416 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6417 << 2 6418 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6419 else if (NewVD->hasLocalStorage()) 6420 Diag(NewVD->getLocation(), diag::err_module_private_local) 6421 << 0 << NewVD->getDeclName() 6422 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6423 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6424 else { 6425 NewVD->setModulePrivate(); 6426 if (NewTemplate) 6427 NewTemplate->setModulePrivate(); 6428 for (auto *B : Bindings) 6429 B->setModulePrivate(); 6430 } 6431 } 6432 6433 // Handle attributes prior to checking for duplicates in MergeVarDecl 6434 ProcessDeclAttributes(S, NewVD, D); 6435 6436 if (getLangOpts().CUDA) { 6437 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6438 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6439 diag::err_thread_unsupported); 6440 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6441 // storage [duration]." 6442 if (SC == SC_None && S->getFnParent() != nullptr && 6443 (NewVD->hasAttr<CUDASharedAttr>() || 6444 NewVD->hasAttr<CUDAConstantAttr>())) { 6445 NewVD->setStorageClass(SC_Static); 6446 } 6447 } 6448 6449 // Ensure that dllimport globals without explicit storage class are treated as 6450 // extern. The storage class is set above using parsed attributes. Now we can 6451 // check the VarDecl itself. 6452 assert(!NewVD->hasAttr<DLLImportAttr>() || 6453 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6454 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6455 6456 // In auto-retain/release, infer strong retension for variables of 6457 // retainable type. 6458 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6459 NewVD->setInvalidDecl(); 6460 6461 // Handle GNU asm-label extension (encoded as an attribute). 6462 if (Expr *E = (Expr*)D.getAsmLabel()) { 6463 // The parser guarantees this is a string. 6464 StringLiteral *SE = cast<StringLiteral>(E); 6465 StringRef Label = SE->getString(); 6466 if (S->getFnParent() != nullptr) { 6467 switch (SC) { 6468 case SC_None: 6469 case SC_Auto: 6470 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6471 break; 6472 case SC_Register: 6473 // Local Named register 6474 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6475 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6476 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6477 break; 6478 case SC_Static: 6479 case SC_Extern: 6480 case SC_PrivateExtern: 6481 break; 6482 } 6483 } else if (SC == SC_Register) { 6484 // Global Named register 6485 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6486 const auto &TI = Context.getTargetInfo(); 6487 bool HasSizeMismatch; 6488 6489 if (!TI.isValidGCCRegisterName(Label)) 6490 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6491 else if (!TI.validateGlobalRegisterVariable(Label, 6492 Context.getTypeSize(R), 6493 HasSizeMismatch)) 6494 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6495 else if (HasSizeMismatch) 6496 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6497 } 6498 6499 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6500 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6501 NewVD->setInvalidDecl(true); 6502 } 6503 } 6504 6505 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6506 Context, Label, 0)); 6507 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6508 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6509 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6510 if (I != ExtnameUndeclaredIdentifiers.end()) { 6511 if (isDeclExternC(NewVD)) { 6512 NewVD->addAttr(I->second); 6513 ExtnameUndeclaredIdentifiers.erase(I); 6514 } else 6515 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6516 << /*Variable*/1 << NewVD; 6517 } 6518 } 6519 6520 // Find the shadowed declaration before filtering for scope. 6521 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6522 ? getShadowedDeclaration(NewVD, Previous) 6523 : nullptr; 6524 6525 // Don't consider existing declarations that are in a different 6526 // scope and are out-of-semantic-context declarations (if the new 6527 // declaration has linkage). 6528 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6529 D.getCXXScopeSpec().isNotEmpty() || 6530 IsMemberSpecialization || 6531 IsVariableTemplateSpecialization); 6532 6533 // Check whether the previous declaration is in the same block scope. This 6534 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6535 if (getLangOpts().CPlusPlus && 6536 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6537 NewVD->setPreviousDeclInSameBlockScope( 6538 Previous.isSingleResult() && !Previous.isShadowed() && 6539 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6540 6541 if (!getLangOpts().CPlusPlus) { 6542 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6543 } else { 6544 // If this is an explicit specialization of a static data member, check it. 6545 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6546 CheckMemberSpecialization(NewVD, Previous)) 6547 NewVD->setInvalidDecl(); 6548 6549 // Merge the decl with the existing one if appropriate. 6550 if (!Previous.empty()) { 6551 if (Previous.isSingleResult() && 6552 isa<FieldDecl>(Previous.getFoundDecl()) && 6553 D.getCXXScopeSpec().isSet()) { 6554 // The user tried to define a non-static data member 6555 // out-of-line (C++ [dcl.meaning]p1). 6556 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6557 << D.getCXXScopeSpec().getRange(); 6558 Previous.clear(); 6559 NewVD->setInvalidDecl(); 6560 } 6561 } else if (D.getCXXScopeSpec().isSet()) { 6562 // No previous declaration in the qualifying scope. 6563 Diag(D.getIdentifierLoc(), diag::err_no_member) 6564 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6565 << D.getCXXScopeSpec().getRange(); 6566 NewVD->setInvalidDecl(); 6567 } 6568 6569 if (!IsVariableTemplateSpecialization) 6570 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6571 6572 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6573 // an explicit specialization (14.8.3) or a partial specialization of a 6574 // concept definition. 6575 if (IsVariableTemplateSpecialization && 6576 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6577 Previous.isSingleResult()) { 6578 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6579 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6580 if (VarTmpl->isConcept()) { 6581 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6582 << 1 /*variable*/ 6583 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6584 : 1 /*explicitly specialized*/); 6585 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6586 NewVD->setInvalidDecl(); 6587 } 6588 } 6589 } 6590 6591 if (NewTemplate) { 6592 VarTemplateDecl *PrevVarTemplate = 6593 NewVD->getPreviousDecl() 6594 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6595 : nullptr; 6596 6597 // Check the template parameter list of this declaration, possibly 6598 // merging in the template parameter list from the previous variable 6599 // template declaration. 6600 if (CheckTemplateParameterList( 6601 TemplateParams, 6602 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6603 : nullptr, 6604 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6605 DC->isDependentContext()) 6606 ? TPC_ClassTemplateMember 6607 : TPC_VarTemplate)) 6608 NewVD->setInvalidDecl(); 6609 6610 // If we are providing an explicit specialization of a static variable 6611 // template, make a note of that. 6612 if (PrevVarTemplate && 6613 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6614 PrevVarTemplate->setMemberSpecialization(); 6615 } 6616 } 6617 6618 // Diagnose shadowed variables iff this isn't a redeclaration. 6619 if (ShadowedDecl && !D.isRedeclaration()) 6620 CheckShadow(NewVD, ShadowedDecl, Previous); 6621 6622 ProcessPragmaWeak(S, NewVD); 6623 6624 // If this is the first declaration of an extern C variable, update 6625 // the map of such variables. 6626 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6627 isIncompleteDeclExternC(*this, NewVD)) 6628 RegisterLocallyScopedExternCDecl(NewVD, S); 6629 6630 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6631 Decl *ManglingContextDecl; 6632 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6633 NewVD->getDeclContext(), ManglingContextDecl)) { 6634 Context.setManglingNumber( 6635 NewVD, MCtx->getManglingNumber( 6636 NewVD, getMSManglingNumber(getLangOpts(), S))); 6637 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6638 } 6639 } 6640 6641 // Special handling of variable named 'main'. 6642 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6643 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6644 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6645 6646 // C++ [basic.start.main]p3 6647 // A program that declares a variable main at global scope is ill-formed. 6648 if (getLangOpts().CPlusPlus) 6649 Diag(D.getLocStart(), diag::err_main_global_variable); 6650 6651 // In C, and external-linkage variable named main results in undefined 6652 // behavior. 6653 else if (NewVD->hasExternalFormalLinkage()) 6654 Diag(D.getLocStart(), diag::warn_main_redefined); 6655 } 6656 6657 if (D.isRedeclaration() && !Previous.empty()) { 6658 checkDLLAttributeRedeclaration( 6659 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6660 IsMemberSpecialization, D.isFunctionDefinition()); 6661 } 6662 6663 if (NewTemplate) { 6664 if (NewVD->isInvalidDecl()) 6665 NewTemplate->setInvalidDecl(); 6666 ActOnDocumentableDecl(NewTemplate); 6667 return NewTemplate; 6668 } 6669 6670 return NewVD; 6671 } 6672 6673 /// Enum describing the %select options in diag::warn_decl_shadow. 6674 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6675 6676 /// Determine what kind of declaration we're shadowing. 6677 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6678 const DeclContext *OldDC) { 6679 if (isa<RecordDecl>(OldDC)) 6680 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6681 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6682 } 6683 6684 /// Return the location of the capture if the given lambda captures the given 6685 /// variable \p VD, or an invalid source location otherwise. 6686 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6687 const VarDecl *VD) { 6688 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6689 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6690 return Capture.getLocation(); 6691 } 6692 return SourceLocation(); 6693 } 6694 6695 /// \brief Return the declaration shadowed by the given variable \p D, or null 6696 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6697 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6698 const LookupResult &R) { 6699 // Return if warning is ignored. 6700 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6701 return nullptr; 6702 6703 // Don't diagnose declarations at file scope. 6704 if (D->hasGlobalStorage()) 6705 return nullptr; 6706 6707 // Only diagnose if we're shadowing an unambiguous field or variable. 6708 if (R.getResultKind() != LookupResult::Found) 6709 return nullptr; 6710 6711 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6712 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6713 ? ShadowedDecl 6714 : nullptr; 6715 } 6716 6717 /// \brief Diagnose variable or built-in function shadowing. Implements 6718 /// -Wshadow. 6719 /// 6720 /// This method is called whenever a VarDecl is added to a "useful" 6721 /// scope. 6722 /// 6723 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6724 /// \param R the lookup of the name 6725 /// 6726 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl, 6727 const LookupResult &R) { 6728 DeclContext *NewDC = D->getDeclContext(); 6729 6730 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6731 // Fields are not shadowed by variables in C++ static methods. 6732 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6733 if (MD->isStatic()) 6734 return; 6735 6736 // Fields shadowed by constructor parameters are a special case. Usually 6737 // the constructor initializes the field with the parameter. 6738 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6739 // Remember that this was shadowed so we can either warn about its 6740 // modification or its existence depending on warning settings. 6741 D = D->getCanonicalDecl(); 6742 ShadowingDecls.insert({D, FD}); 6743 return; 6744 } 6745 } 6746 6747 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6748 if (shadowedVar->isExternC()) { 6749 // For shadowing external vars, make sure that we point to the global 6750 // declaration, not a locally scoped extern declaration. 6751 for (auto I : shadowedVar->redecls()) 6752 if (I->isFileVarDecl()) { 6753 ShadowedDecl = I; 6754 break; 6755 } 6756 } 6757 6758 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6759 6760 unsigned WarningDiag = diag::warn_decl_shadow; 6761 SourceLocation CaptureLoc; 6762 if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) { 6763 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6764 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6765 if (RD->getLambdaCaptureDefault() == LCD_None) { 6766 // Try to avoid warnings for lambdas with an explicit capture list. 6767 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6768 // Warn only when the lambda captures the shadowed decl explicitly. 6769 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6770 if (CaptureLoc.isInvalid()) 6771 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6772 } else { 6773 // Remember that this was shadowed so we can avoid the warning if the 6774 // shadowed decl isn't captured and the warning settings allow it. 6775 cast<LambdaScopeInfo>(getCurFunction()) 6776 ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)}); 6777 return; 6778 } 6779 } 6780 } 6781 } 6782 6783 // Only warn about certain kinds of shadowing for class members. 6784 if (NewDC && NewDC->isRecord()) { 6785 // In particular, don't warn about shadowing non-class members. 6786 if (!OldDC->isRecord()) 6787 return; 6788 6789 // TODO: should we warn about static data members shadowing 6790 // static data members from base classes? 6791 6792 // TODO: don't diagnose for inaccessible shadowed members. 6793 // This is hard to do perfectly because we might friend the 6794 // shadowing context, but that's just a false negative. 6795 } 6796 6797 6798 DeclarationName Name = R.getLookupName(); 6799 6800 // Emit warning and note. 6801 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6802 return; 6803 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6804 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6805 if (!CaptureLoc.isInvalid()) 6806 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6807 << Name << /*explicitly*/ 1; 6808 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6809 } 6810 6811 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6812 /// when these variables are captured by the lambda. 6813 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6814 for (const auto &Shadow : LSI->ShadowingDecls) { 6815 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 6816 // Try to avoid the warning when the shadowed decl isn't captured. 6817 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 6818 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6819 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 6820 ? diag::warn_decl_shadow_uncaptured_local 6821 : diag::warn_decl_shadow) 6822 << Shadow.VD->getDeclName() 6823 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 6824 if (!CaptureLoc.isInvalid()) 6825 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6826 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 6827 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6828 } 6829 } 6830 6831 /// \brief Check -Wshadow without the advantage of a previous lookup. 6832 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6833 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6834 return; 6835 6836 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6837 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6838 LookupName(R, S); 6839 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 6840 CheckShadow(D, ShadowedDecl, R); 6841 } 6842 6843 /// Check if 'E', which is an expression that is about to be modified, refers 6844 /// to a constructor parameter that shadows a field. 6845 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6846 // Quickly ignore expressions that can't be shadowing ctor parameters. 6847 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6848 return; 6849 E = E->IgnoreParenImpCasts(); 6850 auto *DRE = dyn_cast<DeclRefExpr>(E); 6851 if (!DRE) 6852 return; 6853 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6854 auto I = ShadowingDecls.find(D); 6855 if (I == ShadowingDecls.end()) 6856 return; 6857 const NamedDecl *ShadowedDecl = I->second; 6858 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6859 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6860 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6861 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6862 6863 // Avoid issuing multiple warnings about the same decl. 6864 ShadowingDecls.erase(I); 6865 } 6866 6867 /// Check for conflict between this global or extern "C" declaration and 6868 /// previous global or extern "C" declarations. This is only used in C++. 6869 template<typename T> 6870 static bool checkGlobalOrExternCConflict( 6871 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6872 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6873 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6874 6875 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6876 // The common case: this global doesn't conflict with any extern "C" 6877 // declaration. 6878 return false; 6879 } 6880 6881 if (Prev) { 6882 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6883 // Both the old and new declarations have C language linkage. This is a 6884 // redeclaration. 6885 Previous.clear(); 6886 Previous.addDecl(Prev); 6887 return true; 6888 } 6889 6890 // This is a global, non-extern "C" declaration, and there is a previous 6891 // non-global extern "C" declaration. Diagnose if this is a variable 6892 // declaration. 6893 if (!isa<VarDecl>(ND)) 6894 return false; 6895 } else { 6896 // The declaration is extern "C". Check for any declaration in the 6897 // translation unit which might conflict. 6898 if (IsGlobal) { 6899 // We have already performed the lookup into the translation unit. 6900 IsGlobal = false; 6901 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6902 I != E; ++I) { 6903 if (isa<VarDecl>(*I)) { 6904 Prev = *I; 6905 break; 6906 } 6907 } 6908 } else { 6909 DeclContext::lookup_result R = 6910 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6911 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6912 I != E; ++I) { 6913 if (isa<VarDecl>(*I)) { 6914 Prev = *I; 6915 break; 6916 } 6917 // FIXME: If we have any other entity with this name in global scope, 6918 // the declaration is ill-formed, but that is a defect: it breaks the 6919 // 'stat' hack, for instance. Only variables can have mangled name 6920 // clashes with extern "C" declarations, so only they deserve a 6921 // diagnostic. 6922 } 6923 } 6924 6925 if (!Prev) 6926 return false; 6927 } 6928 6929 // Use the first declaration's location to ensure we point at something which 6930 // is lexically inside an extern "C" linkage-spec. 6931 assert(Prev && "should have found a previous declaration to diagnose"); 6932 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6933 Prev = FD->getFirstDecl(); 6934 else 6935 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6936 6937 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6938 << IsGlobal << ND; 6939 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6940 << IsGlobal; 6941 return false; 6942 } 6943 6944 /// Apply special rules for handling extern "C" declarations. Returns \c true 6945 /// if we have found that this is a redeclaration of some prior entity. 6946 /// 6947 /// Per C++ [dcl.link]p6: 6948 /// Two declarations [for a function or variable] with C language linkage 6949 /// with the same name that appear in different scopes refer to the same 6950 /// [entity]. An entity with C language linkage shall not be declared with 6951 /// the same name as an entity in global scope. 6952 template<typename T> 6953 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6954 LookupResult &Previous) { 6955 if (!S.getLangOpts().CPlusPlus) { 6956 // In C, when declaring a global variable, look for a corresponding 'extern' 6957 // variable declared in function scope. We don't need this in C++, because 6958 // we find local extern decls in the surrounding file-scope DeclContext. 6959 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6960 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6961 Previous.clear(); 6962 Previous.addDecl(Prev); 6963 return true; 6964 } 6965 } 6966 return false; 6967 } 6968 6969 // A declaration in the translation unit can conflict with an extern "C" 6970 // declaration. 6971 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6972 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6973 6974 // An extern "C" declaration can conflict with a declaration in the 6975 // translation unit or can be a redeclaration of an extern "C" declaration 6976 // in another scope. 6977 if (isIncompleteDeclExternC(S,ND)) 6978 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6979 6980 // Neither global nor extern "C": nothing to do. 6981 return false; 6982 } 6983 6984 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6985 // If the decl is already known invalid, don't check it. 6986 if (NewVD->isInvalidDecl()) 6987 return; 6988 6989 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6990 QualType T = TInfo->getType(); 6991 6992 // Defer checking an 'auto' type until its initializer is attached. 6993 if (T->isUndeducedType()) 6994 return; 6995 6996 if (NewVD->hasAttrs()) 6997 CheckAlignasUnderalignment(NewVD); 6998 6999 if (T->isObjCObjectType()) { 7000 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7001 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7002 T = Context.getObjCObjectPointerType(T); 7003 NewVD->setType(T); 7004 } 7005 7006 // Emit an error if an address space was applied to decl with local storage. 7007 // This includes arrays of objects with address space qualifiers, but not 7008 // automatic variables that point to other address spaces. 7009 // ISO/IEC TR 18037 S5.1.2 7010 if (!getLangOpts().OpenCL 7011 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7012 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 7013 NewVD->setInvalidDecl(); 7014 return; 7015 } 7016 7017 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7018 // scope. 7019 if (getLangOpts().OpenCLVersion == 120 && 7020 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7021 NewVD->isStaticLocal()) { 7022 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7023 NewVD->setInvalidDecl(); 7024 return; 7025 } 7026 7027 if (getLangOpts().OpenCL) { 7028 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7029 if (NewVD->hasAttr<BlocksAttr>()) { 7030 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7031 return; 7032 } 7033 7034 if (T->isBlockPointerType()) { 7035 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7036 // can't use 'extern' storage class. 7037 if (!T.isConstQualified()) { 7038 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7039 << 0 /*const*/; 7040 NewVD->setInvalidDecl(); 7041 return; 7042 } 7043 if (NewVD->hasExternalStorage()) { 7044 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7045 NewVD->setInvalidDecl(); 7046 return; 7047 } 7048 } 7049 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7050 // __constant address space. 7051 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7052 // variables inside a function can also be declared in the global 7053 // address space. 7054 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7055 NewVD->hasExternalStorage()) { 7056 if (!T->isSamplerT() && 7057 !(T.getAddressSpace() == LangAS::opencl_constant || 7058 (T.getAddressSpace() == LangAS::opencl_global && 7059 getLangOpts().OpenCLVersion == 200))) { 7060 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7061 if (getLangOpts().OpenCLVersion == 200) 7062 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7063 << Scope << "global or constant"; 7064 else 7065 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7066 << Scope << "constant"; 7067 NewVD->setInvalidDecl(); 7068 return; 7069 } 7070 } else { 7071 if (T.getAddressSpace() == LangAS::opencl_global) { 7072 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7073 << 1 /*is any function*/ << "global"; 7074 NewVD->setInvalidDecl(); 7075 return; 7076 } 7077 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7078 // in functions. 7079 if (T.getAddressSpace() == LangAS::opencl_constant || 7080 T.getAddressSpace() == LangAS::opencl_local) { 7081 FunctionDecl *FD = getCurFunctionDecl(); 7082 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7083 if (T.getAddressSpace() == LangAS::opencl_constant) 7084 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7085 << 0 /*non-kernel only*/ << "constant"; 7086 else 7087 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7088 << 0 /*non-kernel only*/ << "local"; 7089 NewVD->setInvalidDecl(); 7090 return; 7091 } 7092 } 7093 } 7094 } 7095 7096 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7097 && !NewVD->hasAttr<BlocksAttr>()) { 7098 if (getLangOpts().getGC() != LangOptions::NonGC) 7099 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7100 else { 7101 assert(!getLangOpts().ObjCAutoRefCount); 7102 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7103 } 7104 } 7105 7106 bool isVM = T->isVariablyModifiedType(); 7107 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7108 NewVD->hasAttr<BlocksAttr>()) 7109 getCurFunction()->setHasBranchProtectedScope(); 7110 7111 if ((isVM && NewVD->hasLinkage()) || 7112 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7113 bool SizeIsNegative; 7114 llvm::APSInt Oversized; 7115 TypeSourceInfo *FixedTInfo = 7116 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7117 SizeIsNegative, Oversized); 7118 if (!FixedTInfo && T->isVariableArrayType()) { 7119 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7120 // FIXME: This won't give the correct result for 7121 // int a[10][n]; 7122 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7123 7124 if (NewVD->isFileVarDecl()) 7125 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7126 << SizeRange; 7127 else if (NewVD->isStaticLocal()) 7128 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7129 << SizeRange; 7130 else 7131 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7132 << SizeRange; 7133 NewVD->setInvalidDecl(); 7134 return; 7135 } 7136 7137 if (!FixedTInfo) { 7138 if (NewVD->isFileVarDecl()) 7139 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7140 else 7141 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7142 NewVD->setInvalidDecl(); 7143 return; 7144 } 7145 7146 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7147 NewVD->setType(FixedTInfo->getType()); 7148 NewVD->setTypeSourceInfo(FixedTInfo); 7149 } 7150 7151 if (T->isVoidType()) { 7152 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7153 // of objects and functions. 7154 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7155 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7156 << T; 7157 NewVD->setInvalidDecl(); 7158 return; 7159 } 7160 } 7161 7162 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7163 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7164 NewVD->setInvalidDecl(); 7165 return; 7166 } 7167 7168 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7169 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7170 NewVD->setInvalidDecl(); 7171 return; 7172 } 7173 7174 if (NewVD->isConstexpr() && !T->isDependentType() && 7175 RequireLiteralType(NewVD->getLocation(), T, 7176 diag::err_constexpr_var_non_literal)) { 7177 NewVD->setInvalidDecl(); 7178 return; 7179 } 7180 } 7181 7182 /// \brief Perform semantic checking on a newly-created variable 7183 /// declaration. 7184 /// 7185 /// This routine performs all of the type-checking required for a 7186 /// variable declaration once it has been built. It is used both to 7187 /// check variables after they have been parsed and their declarators 7188 /// have been translated into a declaration, and to check variables 7189 /// that have been instantiated from a template. 7190 /// 7191 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7192 /// 7193 /// Returns true if the variable declaration is a redeclaration. 7194 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7195 CheckVariableDeclarationType(NewVD); 7196 7197 // If the decl is already known invalid, don't check it. 7198 if (NewVD->isInvalidDecl()) 7199 return false; 7200 7201 // If we did not find anything by this name, look for a non-visible 7202 // extern "C" declaration with the same name. 7203 if (Previous.empty() && 7204 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7205 Previous.setShadowed(); 7206 7207 if (!Previous.empty()) { 7208 MergeVarDecl(NewVD, Previous); 7209 return true; 7210 } 7211 return false; 7212 } 7213 7214 namespace { 7215 struct FindOverriddenMethod { 7216 Sema *S; 7217 CXXMethodDecl *Method; 7218 7219 /// Member lookup function that determines whether a given C++ 7220 /// method overrides a method in a base class, to be used with 7221 /// CXXRecordDecl::lookupInBases(). 7222 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7223 RecordDecl *BaseRecord = 7224 Specifier->getType()->getAs<RecordType>()->getDecl(); 7225 7226 DeclarationName Name = Method->getDeclName(); 7227 7228 // FIXME: Do we care about other names here too? 7229 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7230 // We really want to find the base class destructor here. 7231 QualType T = S->Context.getTypeDeclType(BaseRecord); 7232 CanQualType CT = S->Context.getCanonicalType(T); 7233 7234 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7235 } 7236 7237 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7238 Path.Decls = Path.Decls.slice(1)) { 7239 NamedDecl *D = Path.Decls.front(); 7240 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7241 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7242 return true; 7243 } 7244 } 7245 7246 return false; 7247 } 7248 }; 7249 7250 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7251 } // end anonymous namespace 7252 7253 /// \brief Report an error regarding overriding, along with any relevant 7254 /// overriden methods. 7255 /// 7256 /// \param DiagID the primary error to report. 7257 /// \param MD the overriding method. 7258 /// \param OEK which overrides to include as notes. 7259 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7260 OverrideErrorKind OEK = OEK_All) { 7261 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7262 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7263 E = MD->end_overridden_methods(); 7264 I != E; ++I) { 7265 // This check (& the OEK parameter) could be replaced by a predicate, but 7266 // without lambdas that would be overkill. This is still nicer than writing 7267 // out the diag loop 3 times. 7268 if ((OEK == OEK_All) || 7269 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7270 (OEK == OEK_Deleted && (*I)->isDeleted())) 7271 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7272 } 7273 } 7274 7275 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7276 /// and if so, check that it's a valid override and remember it. 7277 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7278 // Look for methods in base classes that this method might override. 7279 CXXBasePaths Paths; 7280 FindOverriddenMethod FOM; 7281 FOM.Method = MD; 7282 FOM.S = this; 7283 bool hasDeletedOverridenMethods = false; 7284 bool hasNonDeletedOverridenMethods = false; 7285 bool AddedAny = false; 7286 if (DC->lookupInBases(FOM, Paths)) { 7287 for (auto *I : Paths.found_decls()) { 7288 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7289 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7290 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7291 !CheckOverridingFunctionAttributes(MD, OldMD) && 7292 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7293 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7294 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7295 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7296 AddedAny = true; 7297 } 7298 } 7299 } 7300 } 7301 7302 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7303 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7304 } 7305 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7306 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7307 } 7308 7309 return AddedAny; 7310 } 7311 7312 namespace { 7313 // Struct for holding all of the extra arguments needed by 7314 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7315 struct ActOnFDArgs { 7316 Scope *S; 7317 Declarator &D; 7318 MultiTemplateParamsArg TemplateParamLists; 7319 bool AddToScope; 7320 }; 7321 } // end anonymous namespace 7322 7323 namespace { 7324 7325 // Callback to only accept typo corrections that have a non-zero edit distance. 7326 // Also only accept corrections that have the same parent decl. 7327 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7328 public: 7329 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7330 CXXRecordDecl *Parent) 7331 : Context(Context), OriginalFD(TypoFD), 7332 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7333 7334 bool ValidateCandidate(const TypoCorrection &candidate) override { 7335 if (candidate.getEditDistance() == 0) 7336 return false; 7337 7338 SmallVector<unsigned, 1> MismatchedParams; 7339 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7340 CDeclEnd = candidate.end(); 7341 CDecl != CDeclEnd; ++CDecl) { 7342 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7343 7344 if (FD && !FD->hasBody() && 7345 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7346 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7347 CXXRecordDecl *Parent = MD->getParent(); 7348 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7349 return true; 7350 } else if (!ExpectedParent) { 7351 return true; 7352 } 7353 } 7354 } 7355 7356 return false; 7357 } 7358 7359 private: 7360 ASTContext &Context; 7361 FunctionDecl *OriginalFD; 7362 CXXRecordDecl *ExpectedParent; 7363 }; 7364 7365 } // end anonymous namespace 7366 7367 /// \brief Generate diagnostics for an invalid function redeclaration. 7368 /// 7369 /// This routine handles generating the diagnostic messages for an invalid 7370 /// function redeclaration, including finding possible similar declarations 7371 /// or performing typo correction if there are no previous declarations with 7372 /// the same name. 7373 /// 7374 /// Returns a NamedDecl iff typo correction was performed and substituting in 7375 /// the new declaration name does not cause new errors. 7376 static NamedDecl *DiagnoseInvalidRedeclaration( 7377 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7378 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7379 DeclarationName Name = NewFD->getDeclName(); 7380 DeclContext *NewDC = NewFD->getDeclContext(); 7381 SmallVector<unsigned, 1> MismatchedParams; 7382 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7383 TypoCorrection Correction; 7384 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7385 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7386 : diag::err_member_decl_does_not_match; 7387 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7388 IsLocalFriend ? Sema::LookupLocalFriendName 7389 : Sema::LookupOrdinaryName, 7390 Sema::ForRedeclaration); 7391 7392 NewFD->setInvalidDecl(); 7393 if (IsLocalFriend) 7394 SemaRef.LookupName(Prev, S); 7395 else 7396 SemaRef.LookupQualifiedName(Prev, NewDC); 7397 assert(!Prev.isAmbiguous() && 7398 "Cannot have an ambiguity in previous-declaration lookup"); 7399 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7400 if (!Prev.empty()) { 7401 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7402 Func != FuncEnd; ++Func) { 7403 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7404 if (FD && 7405 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7406 // Add 1 to the index so that 0 can mean the mismatch didn't 7407 // involve a parameter 7408 unsigned ParamNum = 7409 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7410 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7411 } 7412 } 7413 // If the qualified name lookup yielded nothing, try typo correction 7414 } else if ((Correction = SemaRef.CorrectTypo( 7415 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7416 &ExtraArgs.D.getCXXScopeSpec(), 7417 llvm::make_unique<DifferentNameValidatorCCC>( 7418 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7419 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7420 // Set up everything for the call to ActOnFunctionDeclarator 7421 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7422 ExtraArgs.D.getIdentifierLoc()); 7423 Previous.clear(); 7424 Previous.setLookupName(Correction.getCorrection()); 7425 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7426 CDeclEnd = Correction.end(); 7427 CDecl != CDeclEnd; ++CDecl) { 7428 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7429 if (FD && !FD->hasBody() && 7430 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7431 Previous.addDecl(FD); 7432 } 7433 } 7434 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7435 7436 NamedDecl *Result; 7437 // Retry building the function declaration with the new previous 7438 // declarations, and with errors suppressed. 7439 { 7440 // Trap errors. 7441 Sema::SFINAETrap Trap(SemaRef); 7442 7443 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7444 // pieces need to verify the typo-corrected C++ declaration and hopefully 7445 // eliminate the need for the parameter pack ExtraArgs. 7446 Result = SemaRef.ActOnFunctionDeclarator( 7447 ExtraArgs.S, ExtraArgs.D, 7448 Correction.getCorrectionDecl()->getDeclContext(), 7449 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7450 ExtraArgs.AddToScope); 7451 7452 if (Trap.hasErrorOccurred()) 7453 Result = nullptr; 7454 } 7455 7456 if (Result) { 7457 // Determine which correction we picked. 7458 Decl *Canonical = Result->getCanonicalDecl(); 7459 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7460 I != E; ++I) 7461 if ((*I)->getCanonicalDecl() == Canonical) 7462 Correction.setCorrectionDecl(*I); 7463 7464 SemaRef.diagnoseTypo( 7465 Correction, 7466 SemaRef.PDiag(IsLocalFriend 7467 ? diag::err_no_matching_local_friend_suggest 7468 : diag::err_member_decl_does_not_match_suggest) 7469 << Name << NewDC << IsDefinition); 7470 return Result; 7471 } 7472 7473 // Pretend the typo correction never occurred 7474 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7475 ExtraArgs.D.getIdentifierLoc()); 7476 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7477 Previous.clear(); 7478 Previous.setLookupName(Name); 7479 } 7480 7481 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7482 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7483 7484 bool NewFDisConst = false; 7485 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7486 NewFDisConst = NewMD->isConst(); 7487 7488 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7489 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7490 NearMatch != NearMatchEnd; ++NearMatch) { 7491 FunctionDecl *FD = NearMatch->first; 7492 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7493 bool FDisConst = MD && MD->isConst(); 7494 bool IsMember = MD || !IsLocalFriend; 7495 7496 // FIXME: These notes are poorly worded for the local friend case. 7497 if (unsigned Idx = NearMatch->second) { 7498 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7499 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7500 if (Loc.isInvalid()) Loc = FD->getLocation(); 7501 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7502 : diag::note_local_decl_close_param_match) 7503 << Idx << FDParam->getType() 7504 << NewFD->getParamDecl(Idx - 1)->getType(); 7505 } else if (FDisConst != NewFDisConst) { 7506 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7507 << NewFDisConst << FD->getSourceRange().getEnd(); 7508 } else 7509 SemaRef.Diag(FD->getLocation(), 7510 IsMember ? diag::note_member_def_close_match 7511 : diag::note_local_decl_close_match); 7512 } 7513 return nullptr; 7514 } 7515 7516 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7517 switch (D.getDeclSpec().getStorageClassSpec()) { 7518 default: llvm_unreachable("Unknown storage class!"); 7519 case DeclSpec::SCS_auto: 7520 case DeclSpec::SCS_register: 7521 case DeclSpec::SCS_mutable: 7522 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7523 diag::err_typecheck_sclass_func); 7524 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7525 D.setInvalidType(); 7526 break; 7527 case DeclSpec::SCS_unspecified: break; 7528 case DeclSpec::SCS_extern: 7529 if (D.getDeclSpec().isExternInLinkageSpec()) 7530 return SC_None; 7531 return SC_Extern; 7532 case DeclSpec::SCS_static: { 7533 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7534 // C99 6.7.1p5: 7535 // The declaration of an identifier for a function that has 7536 // block scope shall have no explicit storage-class specifier 7537 // other than extern 7538 // See also (C++ [dcl.stc]p4). 7539 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7540 diag::err_static_block_func); 7541 break; 7542 } else 7543 return SC_Static; 7544 } 7545 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7546 } 7547 7548 // No explicit storage class has already been returned 7549 return SC_None; 7550 } 7551 7552 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7553 DeclContext *DC, QualType &R, 7554 TypeSourceInfo *TInfo, 7555 StorageClass SC, 7556 bool &IsVirtualOkay) { 7557 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7558 DeclarationName Name = NameInfo.getName(); 7559 7560 FunctionDecl *NewFD = nullptr; 7561 bool isInline = D.getDeclSpec().isInlineSpecified(); 7562 7563 if (!SemaRef.getLangOpts().CPlusPlus) { 7564 // Determine whether the function was written with a 7565 // prototype. This true when: 7566 // - there is a prototype in the declarator, or 7567 // - the type R of the function is some kind of typedef or other non- 7568 // attributed reference to a type name (which eventually refers to a 7569 // function type). 7570 bool HasPrototype = 7571 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7572 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7573 7574 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7575 D.getLocStart(), NameInfo, R, 7576 TInfo, SC, isInline, 7577 HasPrototype, false); 7578 if (D.isInvalidType()) 7579 NewFD->setInvalidDecl(); 7580 7581 return NewFD; 7582 } 7583 7584 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7585 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7586 7587 // Check that the return type is not an abstract class type. 7588 // For record types, this is done by the AbstractClassUsageDiagnoser once 7589 // the class has been completely parsed. 7590 if (!DC->isRecord() && 7591 SemaRef.RequireNonAbstractType( 7592 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7593 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7594 D.setInvalidType(); 7595 7596 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7597 // This is a C++ constructor declaration. 7598 assert(DC->isRecord() && 7599 "Constructors can only be declared in a member context"); 7600 7601 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7602 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7603 D.getLocStart(), NameInfo, 7604 R, TInfo, isExplicit, isInline, 7605 /*isImplicitlyDeclared=*/false, 7606 isConstexpr); 7607 7608 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7609 // This is a C++ destructor declaration. 7610 if (DC->isRecord()) { 7611 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7612 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7613 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7614 SemaRef.Context, Record, 7615 D.getLocStart(), 7616 NameInfo, R, TInfo, isInline, 7617 /*isImplicitlyDeclared=*/false); 7618 7619 // If the class is complete, then we now create the implicit exception 7620 // specification. If the class is incomplete or dependent, we can't do 7621 // it yet. 7622 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7623 Record->getDefinition() && !Record->isBeingDefined() && 7624 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7625 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7626 } 7627 7628 IsVirtualOkay = true; 7629 return NewDD; 7630 7631 } else { 7632 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7633 D.setInvalidType(); 7634 7635 // Create a FunctionDecl to satisfy the function definition parsing 7636 // code path. 7637 return FunctionDecl::Create(SemaRef.Context, DC, 7638 D.getLocStart(), 7639 D.getIdentifierLoc(), Name, R, TInfo, 7640 SC, isInline, 7641 /*hasPrototype=*/true, isConstexpr); 7642 } 7643 7644 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7645 if (!DC->isRecord()) { 7646 SemaRef.Diag(D.getIdentifierLoc(), 7647 diag::err_conv_function_not_member); 7648 return nullptr; 7649 } 7650 7651 SemaRef.CheckConversionDeclarator(D, R, SC); 7652 IsVirtualOkay = true; 7653 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7654 D.getLocStart(), NameInfo, 7655 R, TInfo, isInline, isExplicit, 7656 isConstexpr, SourceLocation()); 7657 7658 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7659 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7660 7661 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7662 isExplicit, NameInfo, R, TInfo, 7663 D.getLocEnd()); 7664 } else if (DC->isRecord()) { 7665 // If the name of the function is the same as the name of the record, 7666 // then this must be an invalid constructor that has a return type. 7667 // (The parser checks for a return type and makes the declarator a 7668 // constructor if it has no return type). 7669 if (Name.getAsIdentifierInfo() && 7670 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7671 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7672 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7673 << SourceRange(D.getIdentifierLoc()); 7674 return nullptr; 7675 } 7676 7677 // This is a C++ method declaration. 7678 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7679 cast<CXXRecordDecl>(DC), 7680 D.getLocStart(), NameInfo, R, 7681 TInfo, SC, isInline, 7682 isConstexpr, SourceLocation()); 7683 IsVirtualOkay = !Ret->isStatic(); 7684 return Ret; 7685 } else { 7686 bool isFriend = 7687 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7688 if (!isFriend && SemaRef.CurContext->isRecord()) 7689 return nullptr; 7690 7691 // Determine whether the function was written with a 7692 // prototype. This true when: 7693 // - we're in C++ (where every function has a prototype), 7694 return FunctionDecl::Create(SemaRef.Context, DC, 7695 D.getLocStart(), 7696 NameInfo, R, TInfo, SC, isInline, 7697 true/*HasPrototype*/, isConstexpr); 7698 } 7699 } 7700 7701 enum OpenCLParamType { 7702 ValidKernelParam, 7703 PtrPtrKernelParam, 7704 PtrKernelParam, 7705 InvalidAddrSpacePtrKernelParam, 7706 InvalidKernelParam, 7707 RecordKernelParam 7708 }; 7709 7710 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7711 if (PT->isPointerType()) { 7712 QualType PointeeType = PT->getPointeeType(); 7713 if (PointeeType->isPointerType()) 7714 return PtrPtrKernelParam; 7715 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7716 PointeeType.getAddressSpace() == 0) 7717 return InvalidAddrSpacePtrKernelParam; 7718 return PtrKernelParam; 7719 } 7720 7721 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7722 // be used as builtin types. 7723 7724 if (PT->isImageType()) 7725 return PtrKernelParam; 7726 7727 if (PT->isBooleanType()) 7728 return InvalidKernelParam; 7729 7730 if (PT->isEventT()) 7731 return InvalidKernelParam; 7732 7733 // OpenCL extension spec v1.2 s9.5: 7734 // This extension adds support for half scalar and vector types as built-in 7735 // types that can be used for arithmetic operations, conversions etc. 7736 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7737 return InvalidKernelParam; 7738 7739 if (PT->isRecordType()) 7740 return RecordKernelParam; 7741 7742 return ValidKernelParam; 7743 } 7744 7745 static void checkIsValidOpenCLKernelParameter( 7746 Sema &S, 7747 Declarator &D, 7748 ParmVarDecl *Param, 7749 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7750 QualType PT = Param->getType(); 7751 7752 // Cache the valid types we encounter to avoid rechecking structs that are 7753 // used again 7754 if (ValidTypes.count(PT.getTypePtr())) 7755 return; 7756 7757 switch (getOpenCLKernelParameterType(S, PT)) { 7758 case PtrPtrKernelParam: 7759 // OpenCL v1.2 s6.9.a: 7760 // A kernel function argument cannot be declared as a 7761 // pointer to a pointer type. 7762 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7763 D.setInvalidType(); 7764 return; 7765 7766 case InvalidAddrSpacePtrKernelParam: 7767 // OpenCL v1.0 s6.5: 7768 // __kernel function arguments declared to be a pointer of a type can point 7769 // to one of the following address spaces only : __global, __local or 7770 // __constant. 7771 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7772 D.setInvalidType(); 7773 return; 7774 7775 // OpenCL v1.2 s6.9.k: 7776 // Arguments to kernel functions in a program cannot be declared with the 7777 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7778 // uintptr_t or a struct and/or union that contain fields declared to be 7779 // one of these built-in scalar types. 7780 7781 case InvalidKernelParam: 7782 // OpenCL v1.2 s6.8 n: 7783 // A kernel function argument cannot be declared 7784 // of event_t type. 7785 // Do not diagnose half type since it is diagnosed as invalid argument 7786 // type for any function elsewhere. 7787 if (!PT->isHalfType()) 7788 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7789 D.setInvalidType(); 7790 return; 7791 7792 case PtrKernelParam: 7793 case ValidKernelParam: 7794 ValidTypes.insert(PT.getTypePtr()); 7795 return; 7796 7797 case RecordKernelParam: 7798 break; 7799 } 7800 7801 // Track nested structs we will inspect 7802 SmallVector<const Decl *, 4> VisitStack; 7803 7804 // Track where we are in the nested structs. Items will migrate from 7805 // VisitStack to HistoryStack as we do the DFS for bad field. 7806 SmallVector<const FieldDecl *, 4> HistoryStack; 7807 HistoryStack.push_back(nullptr); 7808 7809 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7810 VisitStack.push_back(PD); 7811 7812 assert(VisitStack.back() && "First decl null?"); 7813 7814 do { 7815 const Decl *Next = VisitStack.pop_back_val(); 7816 if (!Next) { 7817 assert(!HistoryStack.empty()); 7818 // Found a marker, we have gone up a level 7819 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7820 ValidTypes.insert(Hist->getType().getTypePtr()); 7821 7822 continue; 7823 } 7824 7825 // Adds everything except the original parameter declaration (which is not a 7826 // field itself) to the history stack. 7827 const RecordDecl *RD; 7828 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7829 HistoryStack.push_back(Field); 7830 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7831 } else { 7832 RD = cast<RecordDecl>(Next); 7833 } 7834 7835 // Add a null marker so we know when we've gone back up a level 7836 VisitStack.push_back(nullptr); 7837 7838 for (const auto *FD : RD->fields()) { 7839 QualType QT = FD->getType(); 7840 7841 if (ValidTypes.count(QT.getTypePtr())) 7842 continue; 7843 7844 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7845 if (ParamType == ValidKernelParam) 7846 continue; 7847 7848 if (ParamType == RecordKernelParam) { 7849 VisitStack.push_back(FD); 7850 continue; 7851 } 7852 7853 // OpenCL v1.2 s6.9.p: 7854 // Arguments to kernel functions that are declared to be a struct or union 7855 // do not allow OpenCL objects to be passed as elements of the struct or 7856 // union. 7857 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7858 ParamType == InvalidAddrSpacePtrKernelParam) { 7859 S.Diag(Param->getLocation(), 7860 diag::err_record_with_pointers_kernel_param) 7861 << PT->isUnionType() 7862 << PT; 7863 } else { 7864 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7865 } 7866 7867 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7868 << PD->getDeclName(); 7869 7870 // We have an error, now let's go back up through history and show where 7871 // the offending field came from 7872 for (ArrayRef<const FieldDecl *>::const_iterator 7873 I = HistoryStack.begin() + 1, 7874 E = HistoryStack.end(); 7875 I != E; ++I) { 7876 const FieldDecl *OuterField = *I; 7877 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7878 << OuterField->getType(); 7879 } 7880 7881 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7882 << QT->isPointerType() 7883 << QT; 7884 D.setInvalidType(); 7885 return; 7886 } 7887 } while (!VisitStack.empty()); 7888 } 7889 7890 /// Find the DeclContext in which a tag is implicitly declared if we see an 7891 /// elaborated type specifier in the specified context, and lookup finds 7892 /// nothing. 7893 static DeclContext *getTagInjectionContext(DeclContext *DC) { 7894 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 7895 DC = DC->getParent(); 7896 return DC; 7897 } 7898 7899 /// Find the Scope in which a tag is implicitly declared if we see an 7900 /// elaborated type specifier in the specified context, and lookup finds 7901 /// nothing. 7902 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 7903 while (S->isClassScope() || 7904 (LangOpts.CPlusPlus && 7905 S->isFunctionPrototypeScope()) || 7906 ((S->getFlags() & Scope::DeclScope) == 0) || 7907 (S->getEntity() && S->getEntity()->isTransparentContext())) 7908 S = S->getParent(); 7909 return S; 7910 } 7911 7912 NamedDecl* 7913 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7914 TypeSourceInfo *TInfo, LookupResult &Previous, 7915 MultiTemplateParamsArg TemplateParamLists, 7916 bool &AddToScope) { 7917 QualType R = TInfo->getType(); 7918 7919 assert(R.getTypePtr()->isFunctionType()); 7920 7921 // TODO: consider using NameInfo for diagnostic. 7922 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7923 DeclarationName Name = NameInfo.getName(); 7924 StorageClass SC = getFunctionStorageClass(*this, D); 7925 7926 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7927 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7928 diag::err_invalid_thread) 7929 << DeclSpec::getSpecifierName(TSCS); 7930 7931 if (D.isFirstDeclarationOfMember()) 7932 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7933 D.getIdentifierLoc()); 7934 7935 bool isFriend = false; 7936 FunctionTemplateDecl *FunctionTemplate = nullptr; 7937 bool isMemberSpecialization = false; 7938 bool isFunctionTemplateSpecialization = false; 7939 7940 bool isDependentClassScopeExplicitSpecialization = false; 7941 bool HasExplicitTemplateArgs = false; 7942 TemplateArgumentListInfo TemplateArgs; 7943 7944 bool isVirtualOkay = false; 7945 7946 DeclContext *OriginalDC = DC; 7947 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7948 7949 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7950 isVirtualOkay); 7951 if (!NewFD) return nullptr; 7952 7953 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7954 NewFD->setTopLevelDeclInObjCContainer(); 7955 7956 // Set the lexical context. If this is a function-scope declaration, or has a 7957 // C++ scope specifier, or is the object of a friend declaration, the lexical 7958 // context will be different from the semantic context. 7959 NewFD->setLexicalDeclContext(CurContext); 7960 7961 if (IsLocalExternDecl) 7962 NewFD->setLocalExternDecl(); 7963 7964 if (getLangOpts().CPlusPlus) { 7965 bool isInline = D.getDeclSpec().isInlineSpecified(); 7966 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7967 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7968 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7969 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7970 isFriend = D.getDeclSpec().isFriendSpecified(); 7971 if (isFriend && !isInline && D.isFunctionDefinition()) { 7972 // C++ [class.friend]p5 7973 // A function can be defined in a friend declaration of a 7974 // class . . . . Such a function is implicitly inline. 7975 NewFD->setImplicitlyInline(); 7976 } 7977 7978 // If this is a method defined in an __interface, and is not a constructor 7979 // or an overloaded operator, then set the pure flag (isVirtual will already 7980 // return true). 7981 if (const CXXRecordDecl *Parent = 7982 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7983 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7984 NewFD->setPure(true); 7985 7986 // C++ [class.union]p2 7987 // A union can have member functions, but not virtual functions. 7988 if (isVirtual && Parent->isUnion()) 7989 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7990 } 7991 7992 SetNestedNameSpecifier(NewFD, D); 7993 isMemberSpecialization = false; 7994 isFunctionTemplateSpecialization = false; 7995 if (D.isInvalidType()) 7996 NewFD->setInvalidDecl(); 7997 7998 // Match up the template parameter lists with the scope specifier, then 7999 // determine whether we have a template or a template specialization. 8000 bool Invalid = false; 8001 if (TemplateParameterList *TemplateParams = 8002 MatchTemplateParametersToScopeSpecifier( 8003 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8004 D.getCXXScopeSpec(), 8005 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8006 ? D.getName().TemplateId 8007 : nullptr, 8008 TemplateParamLists, isFriend, isMemberSpecialization, 8009 Invalid)) { 8010 if (TemplateParams->size() > 0) { 8011 // This is a function template 8012 8013 // Check that we can declare a template here. 8014 if (CheckTemplateDeclScope(S, TemplateParams)) 8015 NewFD->setInvalidDecl(); 8016 8017 // A destructor cannot be a template. 8018 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8019 Diag(NewFD->getLocation(), diag::err_destructor_template); 8020 NewFD->setInvalidDecl(); 8021 } 8022 8023 // If we're adding a template to a dependent context, we may need to 8024 // rebuilding some of the types used within the template parameter list, 8025 // now that we know what the current instantiation is. 8026 if (DC->isDependentContext()) { 8027 ContextRAII SavedContext(*this, DC); 8028 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8029 Invalid = true; 8030 } 8031 8032 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8033 NewFD->getLocation(), 8034 Name, TemplateParams, 8035 NewFD); 8036 FunctionTemplate->setLexicalDeclContext(CurContext); 8037 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8038 8039 // For source fidelity, store the other template param lists. 8040 if (TemplateParamLists.size() > 1) { 8041 NewFD->setTemplateParameterListsInfo(Context, 8042 TemplateParamLists.drop_back(1)); 8043 } 8044 } else { 8045 // This is a function template specialization. 8046 isFunctionTemplateSpecialization = true; 8047 // For source fidelity, store all the template param lists. 8048 if (TemplateParamLists.size() > 0) 8049 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8050 8051 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8052 if (isFriend) { 8053 // We want to remove the "template<>", found here. 8054 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8055 8056 // If we remove the template<> and the name is not a 8057 // template-id, we're actually silently creating a problem: 8058 // the friend declaration will refer to an untemplated decl, 8059 // and clearly the user wants a template specialization. So 8060 // we need to insert '<>' after the name. 8061 SourceLocation InsertLoc; 8062 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8063 InsertLoc = D.getName().getSourceRange().getEnd(); 8064 InsertLoc = getLocForEndOfToken(InsertLoc); 8065 } 8066 8067 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8068 << Name << RemoveRange 8069 << FixItHint::CreateRemoval(RemoveRange) 8070 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8071 } 8072 } 8073 } 8074 else { 8075 // All template param lists were matched against the scope specifier: 8076 // this is NOT (an explicit specialization of) a template. 8077 if (TemplateParamLists.size() > 0) 8078 // For source fidelity, store all the template param lists. 8079 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8080 } 8081 8082 if (Invalid) { 8083 NewFD->setInvalidDecl(); 8084 if (FunctionTemplate) 8085 FunctionTemplate->setInvalidDecl(); 8086 } 8087 8088 // C++ [dcl.fct.spec]p5: 8089 // The virtual specifier shall only be used in declarations of 8090 // nonstatic class member functions that appear within a 8091 // member-specification of a class declaration; see 10.3. 8092 // 8093 if (isVirtual && !NewFD->isInvalidDecl()) { 8094 if (!isVirtualOkay) { 8095 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8096 diag::err_virtual_non_function); 8097 } else if (!CurContext->isRecord()) { 8098 // 'virtual' was specified outside of the class. 8099 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8100 diag::err_virtual_out_of_class) 8101 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8102 } else if (NewFD->getDescribedFunctionTemplate()) { 8103 // C++ [temp.mem]p3: 8104 // A member function template shall not be virtual. 8105 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8106 diag::err_virtual_member_function_template) 8107 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8108 } else { 8109 // Okay: Add virtual to the method. 8110 NewFD->setVirtualAsWritten(true); 8111 } 8112 8113 if (getLangOpts().CPlusPlus14 && 8114 NewFD->getReturnType()->isUndeducedType()) 8115 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8116 } 8117 8118 if (getLangOpts().CPlusPlus14 && 8119 (NewFD->isDependentContext() || 8120 (isFriend && CurContext->isDependentContext())) && 8121 NewFD->getReturnType()->isUndeducedType()) { 8122 // If the function template is referenced directly (for instance, as a 8123 // member of the current instantiation), pretend it has a dependent type. 8124 // This is not really justified by the standard, but is the only sane 8125 // thing to do. 8126 // FIXME: For a friend function, we have not marked the function as being 8127 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8128 const FunctionProtoType *FPT = 8129 NewFD->getType()->castAs<FunctionProtoType>(); 8130 QualType Result = 8131 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8132 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8133 FPT->getExtProtoInfo())); 8134 } 8135 8136 // C++ [dcl.fct.spec]p3: 8137 // The inline specifier shall not appear on a block scope function 8138 // declaration. 8139 if (isInline && !NewFD->isInvalidDecl()) { 8140 if (CurContext->isFunctionOrMethod()) { 8141 // 'inline' is not allowed on block scope function declaration. 8142 Diag(D.getDeclSpec().getInlineSpecLoc(), 8143 diag::err_inline_declaration_block_scope) << Name 8144 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8145 } 8146 } 8147 8148 // C++ [dcl.fct.spec]p6: 8149 // The explicit specifier shall be used only in the declaration of a 8150 // constructor or conversion function within its class definition; 8151 // see 12.3.1 and 12.3.2. 8152 if (isExplicit && !NewFD->isInvalidDecl() && 8153 !isa<CXXDeductionGuideDecl>(NewFD)) { 8154 if (!CurContext->isRecord()) { 8155 // 'explicit' was specified outside of the class. 8156 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8157 diag::err_explicit_out_of_class) 8158 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8159 } else if (!isa<CXXConstructorDecl>(NewFD) && 8160 !isa<CXXConversionDecl>(NewFD)) { 8161 // 'explicit' was specified on a function that wasn't a constructor 8162 // or conversion function. 8163 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8164 diag::err_explicit_non_ctor_or_conv_function) 8165 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8166 } 8167 } 8168 8169 if (isConstexpr) { 8170 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8171 // are implicitly inline. 8172 NewFD->setImplicitlyInline(); 8173 8174 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8175 // be either constructors or to return a literal type. Therefore, 8176 // destructors cannot be declared constexpr. 8177 if (isa<CXXDestructorDecl>(NewFD)) 8178 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8179 } 8180 8181 if (isConcept) { 8182 // This is a function concept. 8183 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8184 FTD->setConcept(); 8185 8186 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8187 // applied only to the definition of a function template [...] 8188 if (!D.isFunctionDefinition()) { 8189 Diag(D.getDeclSpec().getConceptSpecLoc(), 8190 diag::err_function_concept_not_defined); 8191 NewFD->setInvalidDecl(); 8192 } 8193 8194 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8195 // have no exception-specification and is treated as if it were specified 8196 // with noexcept(true) (15.4). [...] 8197 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8198 if (FPT->hasExceptionSpec()) { 8199 SourceRange Range; 8200 if (D.isFunctionDeclarator()) 8201 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8202 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8203 << FixItHint::CreateRemoval(Range); 8204 NewFD->setInvalidDecl(); 8205 } else { 8206 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8207 } 8208 8209 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8210 // following restrictions: 8211 // - The declared return type shall have the type bool. 8212 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8213 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8214 NewFD->setInvalidDecl(); 8215 } 8216 8217 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8218 // following restrictions: 8219 // - The declaration's parameter list shall be equivalent to an empty 8220 // parameter list. 8221 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8222 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8223 } 8224 8225 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8226 // implicity defined to be a constexpr declaration (implicitly inline) 8227 NewFD->setImplicitlyInline(); 8228 8229 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8230 // be declared with the thread_local, inline, friend, or constexpr 8231 // specifiers, [...] 8232 if (isInline) { 8233 Diag(D.getDeclSpec().getInlineSpecLoc(), 8234 diag::err_concept_decl_invalid_specifiers) 8235 << 1 << 1; 8236 NewFD->setInvalidDecl(true); 8237 } 8238 8239 if (isFriend) { 8240 Diag(D.getDeclSpec().getFriendSpecLoc(), 8241 diag::err_concept_decl_invalid_specifiers) 8242 << 1 << 2; 8243 NewFD->setInvalidDecl(true); 8244 } 8245 8246 if (isConstexpr) { 8247 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8248 diag::err_concept_decl_invalid_specifiers) 8249 << 1 << 3; 8250 NewFD->setInvalidDecl(true); 8251 } 8252 8253 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8254 // applied only to the definition of a function template or variable 8255 // template, declared in namespace scope. 8256 if (isFunctionTemplateSpecialization) { 8257 Diag(D.getDeclSpec().getConceptSpecLoc(), 8258 diag::err_concept_specified_specialization) << 1; 8259 NewFD->setInvalidDecl(true); 8260 return NewFD; 8261 } 8262 } 8263 8264 // If __module_private__ was specified, mark the function accordingly. 8265 if (D.getDeclSpec().isModulePrivateSpecified()) { 8266 if (isFunctionTemplateSpecialization) { 8267 SourceLocation ModulePrivateLoc 8268 = D.getDeclSpec().getModulePrivateSpecLoc(); 8269 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8270 << 0 8271 << FixItHint::CreateRemoval(ModulePrivateLoc); 8272 } else { 8273 NewFD->setModulePrivate(); 8274 if (FunctionTemplate) 8275 FunctionTemplate->setModulePrivate(); 8276 } 8277 } 8278 8279 if (isFriend) { 8280 if (FunctionTemplate) { 8281 FunctionTemplate->setObjectOfFriendDecl(); 8282 FunctionTemplate->setAccess(AS_public); 8283 } 8284 NewFD->setObjectOfFriendDecl(); 8285 NewFD->setAccess(AS_public); 8286 } 8287 8288 // If a function is defined as defaulted or deleted, mark it as such now. 8289 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8290 // definition kind to FDK_Definition. 8291 switch (D.getFunctionDefinitionKind()) { 8292 case FDK_Declaration: 8293 case FDK_Definition: 8294 break; 8295 8296 case FDK_Defaulted: 8297 NewFD->setDefaulted(); 8298 break; 8299 8300 case FDK_Deleted: 8301 NewFD->setDeletedAsWritten(); 8302 break; 8303 } 8304 8305 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8306 D.isFunctionDefinition()) { 8307 // C++ [class.mfct]p2: 8308 // A member function may be defined (8.4) in its class definition, in 8309 // which case it is an inline member function (7.1.2) 8310 NewFD->setImplicitlyInline(); 8311 } 8312 8313 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8314 !CurContext->isRecord()) { 8315 // C++ [class.static]p1: 8316 // A data or function member of a class may be declared static 8317 // in a class definition, in which case it is a static member of 8318 // the class. 8319 8320 // Complain about the 'static' specifier if it's on an out-of-line 8321 // member function definition. 8322 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8323 diag::err_static_out_of_line) 8324 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8325 } 8326 8327 // C++11 [except.spec]p15: 8328 // A deallocation function with no exception-specification is treated 8329 // as if it were specified with noexcept(true). 8330 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8331 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8332 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8333 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8334 NewFD->setType(Context.getFunctionType( 8335 FPT->getReturnType(), FPT->getParamTypes(), 8336 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8337 } 8338 8339 // Filter out previous declarations that don't match the scope. 8340 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8341 D.getCXXScopeSpec().isNotEmpty() || 8342 isMemberSpecialization || 8343 isFunctionTemplateSpecialization); 8344 8345 // Handle GNU asm-label extension (encoded as an attribute). 8346 if (Expr *E = (Expr*) D.getAsmLabel()) { 8347 // The parser guarantees this is a string. 8348 StringLiteral *SE = cast<StringLiteral>(E); 8349 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8350 SE->getString(), 0)); 8351 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8352 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8353 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8354 if (I != ExtnameUndeclaredIdentifiers.end()) { 8355 if (isDeclExternC(NewFD)) { 8356 NewFD->addAttr(I->second); 8357 ExtnameUndeclaredIdentifiers.erase(I); 8358 } else 8359 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8360 << /*Variable*/0 << NewFD; 8361 } 8362 } 8363 8364 // Copy the parameter declarations from the declarator D to the function 8365 // declaration NewFD, if they are available. First scavenge them into Params. 8366 SmallVector<ParmVarDecl*, 16> Params; 8367 unsigned FTIIdx; 8368 if (D.isFunctionDeclarator(FTIIdx)) { 8369 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8370 8371 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8372 // function that takes no arguments, not a function that takes a 8373 // single void argument. 8374 // We let through "const void" here because Sema::GetTypeForDeclarator 8375 // already checks for that case. 8376 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8377 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8378 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8379 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8380 Param->setDeclContext(NewFD); 8381 Params.push_back(Param); 8382 8383 if (Param->isInvalidDecl()) 8384 NewFD->setInvalidDecl(); 8385 } 8386 } 8387 8388 if (!getLangOpts().CPlusPlus) { 8389 // In C, find all the tag declarations from the prototype and move them 8390 // into the function DeclContext. Remove them from the surrounding tag 8391 // injection context of the function, which is typically but not always 8392 // the TU. 8393 DeclContext *PrototypeTagContext = 8394 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8395 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8396 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8397 8398 // We don't want to reparent enumerators. Look at their parent enum 8399 // instead. 8400 if (!TD) { 8401 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8402 TD = cast<EnumDecl>(ECD->getDeclContext()); 8403 } 8404 if (!TD) 8405 continue; 8406 DeclContext *TagDC = TD->getLexicalDeclContext(); 8407 if (!TagDC->containsDecl(TD)) 8408 continue; 8409 TagDC->removeDecl(TD); 8410 TD->setDeclContext(NewFD); 8411 NewFD->addDecl(TD); 8412 8413 // Preserve the lexical DeclContext if it is not the surrounding tag 8414 // injection context of the FD. In this example, the semantic context of 8415 // E will be f and the lexical context will be S, while both the 8416 // semantic and lexical contexts of S will be f: 8417 // void f(struct S { enum E { a } f; } s); 8418 if (TagDC != PrototypeTagContext) 8419 TD->setLexicalDeclContext(TagDC); 8420 } 8421 } 8422 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8423 // When we're declaring a function with a typedef, typeof, etc as in the 8424 // following example, we'll need to synthesize (unnamed) 8425 // parameters for use in the declaration. 8426 // 8427 // @code 8428 // typedef void fn(int); 8429 // fn f; 8430 // @endcode 8431 8432 // Synthesize a parameter for each argument type. 8433 for (const auto &AI : FT->param_types()) { 8434 ParmVarDecl *Param = 8435 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8436 Param->setScopeInfo(0, Params.size()); 8437 Params.push_back(Param); 8438 } 8439 } else { 8440 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8441 "Should not need args for typedef of non-prototype fn"); 8442 } 8443 8444 // Finally, we know we have the right number of parameters, install them. 8445 NewFD->setParams(Params); 8446 8447 if (D.getDeclSpec().isNoreturnSpecified()) 8448 NewFD->addAttr( 8449 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8450 Context, 0)); 8451 8452 // Functions returning a variably modified type violate C99 6.7.5.2p2 8453 // because all functions have linkage. 8454 if (!NewFD->isInvalidDecl() && 8455 NewFD->getReturnType()->isVariablyModifiedType()) { 8456 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8457 NewFD->setInvalidDecl(); 8458 } 8459 8460 // Apply an implicit SectionAttr if #pragma code_seg is active. 8461 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8462 !NewFD->hasAttr<SectionAttr>()) { 8463 NewFD->addAttr( 8464 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8465 CodeSegStack.CurrentValue->getString(), 8466 CodeSegStack.CurrentPragmaLocation)); 8467 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8468 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8469 ASTContext::PSF_Read, 8470 NewFD)) 8471 NewFD->dropAttr<SectionAttr>(); 8472 } 8473 8474 // Handle attributes. 8475 ProcessDeclAttributes(S, NewFD, D); 8476 8477 if (getLangOpts().OpenCL) { 8478 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8479 // type declaration will generate a compilation error. 8480 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8481 if (AddressSpace == LangAS::opencl_local || 8482 AddressSpace == LangAS::opencl_global || 8483 AddressSpace == LangAS::opencl_constant) { 8484 Diag(NewFD->getLocation(), 8485 diag::err_opencl_return_value_with_address_space); 8486 NewFD->setInvalidDecl(); 8487 } 8488 } 8489 8490 if (!getLangOpts().CPlusPlus) { 8491 // Perform semantic checking on the function declaration. 8492 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8493 CheckMain(NewFD, D.getDeclSpec()); 8494 8495 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8496 CheckMSVCRTEntryPoint(NewFD); 8497 8498 if (!NewFD->isInvalidDecl()) 8499 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8500 isMemberSpecialization)); 8501 else if (!Previous.empty()) 8502 // Recover gracefully from an invalid redeclaration. 8503 D.setRedeclaration(true); 8504 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8505 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8506 "previous declaration set still overloaded"); 8507 8508 // Diagnose no-prototype function declarations with calling conventions that 8509 // don't support variadic calls. Only do this in C and do it after merging 8510 // possibly prototyped redeclarations. 8511 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8512 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8513 CallingConv CC = FT->getExtInfo().getCC(); 8514 if (!supportsVariadicCall(CC)) { 8515 // Windows system headers sometimes accidentally use stdcall without 8516 // (void) parameters, so we relax this to a warning. 8517 int DiagID = 8518 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8519 Diag(NewFD->getLocation(), DiagID) 8520 << FunctionType::getNameForCallConv(CC); 8521 } 8522 } 8523 } else { 8524 // C++11 [replacement.functions]p3: 8525 // The program's definitions shall not be specified as inline. 8526 // 8527 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8528 // 8529 // Suppress the diagnostic if the function is __attribute__((used)), since 8530 // that forces an external definition to be emitted. 8531 if (D.getDeclSpec().isInlineSpecified() && 8532 NewFD->isReplaceableGlobalAllocationFunction() && 8533 !NewFD->hasAttr<UsedAttr>()) 8534 Diag(D.getDeclSpec().getInlineSpecLoc(), 8535 diag::ext_operator_new_delete_declared_inline) 8536 << NewFD->getDeclName(); 8537 8538 // If the declarator is a template-id, translate the parser's template 8539 // argument list into our AST format. 8540 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8541 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8542 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8543 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8544 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8545 TemplateId->NumArgs); 8546 translateTemplateArguments(TemplateArgsPtr, 8547 TemplateArgs); 8548 8549 HasExplicitTemplateArgs = true; 8550 8551 if (NewFD->isInvalidDecl()) { 8552 HasExplicitTemplateArgs = false; 8553 } else if (FunctionTemplate) { 8554 // Function template with explicit template arguments. 8555 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8556 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8557 8558 HasExplicitTemplateArgs = false; 8559 } else { 8560 assert((isFunctionTemplateSpecialization || 8561 D.getDeclSpec().isFriendSpecified()) && 8562 "should have a 'template<>' for this decl"); 8563 // "friend void foo<>(int);" is an implicit specialization decl. 8564 isFunctionTemplateSpecialization = true; 8565 } 8566 } else if (isFriend && isFunctionTemplateSpecialization) { 8567 // This combination is only possible in a recovery case; the user 8568 // wrote something like: 8569 // template <> friend void foo(int); 8570 // which we're recovering from as if the user had written: 8571 // friend void foo<>(int); 8572 // Go ahead and fake up a template id. 8573 HasExplicitTemplateArgs = true; 8574 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8575 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8576 } 8577 8578 // We do not add HD attributes to specializations here because 8579 // they may have different constexpr-ness compared to their 8580 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8581 // may end up with different effective targets. Instead, a 8582 // specialization inherits its target attributes from its template 8583 // in the CheckFunctionTemplateSpecialization() call below. 8584 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8585 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8586 8587 // If it's a friend (and only if it's a friend), it's possible 8588 // that either the specialized function type or the specialized 8589 // template is dependent, and therefore matching will fail. In 8590 // this case, don't check the specialization yet. 8591 bool InstantiationDependent = false; 8592 if (isFunctionTemplateSpecialization && isFriend && 8593 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8594 TemplateSpecializationType::anyDependentTemplateArguments( 8595 TemplateArgs, 8596 InstantiationDependent))) { 8597 assert(HasExplicitTemplateArgs && 8598 "friend function specialization without template args"); 8599 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8600 Previous)) 8601 NewFD->setInvalidDecl(); 8602 } else if (isFunctionTemplateSpecialization) { 8603 if (CurContext->isDependentContext() && CurContext->isRecord() 8604 && !isFriend) { 8605 isDependentClassScopeExplicitSpecialization = true; 8606 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8607 diag::ext_function_specialization_in_class : 8608 diag::err_function_specialization_in_class) 8609 << NewFD->getDeclName(); 8610 } else if (CheckFunctionTemplateSpecialization(NewFD, 8611 (HasExplicitTemplateArgs ? &TemplateArgs 8612 : nullptr), 8613 Previous)) 8614 NewFD->setInvalidDecl(); 8615 8616 // C++ [dcl.stc]p1: 8617 // A storage-class-specifier shall not be specified in an explicit 8618 // specialization (14.7.3) 8619 FunctionTemplateSpecializationInfo *Info = 8620 NewFD->getTemplateSpecializationInfo(); 8621 if (Info && SC != SC_None) { 8622 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8623 Diag(NewFD->getLocation(), 8624 diag::err_explicit_specialization_inconsistent_storage_class) 8625 << SC 8626 << FixItHint::CreateRemoval( 8627 D.getDeclSpec().getStorageClassSpecLoc()); 8628 8629 else 8630 Diag(NewFD->getLocation(), 8631 diag::ext_explicit_specialization_storage_class) 8632 << FixItHint::CreateRemoval( 8633 D.getDeclSpec().getStorageClassSpecLoc()); 8634 } 8635 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8636 if (CheckMemberSpecialization(NewFD, Previous)) 8637 NewFD->setInvalidDecl(); 8638 } 8639 8640 // Perform semantic checking on the function declaration. 8641 if (!isDependentClassScopeExplicitSpecialization) { 8642 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8643 CheckMain(NewFD, D.getDeclSpec()); 8644 8645 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8646 CheckMSVCRTEntryPoint(NewFD); 8647 8648 if (!NewFD->isInvalidDecl()) 8649 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8650 isMemberSpecialization)); 8651 else if (!Previous.empty()) 8652 // Recover gracefully from an invalid redeclaration. 8653 D.setRedeclaration(true); 8654 } 8655 8656 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8657 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8658 "previous declaration set still overloaded"); 8659 8660 NamedDecl *PrincipalDecl = (FunctionTemplate 8661 ? cast<NamedDecl>(FunctionTemplate) 8662 : NewFD); 8663 8664 if (isFriend && NewFD->getPreviousDecl()) { 8665 AccessSpecifier Access = AS_public; 8666 if (!NewFD->isInvalidDecl()) 8667 Access = NewFD->getPreviousDecl()->getAccess(); 8668 8669 NewFD->setAccess(Access); 8670 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8671 } 8672 8673 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8674 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8675 PrincipalDecl->setNonMemberOperator(); 8676 8677 // If we have a function template, check the template parameter 8678 // list. This will check and merge default template arguments. 8679 if (FunctionTemplate) { 8680 FunctionTemplateDecl *PrevTemplate = 8681 FunctionTemplate->getPreviousDecl(); 8682 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8683 PrevTemplate ? PrevTemplate->getTemplateParameters() 8684 : nullptr, 8685 D.getDeclSpec().isFriendSpecified() 8686 ? (D.isFunctionDefinition() 8687 ? TPC_FriendFunctionTemplateDefinition 8688 : TPC_FriendFunctionTemplate) 8689 : (D.getCXXScopeSpec().isSet() && 8690 DC && DC->isRecord() && 8691 DC->isDependentContext()) 8692 ? TPC_ClassTemplateMember 8693 : TPC_FunctionTemplate); 8694 } 8695 8696 if (NewFD->isInvalidDecl()) { 8697 // Ignore all the rest of this. 8698 } else if (!D.isRedeclaration()) { 8699 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8700 AddToScope }; 8701 // Fake up an access specifier if it's supposed to be a class member. 8702 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8703 NewFD->setAccess(AS_public); 8704 8705 // Qualified decls generally require a previous declaration. 8706 if (D.getCXXScopeSpec().isSet()) { 8707 // ...with the major exception of templated-scope or 8708 // dependent-scope friend declarations. 8709 8710 // TODO: we currently also suppress this check in dependent 8711 // contexts because (1) the parameter depth will be off when 8712 // matching friend templates and (2) we might actually be 8713 // selecting a friend based on a dependent factor. But there 8714 // are situations where these conditions don't apply and we 8715 // can actually do this check immediately. 8716 if (isFriend && 8717 (TemplateParamLists.size() || 8718 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8719 CurContext->isDependentContext())) { 8720 // ignore these 8721 } else { 8722 // The user tried to provide an out-of-line definition for a 8723 // function that is a member of a class or namespace, but there 8724 // was no such member function declared (C++ [class.mfct]p2, 8725 // C++ [namespace.memdef]p2). For example: 8726 // 8727 // class X { 8728 // void f() const; 8729 // }; 8730 // 8731 // void X::f() { } // ill-formed 8732 // 8733 // Complain about this problem, and attempt to suggest close 8734 // matches (e.g., those that differ only in cv-qualifiers and 8735 // whether the parameter types are references). 8736 8737 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8738 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8739 AddToScope = ExtraArgs.AddToScope; 8740 return Result; 8741 } 8742 } 8743 8744 // Unqualified local friend declarations are required to resolve 8745 // to something. 8746 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8747 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8748 *this, Previous, NewFD, ExtraArgs, true, S)) { 8749 AddToScope = ExtraArgs.AddToScope; 8750 return Result; 8751 } 8752 } 8753 } else if (!D.isFunctionDefinition() && 8754 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8755 !isFriend && !isFunctionTemplateSpecialization && 8756 !isMemberSpecialization) { 8757 // An out-of-line member function declaration must also be a 8758 // definition (C++ [class.mfct]p2). 8759 // Note that this is not the case for explicit specializations of 8760 // function templates or member functions of class templates, per 8761 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8762 // extension for compatibility with old SWIG code which likes to 8763 // generate them. 8764 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8765 << D.getCXXScopeSpec().getRange(); 8766 } 8767 } 8768 8769 ProcessPragmaWeak(S, NewFD); 8770 checkAttributesAfterMerging(*this, *NewFD); 8771 8772 AddKnownFunctionAttributes(NewFD); 8773 8774 if (NewFD->hasAttr<OverloadableAttr>() && 8775 !NewFD->getType()->getAs<FunctionProtoType>()) { 8776 Diag(NewFD->getLocation(), 8777 diag::err_attribute_overloadable_no_prototype) 8778 << NewFD; 8779 8780 // Turn this into a variadic function with no parameters. 8781 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8782 FunctionProtoType::ExtProtoInfo EPI( 8783 Context.getDefaultCallingConvention(true, false)); 8784 EPI.Variadic = true; 8785 EPI.ExtInfo = FT->getExtInfo(); 8786 8787 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8788 NewFD->setType(R); 8789 } 8790 8791 // If there's a #pragma GCC visibility in scope, and this isn't a class 8792 // member, set the visibility of this function. 8793 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8794 AddPushedVisibilityAttribute(NewFD); 8795 8796 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8797 // marking the function. 8798 AddCFAuditedAttribute(NewFD); 8799 8800 // If this is a function definition, check if we have to apply optnone due to 8801 // a pragma. 8802 if(D.isFunctionDefinition()) 8803 AddRangeBasedOptnone(NewFD); 8804 8805 // If this is the first declaration of an extern C variable, update 8806 // the map of such variables. 8807 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8808 isIncompleteDeclExternC(*this, NewFD)) 8809 RegisterLocallyScopedExternCDecl(NewFD, S); 8810 8811 // Set this FunctionDecl's range up to the right paren. 8812 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8813 8814 if (D.isRedeclaration() && !Previous.empty()) { 8815 checkDLLAttributeRedeclaration( 8816 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8817 isMemberSpecialization || isFunctionTemplateSpecialization, 8818 D.isFunctionDefinition()); 8819 } 8820 8821 if (getLangOpts().CUDA) { 8822 IdentifierInfo *II = NewFD->getIdentifier(); 8823 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8824 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8825 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8826 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8827 8828 Context.setcudaConfigureCallDecl(NewFD); 8829 } 8830 8831 // Variadic functions, other than a *declaration* of printf, are not allowed 8832 // in device-side CUDA code, unless someone passed 8833 // -fcuda-allow-variadic-functions. 8834 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8835 (NewFD->hasAttr<CUDADeviceAttr>() || 8836 NewFD->hasAttr<CUDAGlobalAttr>()) && 8837 !(II && II->isStr("printf") && NewFD->isExternC() && 8838 !D.isFunctionDefinition())) { 8839 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8840 } 8841 } 8842 8843 if (getLangOpts().CPlusPlus) { 8844 if (FunctionTemplate) { 8845 if (NewFD->isInvalidDecl()) 8846 FunctionTemplate->setInvalidDecl(); 8847 return FunctionTemplate; 8848 } 8849 } 8850 8851 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8852 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8853 if ((getLangOpts().OpenCLVersion >= 120) 8854 && (SC == SC_Static)) { 8855 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8856 D.setInvalidType(); 8857 } 8858 8859 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8860 if (!NewFD->getReturnType()->isVoidType()) { 8861 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8862 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8863 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8864 : FixItHint()); 8865 D.setInvalidType(); 8866 } 8867 8868 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8869 for (auto Param : NewFD->parameters()) 8870 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8871 } 8872 for (const ParmVarDecl *Param : NewFD->parameters()) { 8873 QualType PT = Param->getType(); 8874 8875 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8876 // types. 8877 if (getLangOpts().OpenCLVersion >= 200) { 8878 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8879 QualType ElemTy = PipeTy->getElementType(); 8880 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8881 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8882 D.setInvalidType(); 8883 } 8884 } 8885 } 8886 } 8887 8888 MarkUnusedFileScopedDecl(NewFD); 8889 8890 // Here we have an function template explicit specialization at class scope. 8891 // The actually specialization will be postponed to template instatiation 8892 // time via the ClassScopeFunctionSpecializationDecl node. 8893 if (isDependentClassScopeExplicitSpecialization) { 8894 ClassScopeFunctionSpecializationDecl *NewSpec = 8895 ClassScopeFunctionSpecializationDecl::Create( 8896 Context, CurContext, SourceLocation(), 8897 cast<CXXMethodDecl>(NewFD), 8898 HasExplicitTemplateArgs, TemplateArgs); 8899 CurContext->addDecl(NewSpec); 8900 AddToScope = false; 8901 } 8902 8903 return NewFD; 8904 } 8905 8906 /// \brief Checks if the new declaration declared in dependent context must be 8907 /// put in the same redeclaration chain as the specified declaration. 8908 /// 8909 /// \param D Declaration that is checked. 8910 /// \param PrevDecl Previous declaration found with proper lookup method for the 8911 /// same declaration name. 8912 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8913 /// belongs to. 8914 /// 8915 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8916 // Any declarations should be put into redeclaration chains except for 8917 // friend declaration in a dependent context that names a function in 8918 // namespace scope. 8919 // 8920 // This allows to compile code like: 8921 // 8922 // void func(); 8923 // template<typename T> class C1 { friend void func() { } }; 8924 // template<typename T> class C2 { friend void func() { } }; 8925 // 8926 // This code snippet is a valid code unless both templates are instantiated. 8927 return !(D->getLexicalDeclContext()->isDependentContext() && 8928 D->getDeclContext()->isFileContext() && 8929 D->getFriendObjectKind() != Decl::FOK_None); 8930 } 8931 8932 /// \brief Perform semantic checking of a new function declaration. 8933 /// 8934 /// Performs semantic analysis of the new function declaration 8935 /// NewFD. This routine performs all semantic checking that does not 8936 /// require the actual declarator involved in the declaration, and is 8937 /// used both for the declaration of functions as they are parsed 8938 /// (called via ActOnDeclarator) and for the declaration of functions 8939 /// that have been instantiated via C++ template instantiation (called 8940 /// via InstantiateDecl). 8941 /// 8942 /// \param IsMemberSpecialization whether this new function declaration is 8943 /// a member specialization (that replaces any definition provided by the 8944 /// previous declaration). 8945 /// 8946 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8947 /// 8948 /// \returns true if the function declaration is a redeclaration. 8949 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8950 LookupResult &Previous, 8951 bool IsMemberSpecialization) { 8952 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8953 "Variably modified return types are not handled here"); 8954 8955 // Determine whether the type of this function should be merged with 8956 // a previous visible declaration. This never happens for functions in C++, 8957 // and always happens in C if the previous declaration was visible. 8958 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8959 !Previous.isShadowed(); 8960 8961 bool Redeclaration = false; 8962 NamedDecl *OldDecl = nullptr; 8963 8964 // Merge or overload the declaration with an existing declaration of 8965 // the same name, if appropriate. 8966 if (!Previous.empty()) { 8967 // Determine whether NewFD is an overload of PrevDecl or 8968 // a declaration that requires merging. If it's an overload, 8969 // there's no more work to do here; we'll just add the new 8970 // function to the scope. 8971 if (!AllowOverloadingOfFunction(Previous, Context)) { 8972 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8973 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8974 Redeclaration = true; 8975 OldDecl = Candidate; 8976 } 8977 } else { 8978 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8979 /*NewIsUsingDecl*/ false)) { 8980 case Ovl_Match: 8981 Redeclaration = true; 8982 break; 8983 8984 case Ovl_NonFunction: 8985 Redeclaration = true; 8986 break; 8987 8988 case Ovl_Overload: 8989 Redeclaration = false; 8990 break; 8991 } 8992 8993 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8994 // If a function name is overloadable in C, then every function 8995 // with that name must be marked "overloadable". 8996 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8997 << Redeclaration << NewFD; 8998 NamedDecl *OverloadedDecl = nullptr; 8999 if (Redeclaration) 9000 OverloadedDecl = OldDecl; 9001 else if (!Previous.empty()) 9002 OverloadedDecl = Previous.getRepresentativeDecl(); 9003 if (OverloadedDecl) 9004 Diag(OverloadedDecl->getLocation(), 9005 diag::note_attribute_overloadable_prev_overload); 9006 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9007 } 9008 } 9009 } 9010 9011 // Check for a previous extern "C" declaration with this name. 9012 if (!Redeclaration && 9013 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9014 if (!Previous.empty()) { 9015 // This is an extern "C" declaration with the same name as a previous 9016 // declaration, and thus redeclares that entity... 9017 Redeclaration = true; 9018 OldDecl = Previous.getFoundDecl(); 9019 MergeTypeWithPrevious = false; 9020 9021 // ... except in the presence of __attribute__((overloadable)). 9022 if (OldDecl->hasAttr<OverloadableAttr>()) { 9023 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9024 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9025 << Redeclaration << NewFD; 9026 Diag(Previous.getFoundDecl()->getLocation(), 9027 diag::note_attribute_overloadable_prev_overload); 9028 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9029 } 9030 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9031 Redeclaration = false; 9032 OldDecl = nullptr; 9033 } 9034 } 9035 } 9036 } 9037 9038 // C++11 [dcl.constexpr]p8: 9039 // A constexpr specifier for a non-static member function that is not 9040 // a constructor declares that member function to be const. 9041 // 9042 // This needs to be delayed until we know whether this is an out-of-line 9043 // definition of a static member function. 9044 // 9045 // This rule is not present in C++1y, so we produce a backwards 9046 // compatibility warning whenever it happens in C++11. 9047 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9048 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9049 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9050 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9051 CXXMethodDecl *OldMD = nullptr; 9052 if (OldDecl) 9053 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9054 if (!OldMD || !OldMD->isStatic()) { 9055 const FunctionProtoType *FPT = 9056 MD->getType()->castAs<FunctionProtoType>(); 9057 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9058 EPI.TypeQuals |= Qualifiers::Const; 9059 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9060 FPT->getParamTypes(), EPI)); 9061 9062 // Warn that we did this, if we're not performing template instantiation. 9063 // In that case, we'll have warned already when the template was defined. 9064 if (!inTemplateInstantiation()) { 9065 SourceLocation AddConstLoc; 9066 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9067 .IgnoreParens().getAs<FunctionTypeLoc>()) 9068 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9069 9070 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9071 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9072 } 9073 } 9074 } 9075 9076 if (Redeclaration) { 9077 // NewFD and OldDecl represent declarations that need to be 9078 // merged. 9079 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9080 NewFD->setInvalidDecl(); 9081 return Redeclaration; 9082 } 9083 9084 Previous.clear(); 9085 Previous.addDecl(OldDecl); 9086 9087 if (FunctionTemplateDecl *OldTemplateDecl 9088 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9089 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9090 FunctionTemplateDecl *NewTemplateDecl 9091 = NewFD->getDescribedFunctionTemplate(); 9092 assert(NewTemplateDecl && "Template/non-template mismatch"); 9093 if (CXXMethodDecl *Method 9094 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9095 Method->setAccess(OldTemplateDecl->getAccess()); 9096 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9097 } 9098 9099 // If this is an explicit specialization of a member that is a function 9100 // template, mark it as a member specialization. 9101 if (IsMemberSpecialization && 9102 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9103 NewTemplateDecl->setMemberSpecialization(); 9104 assert(OldTemplateDecl->isMemberSpecialization()); 9105 // Explicit specializations of a member template do not inherit deleted 9106 // status from the parent member template that they are specializing. 9107 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9108 FunctionDecl *const OldTemplatedDecl = 9109 OldTemplateDecl->getTemplatedDecl(); 9110 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9111 OldTemplatedDecl->setDeletedAsWritten(false); 9112 } 9113 } 9114 9115 } else { 9116 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9117 // This needs to happen first so that 'inline' propagates. 9118 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9119 if (isa<CXXMethodDecl>(NewFD)) 9120 NewFD->setAccess(OldDecl->getAccess()); 9121 } 9122 } 9123 } 9124 9125 // Semantic checking for this function declaration (in isolation). 9126 9127 if (getLangOpts().CPlusPlus) { 9128 // C++-specific checks. 9129 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9130 CheckConstructor(Constructor); 9131 } else if (CXXDestructorDecl *Destructor = 9132 dyn_cast<CXXDestructorDecl>(NewFD)) { 9133 CXXRecordDecl *Record = Destructor->getParent(); 9134 QualType ClassType = Context.getTypeDeclType(Record); 9135 9136 // FIXME: Shouldn't we be able to perform this check even when the class 9137 // type is dependent? Both gcc and edg can handle that. 9138 if (!ClassType->isDependentType()) { 9139 DeclarationName Name 9140 = Context.DeclarationNames.getCXXDestructorName( 9141 Context.getCanonicalType(ClassType)); 9142 if (NewFD->getDeclName() != Name) { 9143 Diag(NewFD->getLocation(), diag::err_destructor_name); 9144 NewFD->setInvalidDecl(); 9145 return Redeclaration; 9146 } 9147 } 9148 } else if (CXXConversionDecl *Conversion 9149 = dyn_cast<CXXConversionDecl>(NewFD)) { 9150 ActOnConversionDeclarator(Conversion); 9151 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9152 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9153 CheckDeductionGuideTemplate(TD); 9154 9155 // A deduction guide is not on the list of entities that can be 9156 // explicitly specialized. 9157 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9158 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9159 << /*explicit specialization*/ 1; 9160 } 9161 9162 // Find any virtual functions that this function overrides. 9163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9164 if (!Method->isFunctionTemplateSpecialization() && 9165 !Method->getDescribedFunctionTemplate() && 9166 Method->isCanonicalDecl()) { 9167 if (AddOverriddenMethods(Method->getParent(), Method)) { 9168 // If the function was marked as "static", we have a problem. 9169 if (NewFD->getStorageClass() == SC_Static) { 9170 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9171 } 9172 } 9173 } 9174 9175 if (Method->isStatic()) 9176 checkThisInStaticMemberFunctionType(Method); 9177 } 9178 9179 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9180 if (NewFD->isOverloadedOperator() && 9181 CheckOverloadedOperatorDeclaration(NewFD)) { 9182 NewFD->setInvalidDecl(); 9183 return Redeclaration; 9184 } 9185 9186 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9187 if (NewFD->getLiteralIdentifier() && 9188 CheckLiteralOperatorDeclaration(NewFD)) { 9189 NewFD->setInvalidDecl(); 9190 return Redeclaration; 9191 } 9192 9193 // In C++, check default arguments now that we have merged decls. Unless 9194 // the lexical context is the class, because in this case this is done 9195 // during delayed parsing anyway. 9196 if (!CurContext->isRecord()) 9197 CheckCXXDefaultArguments(NewFD); 9198 9199 // If this function declares a builtin function, check the type of this 9200 // declaration against the expected type for the builtin. 9201 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9202 ASTContext::GetBuiltinTypeError Error; 9203 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9204 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9205 // If the type of the builtin differs only in its exception 9206 // specification, that's OK. 9207 // FIXME: If the types do differ in this way, it would be better to 9208 // retain the 'noexcept' form of the type. 9209 if (!T.isNull() && 9210 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9211 NewFD->getType())) 9212 // The type of this function differs from the type of the builtin, 9213 // so forget about the builtin entirely. 9214 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9215 } 9216 9217 // If this function is declared as being extern "C", then check to see if 9218 // the function returns a UDT (class, struct, or union type) that is not C 9219 // compatible, and if it does, warn the user. 9220 // But, issue any diagnostic on the first declaration only. 9221 if (Previous.empty() && NewFD->isExternC()) { 9222 QualType R = NewFD->getReturnType(); 9223 if (R->isIncompleteType() && !R->isVoidType()) 9224 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9225 << NewFD << R; 9226 else if (!R.isPODType(Context) && !R->isVoidType() && 9227 !R->isObjCObjectPointerType()) 9228 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9229 } 9230 9231 // C++1z [dcl.fct]p6: 9232 // [...] whether the function has a non-throwing exception-specification 9233 // [is] part of the function type 9234 // 9235 // This results in an ABI break between C++14 and C++17 for functions whose 9236 // declared type includes an exception-specification in a parameter or 9237 // return type. (Exception specifications on the function itself are OK in 9238 // most cases, and exception specifications are not permitted in most other 9239 // contexts where they could make it into a mangling.) 9240 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9241 auto HasNoexcept = [&](QualType T) -> bool { 9242 // Strip off declarator chunks that could be between us and a function 9243 // type. We don't need to look far, exception specifications are very 9244 // restricted prior to C++17. 9245 if (auto *RT = T->getAs<ReferenceType>()) 9246 T = RT->getPointeeType(); 9247 else if (T->isAnyPointerType()) 9248 T = T->getPointeeType(); 9249 else if (auto *MPT = T->getAs<MemberPointerType>()) 9250 T = MPT->getPointeeType(); 9251 if (auto *FPT = T->getAs<FunctionProtoType>()) 9252 if (FPT->isNothrow(Context)) 9253 return true; 9254 return false; 9255 }; 9256 9257 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9258 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9259 for (QualType T : FPT->param_types()) 9260 AnyNoexcept |= HasNoexcept(T); 9261 if (AnyNoexcept) 9262 Diag(NewFD->getLocation(), 9263 diag::warn_cxx1z_compat_exception_spec_in_signature) 9264 << NewFD; 9265 } 9266 9267 if (!Redeclaration && LangOpts.CUDA) 9268 checkCUDATargetOverload(NewFD, Previous); 9269 } 9270 return Redeclaration; 9271 } 9272 9273 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9274 // C++11 [basic.start.main]p3: 9275 // A program that [...] declares main to be inline, static or 9276 // constexpr is ill-formed. 9277 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9278 // appear in a declaration of main. 9279 // static main is not an error under C99, but we should warn about it. 9280 // We accept _Noreturn main as an extension. 9281 if (FD->getStorageClass() == SC_Static) 9282 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9283 ? diag::err_static_main : diag::warn_static_main) 9284 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9285 if (FD->isInlineSpecified()) 9286 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9287 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9288 if (DS.isNoreturnSpecified()) { 9289 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9290 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9291 Diag(NoreturnLoc, diag::ext_noreturn_main); 9292 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9293 << FixItHint::CreateRemoval(NoreturnRange); 9294 } 9295 if (FD->isConstexpr()) { 9296 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9297 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9298 FD->setConstexpr(false); 9299 } 9300 9301 if (getLangOpts().OpenCL) { 9302 Diag(FD->getLocation(), diag::err_opencl_no_main) 9303 << FD->hasAttr<OpenCLKernelAttr>(); 9304 FD->setInvalidDecl(); 9305 return; 9306 } 9307 9308 QualType T = FD->getType(); 9309 assert(T->isFunctionType() && "function decl is not of function type"); 9310 const FunctionType* FT = T->castAs<FunctionType>(); 9311 9312 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9313 // In C with GNU extensions we allow main() to have non-integer return 9314 // type, but we should warn about the extension, and we disable the 9315 // implicit-return-zero rule. 9316 9317 // GCC in C mode accepts qualified 'int'. 9318 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9319 FD->setHasImplicitReturnZero(true); 9320 else { 9321 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9322 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9323 if (RTRange.isValid()) 9324 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9325 << FixItHint::CreateReplacement(RTRange, "int"); 9326 } 9327 } else { 9328 // In C and C++, main magically returns 0 if you fall off the end; 9329 // set the flag which tells us that. 9330 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9331 9332 // All the standards say that main() should return 'int'. 9333 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9334 FD->setHasImplicitReturnZero(true); 9335 else { 9336 // Otherwise, this is just a flat-out error. 9337 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9338 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9339 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9340 : FixItHint()); 9341 FD->setInvalidDecl(true); 9342 } 9343 } 9344 9345 // Treat protoless main() as nullary. 9346 if (isa<FunctionNoProtoType>(FT)) return; 9347 9348 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9349 unsigned nparams = FTP->getNumParams(); 9350 assert(FD->getNumParams() == nparams); 9351 9352 bool HasExtraParameters = (nparams > 3); 9353 9354 if (FTP->isVariadic()) { 9355 Diag(FD->getLocation(), diag::ext_variadic_main); 9356 // FIXME: if we had information about the location of the ellipsis, we 9357 // could add a FixIt hint to remove it as a parameter. 9358 } 9359 9360 // Darwin passes an undocumented fourth argument of type char**. If 9361 // other platforms start sprouting these, the logic below will start 9362 // getting shifty. 9363 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9364 HasExtraParameters = false; 9365 9366 if (HasExtraParameters) { 9367 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9368 FD->setInvalidDecl(true); 9369 nparams = 3; 9370 } 9371 9372 // FIXME: a lot of the following diagnostics would be improved 9373 // if we had some location information about types. 9374 9375 QualType CharPP = 9376 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9377 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9378 9379 for (unsigned i = 0; i < nparams; ++i) { 9380 QualType AT = FTP->getParamType(i); 9381 9382 bool mismatch = true; 9383 9384 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9385 mismatch = false; 9386 else if (Expected[i] == CharPP) { 9387 // As an extension, the following forms are okay: 9388 // char const ** 9389 // char const * const * 9390 // char * const * 9391 9392 QualifierCollector qs; 9393 const PointerType* PT; 9394 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9395 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9396 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9397 Context.CharTy)) { 9398 qs.removeConst(); 9399 mismatch = !qs.empty(); 9400 } 9401 } 9402 9403 if (mismatch) { 9404 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9405 // TODO: suggest replacing given type with expected type 9406 FD->setInvalidDecl(true); 9407 } 9408 } 9409 9410 if (nparams == 1 && !FD->isInvalidDecl()) { 9411 Diag(FD->getLocation(), diag::warn_main_one_arg); 9412 } 9413 9414 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9415 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9416 FD->setInvalidDecl(); 9417 } 9418 } 9419 9420 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9421 QualType T = FD->getType(); 9422 assert(T->isFunctionType() && "function decl is not of function type"); 9423 const FunctionType *FT = T->castAs<FunctionType>(); 9424 9425 // Set an implicit return of 'zero' if the function can return some integral, 9426 // enumeration, pointer or nullptr type. 9427 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9428 FT->getReturnType()->isAnyPointerType() || 9429 FT->getReturnType()->isNullPtrType()) 9430 // DllMain is exempt because a return value of zero means it failed. 9431 if (FD->getName() != "DllMain") 9432 FD->setHasImplicitReturnZero(true); 9433 9434 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9435 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9436 FD->setInvalidDecl(); 9437 } 9438 } 9439 9440 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9441 // FIXME: Need strict checking. In C89, we need to check for 9442 // any assignment, increment, decrement, function-calls, or 9443 // commas outside of a sizeof. In C99, it's the same list, 9444 // except that the aforementioned are allowed in unevaluated 9445 // expressions. Everything else falls under the 9446 // "may accept other forms of constant expressions" exception. 9447 // (We never end up here for C++, so the constant expression 9448 // rules there don't matter.) 9449 const Expr *Culprit; 9450 if (Init->isConstantInitializer(Context, false, &Culprit)) 9451 return false; 9452 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9453 << Culprit->getSourceRange(); 9454 return true; 9455 } 9456 9457 namespace { 9458 // Visits an initialization expression to see if OrigDecl is evaluated in 9459 // its own initialization and throws a warning if it does. 9460 class SelfReferenceChecker 9461 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9462 Sema &S; 9463 Decl *OrigDecl; 9464 bool isRecordType; 9465 bool isPODType; 9466 bool isReferenceType; 9467 9468 bool isInitList; 9469 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9470 9471 public: 9472 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9473 9474 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9475 S(S), OrigDecl(OrigDecl) { 9476 isPODType = false; 9477 isRecordType = false; 9478 isReferenceType = false; 9479 isInitList = false; 9480 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9481 isPODType = VD->getType().isPODType(S.Context); 9482 isRecordType = VD->getType()->isRecordType(); 9483 isReferenceType = VD->getType()->isReferenceType(); 9484 } 9485 } 9486 9487 // For most expressions, just call the visitor. For initializer lists, 9488 // track the index of the field being initialized since fields are 9489 // initialized in order allowing use of previously initialized fields. 9490 void CheckExpr(Expr *E) { 9491 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9492 if (!InitList) { 9493 Visit(E); 9494 return; 9495 } 9496 9497 // Track and increment the index here. 9498 isInitList = true; 9499 InitFieldIndex.push_back(0); 9500 for (auto Child : InitList->children()) { 9501 CheckExpr(cast<Expr>(Child)); 9502 ++InitFieldIndex.back(); 9503 } 9504 InitFieldIndex.pop_back(); 9505 } 9506 9507 // Returns true if MemberExpr is checked and no futher checking is needed. 9508 // Returns false if additional checking is required. 9509 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9510 llvm::SmallVector<FieldDecl*, 4> Fields; 9511 Expr *Base = E; 9512 bool ReferenceField = false; 9513 9514 // Get the field memebers used. 9515 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9516 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9517 if (!FD) 9518 return false; 9519 Fields.push_back(FD); 9520 if (FD->getType()->isReferenceType()) 9521 ReferenceField = true; 9522 Base = ME->getBase()->IgnoreParenImpCasts(); 9523 } 9524 9525 // Keep checking only if the base Decl is the same. 9526 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9527 if (!DRE || DRE->getDecl() != OrigDecl) 9528 return false; 9529 9530 // A reference field can be bound to an unininitialized field. 9531 if (CheckReference && !ReferenceField) 9532 return true; 9533 9534 // Convert FieldDecls to their index number. 9535 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9536 for (const FieldDecl *I : llvm::reverse(Fields)) 9537 UsedFieldIndex.push_back(I->getFieldIndex()); 9538 9539 // See if a warning is needed by checking the first difference in index 9540 // numbers. If field being used has index less than the field being 9541 // initialized, then the use is safe. 9542 for (auto UsedIter = UsedFieldIndex.begin(), 9543 UsedEnd = UsedFieldIndex.end(), 9544 OrigIter = InitFieldIndex.begin(), 9545 OrigEnd = InitFieldIndex.end(); 9546 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9547 if (*UsedIter < *OrigIter) 9548 return true; 9549 if (*UsedIter > *OrigIter) 9550 break; 9551 } 9552 9553 // TODO: Add a different warning which will print the field names. 9554 HandleDeclRefExpr(DRE); 9555 return true; 9556 } 9557 9558 // For most expressions, the cast is directly above the DeclRefExpr. 9559 // For conditional operators, the cast can be outside the conditional 9560 // operator if both expressions are DeclRefExpr's. 9561 void HandleValue(Expr *E) { 9562 E = E->IgnoreParens(); 9563 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9564 HandleDeclRefExpr(DRE); 9565 return; 9566 } 9567 9568 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9569 Visit(CO->getCond()); 9570 HandleValue(CO->getTrueExpr()); 9571 HandleValue(CO->getFalseExpr()); 9572 return; 9573 } 9574 9575 if (BinaryConditionalOperator *BCO = 9576 dyn_cast<BinaryConditionalOperator>(E)) { 9577 Visit(BCO->getCond()); 9578 HandleValue(BCO->getFalseExpr()); 9579 return; 9580 } 9581 9582 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9583 HandleValue(OVE->getSourceExpr()); 9584 return; 9585 } 9586 9587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9588 if (BO->getOpcode() == BO_Comma) { 9589 Visit(BO->getLHS()); 9590 HandleValue(BO->getRHS()); 9591 return; 9592 } 9593 } 9594 9595 if (isa<MemberExpr>(E)) { 9596 if (isInitList) { 9597 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9598 false /*CheckReference*/)) 9599 return; 9600 } 9601 9602 Expr *Base = E->IgnoreParenImpCasts(); 9603 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9604 // Check for static member variables and don't warn on them. 9605 if (!isa<FieldDecl>(ME->getMemberDecl())) 9606 return; 9607 Base = ME->getBase()->IgnoreParenImpCasts(); 9608 } 9609 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9610 HandleDeclRefExpr(DRE); 9611 return; 9612 } 9613 9614 Visit(E); 9615 } 9616 9617 // Reference types not handled in HandleValue are handled here since all 9618 // uses of references are bad, not just r-value uses. 9619 void VisitDeclRefExpr(DeclRefExpr *E) { 9620 if (isReferenceType) 9621 HandleDeclRefExpr(E); 9622 } 9623 9624 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9625 if (E->getCastKind() == CK_LValueToRValue) { 9626 HandleValue(E->getSubExpr()); 9627 return; 9628 } 9629 9630 Inherited::VisitImplicitCastExpr(E); 9631 } 9632 9633 void VisitMemberExpr(MemberExpr *E) { 9634 if (isInitList) { 9635 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9636 return; 9637 } 9638 9639 // Don't warn on arrays since they can be treated as pointers. 9640 if (E->getType()->canDecayToPointerType()) return; 9641 9642 // Warn when a non-static method call is followed by non-static member 9643 // field accesses, which is followed by a DeclRefExpr. 9644 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9645 bool Warn = (MD && !MD->isStatic()); 9646 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9647 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9648 if (!isa<FieldDecl>(ME->getMemberDecl())) 9649 Warn = false; 9650 Base = ME->getBase()->IgnoreParenImpCasts(); 9651 } 9652 9653 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9654 if (Warn) 9655 HandleDeclRefExpr(DRE); 9656 return; 9657 } 9658 9659 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9660 // Visit that expression. 9661 Visit(Base); 9662 } 9663 9664 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9665 Expr *Callee = E->getCallee(); 9666 9667 if (isa<UnresolvedLookupExpr>(Callee)) 9668 return Inherited::VisitCXXOperatorCallExpr(E); 9669 9670 Visit(Callee); 9671 for (auto Arg: E->arguments()) 9672 HandleValue(Arg->IgnoreParenImpCasts()); 9673 } 9674 9675 void VisitUnaryOperator(UnaryOperator *E) { 9676 // For POD record types, addresses of its own members are well-defined. 9677 if (E->getOpcode() == UO_AddrOf && isRecordType && 9678 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9679 if (!isPODType) 9680 HandleValue(E->getSubExpr()); 9681 return; 9682 } 9683 9684 if (E->isIncrementDecrementOp()) { 9685 HandleValue(E->getSubExpr()); 9686 return; 9687 } 9688 9689 Inherited::VisitUnaryOperator(E); 9690 } 9691 9692 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9693 9694 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9695 if (E->getConstructor()->isCopyConstructor()) { 9696 Expr *ArgExpr = E->getArg(0); 9697 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9698 if (ILE->getNumInits() == 1) 9699 ArgExpr = ILE->getInit(0); 9700 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9701 if (ICE->getCastKind() == CK_NoOp) 9702 ArgExpr = ICE->getSubExpr(); 9703 HandleValue(ArgExpr); 9704 return; 9705 } 9706 Inherited::VisitCXXConstructExpr(E); 9707 } 9708 9709 void VisitCallExpr(CallExpr *E) { 9710 // Treat std::move as a use. 9711 if (E->getNumArgs() == 1) { 9712 if (FunctionDecl *FD = E->getDirectCallee()) { 9713 if (FD->isInStdNamespace() && FD->getIdentifier() && 9714 FD->getIdentifier()->isStr("move")) { 9715 HandleValue(E->getArg(0)); 9716 return; 9717 } 9718 } 9719 } 9720 9721 Inherited::VisitCallExpr(E); 9722 } 9723 9724 void VisitBinaryOperator(BinaryOperator *E) { 9725 if (E->isCompoundAssignmentOp()) { 9726 HandleValue(E->getLHS()); 9727 Visit(E->getRHS()); 9728 return; 9729 } 9730 9731 Inherited::VisitBinaryOperator(E); 9732 } 9733 9734 // A custom visitor for BinaryConditionalOperator is needed because the 9735 // regular visitor would check the condition and true expression separately 9736 // but both point to the same place giving duplicate diagnostics. 9737 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9738 Visit(E->getCond()); 9739 Visit(E->getFalseExpr()); 9740 } 9741 9742 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9743 Decl* ReferenceDecl = DRE->getDecl(); 9744 if (OrigDecl != ReferenceDecl) return; 9745 unsigned diag; 9746 if (isReferenceType) { 9747 diag = diag::warn_uninit_self_reference_in_reference_init; 9748 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9749 diag = diag::warn_static_self_reference_in_init; 9750 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9751 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9752 DRE->getDecl()->getType()->isRecordType()) { 9753 diag = diag::warn_uninit_self_reference_in_init; 9754 } else { 9755 // Local variables will be handled by the CFG analysis. 9756 return; 9757 } 9758 9759 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9760 S.PDiag(diag) 9761 << DRE->getNameInfo().getName() 9762 << OrigDecl->getLocation() 9763 << DRE->getSourceRange()); 9764 } 9765 }; 9766 9767 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9768 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9769 bool DirectInit) { 9770 // Parameters arguments are occassionially constructed with itself, 9771 // for instance, in recursive functions. Skip them. 9772 if (isa<ParmVarDecl>(OrigDecl)) 9773 return; 9774 9775 E = E->IgnoreParens(); 9776 9777 // Skip checking T a = a where T is not a record or reference type. 9778 // Doing so is a way to silence uninitialized warnings. 9779 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9780 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9781 if (ICE->getCastKind() == CK_LValueToRValue) 9782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9783 if (DRE->getDecl() == OrigDecl) 9784 return; 9785 9786 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9787 } 9788 } // end anonymous namespace 9789 9790 namespace { 9791 // Simple wrapper to add the name of a variable or (if no variable is 9792 // available) a DeclarationName into a diagnostic. 9793 struct VarDeclOrName { 9794 VarDecl *VDecl; 9795 DeclarationName Name; 9796 9797 friend const Sema::SemaDiagnosticBuilder & 9798 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9799 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9800 } 9801 }; 9802 } // end anonymous namespace 9803 9804 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9805 DeclarationName Name, QualType Type, 9806 TypeSourceInfo *TSI, 9807 SourceRange Range, bool DirectInit, 9808 Expr *Init) { 9809 bool IsInitCapture = !VDecl; 9810 assert((!VDecl || !VDecl->isInitCapture()) && 9811 "init captures are expected to be deduced prior to initialization"); 9812 9813 VarDeclOrName VN{VDecl, Name}; 9814 9815 DeducedType *Deduced = Type->getContainedDeducedType(); 9816 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 9817 9818 // C++11 [dcl.spec.auto]p3 9819 if (!Init) { 9820 assert(VDecl && "no init for init capture deduction?"); 9821 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 9822 << VDecl->getDeclName() << Type; 9823 return QualType(); 9824 } 9825 9826 ArrayRef<Expr*> DeduceInits = Init; 9827 if (DirectInit) { 9828 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 9829 DeduceInits = PL->exprs(); 9830 } 9831 9832 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 9833 assert(VDecl && "non-auto type for init capture deduction?"); 9834 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9835 InitializationKind Kind = InitializationKind::CreateForInit( 9836 VDecl->getLocation(), DirectInit, Init); 9837 // FIXME: Initialization should not be taking a mutable list of inits. 9838 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 9839 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 9840 InitsCopy); 9841 } 9842 9843 if (DirectInit) { 9844 if (auto *IL = dyn_cast<InitListExpr>(Init)) 9845 DeduceInits = IL->inits(); 9846 } 9847 9848 // Deduction only works if we have exactly one source expression. 9849 if (DeduceInits.empty()) { 9850 // It isn't possible to write this directly, but it is possible to 9851 // end up in this situation with "auto x(some_pack...);" 9852 Diag(Init->getLocStart(), IsInitCapture 9853 ? diag::err_init_capture_no_expression 9854 : diag::err_auto_var_init_no_expression) 9855 << VN << Type << Range; 9856 return QualType(); 9857 } 9858 9859 if (DeduceInits.size() > 1) { 9860 Diag(DeduceInits[1]->getLocStart(), 9861 IsInitCapture ? diag::err_init_capture_multiple_expressions 9862 : diag::err_auto_var_init_multiple_expressions) 9863 << VN << Type << Range; 9864 return QualType(); 9865 } 9866 9867 Expr *DeduceInit = DeduceInits[0]; 9868 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9869 Diag(Init->getLocStart(), IsInitCapture 9870 ? diag::err_init_capture_paren_braces 9871 : diag::err_auto_var_init_paren_braces) 9872 << isa<InitListExpr>(Init) << VN << Type << Range; 9873 return QualType(); 9874 } 9875 9876 // Expressions default to 'id' when we're in a debugger. 9877 bool DefaultedAnyToId = false; 9878 if (getLangOpts().DebuggerCastResultToId && 9879 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9880 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9881 if (Result.isInvalid()) { 9882 return QualType(); 9883 } 9884 Init = Result.get(); 9885 DefaultedAnyToId = true; 9886 } 9887 9888 // C++ [dcl.decomp]p1: 9889 // If the assignment-expression [...] has array type A and no ref-qualifier 9890 // is present, e has type cv A 9891 if (VDecl && isa<DecompositionDecl>(VDecl) && 9892 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 9893 DeduceInit->getType()->isConstantArrayType()) 9894 return Context.getQualifiedType(DeduceInit->getType(), 9895 Type.getQualifiers()); 9896 9897 QualType DeducedType; 9898 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9899 if (!IsInitCapture) 9900 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9901 else if (isa<InitListExpr>(Init)) 9902 Diag(Range.getBegin(), 9903 diag::err_init_capture_deduction_failure_from_init_list) 9904 << VN 9905 << (DeduceInit->getType().isNull() ? TSI->getType() 9906 : DeduceInit->getType()) 9907 << DeduceInit->getSourceRange(); 9908 else 9909 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9910 << VN << TSI->getType() 9911 << (DeduceInit->getType().isNull() ? TSI->getType() 9912 : DeduceInit->getType()) 9913 << DeduceInit->getSourceRange(); 9914 } 9915 9916 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9917 // 'id' instead of a specific object type prevents most of our usual 9918 // checks. 9919 // We only want to warn outside of template instantiations, though: 9920 // inside a template, the 'id' could have come from a parameter. 9921 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 9922 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9923 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9924 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 9925 } 9926 9927 return DeducedType; 9928 } 9929 9930 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 9931 Expr *Init) { 9932 QualType DeducedType = deduceVarTypeFromInitializer( 9933 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 9934 VDecl->getSourceRange(), DirectInit, Init); 9935 if (DeducedType.isNull()) { 9936 VDecl->setInvalidDecl(); 9937 return true; 9938 } 9939 9940 VDecl->setType(DeducedType); 9941 assert(VDecl->isLinkageValid()); 9942 9943 // In ARC, infer lifetime. 9944 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9945 VDecl->setInvalidDecl(); 9946 9947 // If this is a redeclaration, check that the type we just deduced matches 9948 // the previously declared type. 9949 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9950 // We never need to merge the type, because we cannot form an incomplete 9951 // array of auto, nor deduce such a type. 9952 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9953 } 9954 9955 // Check the deduced type is valid for a variable declaration. 9956 CheckVariableDeclarationType(VDecl); 9957 return VDecl->isInvalidDecl(); 9958 } 9959 9960 /// AddInitializerToDecl - Adds the initializer Init to the 9961 /// declaration dcl. If DirectInit is true, this is C++ direct 9962 /// initialization rather than copy initialization. 9963 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 9964 // If there is no declaration, there was an error parsing it. Just ignore 9965 // the initializer. 9966 if (!RealDecl || RealDecl->isInvalidDecl()) { 9967 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9968 return; 9969 } 9970 9971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9972 // Pure-specifiers are handled in ActOnPureSpecifier. 9973 Diag(Method->getLocation(), diag::err_member_function_initialization) 9974 << Method->getDeclName() << Init->getSourceRange(); 9975 Method->setInvalidDecl(); 9976 return; 9977 } 9978 9979 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9980 if (!VDecl) { 9981 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9982 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9983 RealDecl->setInvalidDecl(); 9984 return; 9985 } 9986 9987 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9988 if (VDecl->getType()->isUndeducedType()) { 9989 // Attempt typo correction early so that the type of the init expression can 9990 // be deduced based on the chosen correction if the original init contains a 9991 // TypoExpr. 9992 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9993 if (!Res.isUsable()) { 9994 RealDecl->setInvalidDecl(); 9995 return; 9996 } 9997 Init = Res.get(); 9998 9999 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10000 return; 10001 } 10002 10003 // dllimport cannot be used on variable definitions. 10004 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10005 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10006 VDecl->setInvalidDecl(); 10007 return; 10008 } 10009 10010 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10011 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10012 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10013 VDecl->setInvalidDecl(); 10014 return; 10015 } 10016 10017 if (!VDecl->getType()->isDependentType()) { 10018 // A definition must end up with a complete type, which means it must be 10019 // complete with the restriction that an array type might be completed by 10020 // the initializer; note that later code assumes this restriction. 10021 QualType BaseDeclType = VDecl->getType(); 10022 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10023 BaseDeclType = Array->getElementType(); 10024 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10025 diag::err_typecheck_decl_incomplete_type)) { 10026 RealDecl->setInvalidDecl(); 10027 return; 10028 } 10029 10030 // The variable can not have an abstract class type. 10031 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10032 diag::err_abstract_type_in_decl, 10033 AbstractVariableType)) 10034 VDecl->setInvalidDecl(); 10035 } 10036 10037 // If adding the initializer will turn this declaration into a definition, 10038 // and we already have a definition for this variable, diagnose or otherwise 10039 // handle the situation. 10040 VarDecl *Def; 10041 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10042 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10043 !VDecl->isThisDeclarationADemotedDefinition() && 10044 checkVarDeclRedefinition(Def, VDecl)) 10045 return; 10046 10047 if (getLangOpts().CPlusPlus) { 10048 // C++ [class.static.data]p4 10049 // If a static data member is of const integral or const 10050 // enumeration type, its declaration in the class definition can 10051 // specify a constant-initializer which shall be an integral 10052 // constant expression (5.19). In that case, the member can appear 10053 // in integral constant expressions. The member shall still be 10054 // defined in a namespace scope if it is used in the program and the 10055 // namespace scope definition shall not contain an initializer. 10056 // 10057 // We already performed a redefinition check above, but for static 10058 // data members we also need to check whether there was an in-class 10059 // declaration with an initializer. 10060 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10061 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10062 << VDecl->getDeclName(); 10063 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10064 diag::note_previous_initializer) 10065 << 0; 10066 return; 10067 } 10068 10069 if (VDecl->hasLocalStorage()) 10070 getCurFunction()->setHasBranchProtectedScope(); 10071 10072 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10073 VDecl->setInvalidDecl(); 10074 return; 10075 } 10076 } 10077 10078 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10079 // a kernel function cannot be initialized." 10080 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10081 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10082 VDecl->setInvalidDecl(); 10083 return; 10084 } 10085 10086 // Get the decls type and save a reference for later, since 10087 // CheckInitializerTypes may change it. 10088 QualType DclT = VDecl->getType(), SavT = DclT; 10089 10090 // Expressions default to 'id' when we're in a debugger 10091 // and we are assigning it to a variable of Objective-C pointer type. 10092 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10093 Init->getType() == Context.UnknownAnyTy) { 10094 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10095 if (Result.isInvalid()) { 10096 VDecl->setInvalidDecl(); 10097 return; 10098 } 10099 Init = Result.get(); 10100 } 10101 10102 // Perform the initialization. 10103 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10104 if (!VDecl->isInvalidDecl()) { 10105 // Handle errors like: int a({0}) 10106 if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 && 10107 !canInitializeWithParenthesizedList(VDecl->getType())) 10108 if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) { 10109 Diag(VDecl->getLocation(), diag::err_list_init_in_parens) 10110 << VDecl->getType() << CXXDirectInit->getSourceRange() 10111 << FixItHint::CreateRemoval(CXXDirectInit->getLocStart()) 10112 << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd()); 10113 Init = IList; 10114 CXXDirectInit = nullptr; 10115 } 10116 10117 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10118 InitializationKind Kind = InitializationKind::CreateForInit( 10119 VDecl->getLocation(), DirectInit, Init); 10120 10121 MultiExprArg Args = Init; 10122 if (CXXDirectInit) 10123 Args = MultiExprArg(CXXDirectInit->getExprs(), 10124 CXXDirectInit->getNumExprs()); 10125 10126 // Try to correct any TypoExprs in the initialization arguments. 10127 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10128 ExprResult Res = CorrectDelayedTyposInExpr( 10129 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10130 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10131 return Init.Failed() ? ExprError() : E; 10132 }); 10133 if (Res.isInvalid()) { 10134 VDecl->setInvalidDecl(); 10135 } else if (Res.get() != Args[Idx]) { 10136 Args[Idx] = Res.get(); 10137 } 10138 } 10139 if (VDecl->isInvalidDecl()) 10140 return; 10141 10142 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10143 /*TopLevelOfInitList=*/false, 10144 /*TreatUnavailableAsInvalid=*/false); 10145 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10146 if (Result.isInvalid()) { 10147 VDecl->setInvalidDecl(); 10148 return; 10149 } 10150 10151 Init = Result.getAs<Expr>(); 10152 } 10153 10154 // Check for self-references within variable initializers. 10155 // Variables declared within a function/method body (except for references) 10156 // are handled by a dataflow analysis. 10157 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10158 VDecl->getType()->isReferenceType()) { 10159 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10160 } 10161 10162 // If the type changed, it means we had an incomplete type that was 10163 // completed by the initializer. For example: 10164 // int ary[] = { 1, 3, 5 }; 10165 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10166 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10167 VDecl->setType(DclT); 10168 10169 if (!VDecl->isInvalidDecl()) { 10170 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10171 10172 if (VDecl->hasAttr<BlocksAttr>()) 10173 checkRetainCycles(VDecl, Init); 10174 10175 // It is safe to assign a weak reference into a strong variable. 10176 // Although this code can still have problems: 10177 // id x = self.weakProp; 10178 // id y = self.weakProp; 10179 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10180 // paths through the function. This should be revisited if 10181 // -Wrepeated-use-of-weak is made flow-sensitive. 10182 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 10183 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10184 Init->getLocStart())) 10185 getCurFunction()->markSafeWeakUse(Init); 10186 } 10187 10188 // The initialization is usually a full-expression. 10189 // 10190 // FIXME: If this is a braced initialization of an aggregate, it is not 10191 // an expression, and each individual field initializer is a separate 10192 // full-expression. For instance, in: 10193 // 10194 // struct Temp { ~Temp(); }; 10195 // struct S { S(Temp); }; 10196 // struct T { S a, b; } t = { Temp(), Temp() } 10197 // 10198 // we should destroy the first Temp before constructing the second. 10199 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10200 false, 10201 VDecl->isConstexpr()); 10202 if (Result.isInvalid()) { 10203 VDecl->setInvalidDecl(); 10204 return; 10205 } 10206 Init = Result.get(); 10207 10208 // Attach the initializer to the decl. 10209 VDecl->setInit(Init); 10210 10211 if (VDecl->isLocalVarDecl()) { 10212 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10213 // static storage duration shall be constant expressions or string literals. 10214 // C++ does not have this restriction. 10215 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 10216 const Expr *Culprit; 10217 if (VDecl->getStorageClass() == SC_Static) 10218 CheckForConstantInitializer(Init, DclT); 10219 // C89 is stricter than C99 for non-static aggregate types. 10220 // C89 6.5.7p3: All the expressions [...] in an initializer list 10221 // for an object that has aggregate or union type shall be 10222 // constant expressions. 10223 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10224 isa<InitListExpr>(Init) && 10225 !Init->isConstantInitializer(Context, false, &Culprit)) 10226 Diag(Culprit->getExprLoc(), 10227 diag::ext_aggregate_init_not_constant) 10228 << Culprit->getSourceRange(); 10229 } 10230 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10231 VDecl->getLexicalDeclContext()->isRecord()) { 10232 // This is an in-class initialization for a static data member, e.g., 10233 // 10234 // struct S { 10235 // static const int value = 17; 10236 // }; 10237 10238 // C++ [class.mem]p4: 10239 // A member-declarator can contain a constant-initializer only 10240 // if it declares a static member (9.4) of const integral or 10241 // const enumeration type, see 9.4.2. 10242 // 10243 // C++11 [class.static.data]p3: 10244 // If a non-volatile non-inline const static data member is of integral 10245 // or enumeration type, its declaration in the class definition can 10246 // specify a brace-or-equal-initializer in which every initalizer-clause 10247 // that is an assignment-expression is a constant expression. A static 10248 // data member of literal type can be declared in the class definition 10249 // with the constexpr specifier; if so, its declaration shall specify a 10250 // brace-or-equal-initializer in which every initializer-clause that is 10251 // an assignment-expression is a constant expression. 10252 10253 // Do nothing on dependent types. 10254 if (DclT->isDependentType()) { 10255 10256 // Allow any 'static constexpr' members, whether or not they are of literal 10257 // type. We separately check that every constexpr variable is of literal 10258 // type. 10259 } else if (VDecl->isConstexpr()) { 10260 10261 // Require constness. 10262 } else if (!DclT.isConstQualified()) { 10263 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10264 << Init->getSourceRange(); 10265 VDecl->setInvalidDecl(); 10266 10267 // We allow integer constant expressions in all cases. 10268 } else if (DclT->isIntegralOrEnumerationType()) { 10269 // Check whether the expression is a constant expression. 10270 SourceLocation Loc; 10271 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10272 // In C++11, a non-constexpr const static data member with an 10273 // in-class initializer cannot be volatile. 10274 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10275 else if (Init->isValueDependent()) 10276 ; // Nothing to check. 10277 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10278 ; // Ok, it's an ICE! 10279 else if (Init->isEvaluatable(Context)) { 10280 // If we can constant fold the initializer through heroics, accept it, 10281 // but report this as a use of an extension for -pedantic. 10282 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10283 << Init->getSourceRange(); 10284 } else { 10285 // Otherwise, this is some crazy unknown case. Report the issue at the 10286 // location provided by the isIntegerConstantExpr failed check. 10287 Diag(Loc, diag::err_in_class_initializer_non_constant) 10288 << Init->getSourceRange(); 10289 VDecl->setInvalidDecl(); 10290 } 10291 10292 // We allow foldable floating-point constants as an extension. 10293 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10294 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10295 // it anyway and provide a fixit to add the 'constexpr'. 10296 if (getLangOpts().CPlusPlus11) { 10297 Diag(VDecl->getLocation(), 10298 diag::ext_in_class_initializer_float_type_cxx11) 10299 << DclT << Init->getSourceRange(); 10300 Diag(VDecl->getLocStart(), 10301 diag::note_in_class_initializer_float_type_cxx11) 10302 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10303 } else { 10304 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10305 << DclT << Init->getSourceRange(); 10306 10307 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10308 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10309 << Init->getSourceRange(); 10310 VDecl->setInvalidDecl(); 10311 } 10312 } 10313 10314 // Suggest adding 'constexpr' in C++11 for literal types. 10315 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10316 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10317 << DclT << Init->getSourceRange() 10318 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10319 VDecl->setConstexpr(true); 10320 10321 } else { 10322 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10323 << DclT << Init->getSourceRange(); 10324 VDecl->setInvalidDecl(); 10325 } 10326 } else if (VDecl->isFileVarDecl()) { 10327 // In C, extern is typically used to avoid tentative definitions when 10328 // declaring variables in headers, but adding an intializer makes it a 10329 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10330 // In C++, extern is often used to give implictly static const variables 10331 // external linkage, so don't warn in that case. If selectany is present, 10332 // this might be header code intended for C and C++ inclusion, so apply the 10333 // C++ rules. 10334 if (VDecl->getStorageClass() == SC_Extern && 10335 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10336 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10337 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10338 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10339 Diag(VDecl->getLocation(), diag::warn_extern_init); 10340 10341 // C99 6.7.8p4. All file scoped initializers need to be constant. 10342 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10343 CheckForConstantInitializer(Init, DclT); 10344 } 10345 10346 // We will represent direct-initialization similarly to copy-initialization: 10347 // int x(1); -as-> int x = 1; 10348 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10349 // 10350 // Clients that want to distinguish between the two forms, can check for 10351 // direct initializer using VarDecl::getInitStyle(). 10352 // A major benefit is that clients that don't particularly care about which 10353 // exactly form was it (like the CodeGen) can handle both cases without 10354 // special case code. 10355 10356 // C++ 8.5p11: 10357 // The form of initialization (using parentheses or '=') is generally 10358 // insignificant, but does matter when the entity being initialized has a 10359 // class type. 10360 if (CXXDirectInit) { 10361 assert(DirectInit && "Call-style initializer must be direct init."); 10362 VDecl->setInitStyle(VarDecl::CallInit); 10363 } else if (DirectInit) { 10364 // This must be list-initialization. No other way is direct-initialization. 10365 VDecl->setInitStyle(VarDecl::ListInit); 10366 } 10367 10368 CheckCompleteVariableDeclaration(VDecl); 10369 } 10370 10371 /// ActOnInitializerError - Given that there was an error parsing an 10372 /// initializer for the given declaration, try to return to some form 10373 /// of sanity. 10374 void Sema::ActOnInitializerError(Decl *D) { 10375 // Our main concern here is re-establishing invariants like "a 10376 // variable's type is either dependent or complete". 10377 if (!D || D->isInvalidDecl()) return; 10378 10379 VarDecl *VD = dyn_cast<VarDecl>(D); 10380 if (!VD) return; 10381 10382 // Bindings are not usable if we can't make sense of the initializer. 10383 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10384 for (auto *BD : DD->bindings()) 10385 BD->setInvalidDecl(); 10386 10387 // Auto types are meaningless if we can't make sense of the initializer. 10388 if (ParsingInitForAutoVars.count(D)) { 10389 D->setInvalidDecl(); 10390 return; 10391 } 10392 10393 QualType Ty = VD->getType(); 10394 if (Ty->isDependentType()) return; 10395 10396 // Require a complete type. 10397 if (RequireCompleteType(VD->getLocation(), 10398 Context.getBaseElementType(Ty), 10399 diag::err_typecheck_decl_incomplete_type)) { 10400 VD->setInvalidDecl(); 10401 return; 10402 } 10403 10404 // Require a non-abstract type. 10405 if (RequireNonAbstractType(VD->getLocation(), Ty, 10406 diag::err_abstract_type_in_decl, 10407 AbstractVariableType)) { 10408 VD->setInvalidDecl(); 10409 return; 10410 } 10411 10412 // Don't bother complaining about constructors or destructors, 10413 // though. 10414 } 10415 10416 /// Checks if an object of the given type can be initialized with parenthesized 10417 /// init-list. 10418 /// 10419 /// \param TargetType Type of object being initialized. 10420 /// 10421 /// The function is used to detect wrong initializations, such as 'int({0})'. 10422 /// 10423 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) { 10424 return TargetType->isDependentType() || TargetType->isRecordType() || 10425 TargetType->getContainedAutoType(); 10426 } 10427 10428 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10429 // If there is no declaration, there was an error parsing it. Just ignore it. 10430 if (!RealDecl) 10431 return; 10432 10433 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10434 QualType Type = Var->getType(); 10435 10436 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10437 if (isa<DecompositionDecl>(RealDecl)) { 10438 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10439 Var->setInvalidDecl(); 10440 return; 10441 } 10442 10443 if (Type->isUndeducedType() && 10444 DeduceVariableDeclarationType(Var, false, nullptr)) 10445 return; 10446 10447 // C++11 [class.static.data]p3: A static data member can be declared with 10448 // the constexpr specifier; if so, its declaration shall specify 10449 // a brace-or-equal-initializer. 10450 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10451 // the definition of a variable [...] or the declaration of a static data 10452 // member. 10453 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10454 !Var->isThisDeclarationADemotedDefinition()) { 10455 if (Var->isStaticDataMember()) { 10456 // C++1z removes the relevant rule; the in-class declaration is always 10457 // a definition there. 10458 if (!getLangOpts().CPlusPlus1z) { 10459 Diag(Var->getLocation(), 10460 diag::err_constexpr_static_mem_var_requires_init) 10461 << Var->getDeclName(); 10462 Var->setInvalidDecl(); 10463 return; 10464 } 10465 } else { 10466 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10467 Var->setInvalidDecl(); 10468 return; 10469 } 10470 } 10471 10472 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10473 // definition having the concept specifier is called a variable concept. A 10474 // concept definition refers to [...] a variable concept and its initializer. 10475 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10476 if (VTD->isConcept()) { 10477 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10478 Var->setInvalidDecl(); 10479 return; 10480 } 10481 } 10482 10483 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10484 // be initialized. 10485 if (!Var->isInvalidDecl() && 10486 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10487 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10488 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10489 Var->setInvalidDecl(); 10490 return; 10491 } 10492 10493 switch (Var->isThisDeclarationADefinition()) { 10494 case VarDecl::Definition: 10495 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10496 break; 10497 10498 // We have an out-of-line definition of a static data member 10499 // that has an in-class initializer, so we type-check this like 10500 // a declaration. 10501 // 10502 // Fall through 10503 10504 case VarDecl::DeclarationOnly: 10505 // It's only a declaration. 10506 10507 // Block scope. C99 6.7p7: If an identifier for an object is 10508 // declared with no linkage (C99 6.2.2p6), the type for the 10509 // object shall be complete. 10510 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10511 !Var->hasLinkage() && !Var->isInvalidDecl() && 10512 RequireCompleteType(Var->getLocation(), Type, 10513 diag::err_typecheck_decl_incomplete_type)) 10514 Var->setInvalidDecl(); 10515 10516 // Make sure that the type is not abstract. 10517 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10518 RequireNonAbstractType(Var->getLocation(), Type, 10519 diag::err_abstract_type_in_decl, 10520 AbstractVariableType)) 10521 Var->setInvalidDecl(); 10522 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10523 Var->getStorageClass() == SC_PrivateExtern) { 10524 Diag(Var->getLocation(), diag::warn_private_extern); 10525 Diag(Var->getLocation(), diag::note_private_extern); 10526 } 10527 10528 return; 10529 10530 case VarDecl::TentativeDefinition: 10531 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10532 // object that has file scope without an initializer, and without a 10533 // storage-class specifier or with the storage-class specifier "static", 10534 // constitutes a tentative definition. Note: A tentative definition with 10535 // external linkage is valid (C99 6.2.2p5). 10536 if (!Var->isInvalidDecl()) { 10537 if (const IncompleteArrayType *ArrayT 10538 = Context.getAsIncompleteArrayType(Type)) { 10539 if (RequireCompleteType(Var->getLocation(), 10540 ArrayT->getElementType(), 10541 diag::err_illegal_decl_array_incomplete_type)) 10542 Var->setInvalidDecl(); 10543 } else if (Var->getStorageClass() == SC_Static) { 10544 // C99 6.9.2p3: If the declaration of an identifier for an object is 10545 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10546 // declared type shall not be an incomplete type. 10547 // NOTE: code such as the following 10548 // static struct s; 10549 // struct s { int a; }; 10550 // is accepted by gcc. Hence here we issue a warning instead of 10551 // an error and we do not invalidate the static declaration. 10552 // NOTE: to avoid multiple warnings, only check the first declaration. 10553 if (Var->isFirstDecl()) 10554 RequireCompleteType(Var->getLocation(), Type, 10555 diag::ext_typecheck_decl_incomplete_type); 10556 } 10557 } 10558 10559 // Record the tentative definition; we're done. 10560 if (!Var->isInvalidDecl()) 10561 TentativeDefinitions.push_back(Var); 10562 return; 10563 } 10564 10565 // Provide a specific diagnostic for uninitialized variable 10566 // definitions with incomplete array type. 10567 if (Type->isIncompleteArrayType()) { 10568 Diag(Var->getLocation(), 10569 diag::err_typecheck_incomplete_array_needs_initializer); 10570 Var->setInvalidDecl(); 10571 return; 10572 } 10573 10574 // Provide a specific diagnostic for uninitialized variable 10575 // definitions with reference type. 10576 if (Type->isReferenceType()) { 10577 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10578 << Var->getDeclName() 10579 << SourceRange(Var->getLocation(), Var->getLocation()); 10580 Var->setInvalidDecl(); 10581 return; 10582 } 10583 10584 // Do not attempt to type-check the default initializer for a 10585 // variable with dependent type. 10586 if (Type->isDependentType()) 10587 return; 10588 10589 if (Var->isInvalidDecl()) 10590 return; 10591 10592 if (!Var->hasAttr<AliasAttr>()) { 10593 if (RequireCompleteType(Var->getLocation(), 10594 Context.getBaseElementType(Type), 10595 diag::err_typecheck_decl_incomplete_type)) { 10596 Var->setInvalidDecl(); 10597 return; 10598 } 10599 } else { 10600 return; 10601 } 10602 10603 // The variable can not have an abstract class type. 10604 if (RequireNonAbstractType(Var->getLocation(), Type, 10605 diag::err_abstract_type_in_decl, 10606 AbstractVariableType)) { 10607 Var->setInvalidDecl(); 10608 return; 10609 } 10610 10611 // Check for jumps past the implicit initializer. C++0x 10612 // clarifies that this applies to a "variable with automatic 10613 // storage duration", not a "local variable". 10614 // C++11 [stmt.dcl]p3 10615 // A program that jumps from a point where a variable with automatic 10616 // storage duration is not in scope to a point where it is in scope is 10617 // ill-formed unless the variable has scalar type, class type with a 10618 // trivial default constructor and a trivial destructor, a cv-qualified 10619 // version of one of these types, or an array of one of the preceding 10620 // types and is declared without an initializer. 10621 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10622 if (const RecordType *Record 10623 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10624 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10625 // Mark the function for further checking even if the looser rules of 10626 // C++11 do not require such checks, so that we can diagnose 10627 // incompatibilities with C++98. 10628 if (!CXXRecord->isPOD()) 10629 getCurFunction()->setHasBranchProtectedScope(); 10630 } 10631 } 10632 10633 // C++03 [dcl.init]p9: 10634 // If no initializer is specified for an object, and the 10635 // object is of (possibly cv-qualified) non-POD class type (or 10636 // array thereof), the object shall be default-initialized; if 10637 // the object is of const-qualified type, the underlying class 10638 // type shall have a user-declared default 10639 // constructor. Otherwise, if no initializer is specified for 10640 // a non- static object, the object and its subobjects, if 10641 // any, have an indeterminate initial value); if the object 10642 // or any of its subobjects are of const-qualified type, the 10643 // program is ill-formed. 10644 // C++0x [dcl.init]p11: 10645 // If no initializer is specified for an object, the object is 10646 // default-initialized; [...]. 10647 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10648 InitializationKind Kind 10649 = InitializationKind::CreateDefault(Var->getLocation()); 10650 10651 InitializationSequence InitSeq(*this, Entity, Kind, None); 10652 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10653 if (Init.isInvalid()) 10654 Var->setInvalidDecl(); 10655 else if (Init.get()) { 10656 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10657 // This is important for template substitution. 10658 Var->setInitStyle(VarDecl::CallInit); 10659 } 10660 10661 CheckCompleteVariableDeclaration(Var); 10662 } 10663 } 10664 10665 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10666 // If there is no declaration, there was an error parsing it. Ignore it. 10667 if (!D) 10668 return; 10669 10670 VarDecl *VD = dyn_cast<VarDecl>(D); 10671 if (!VD) { 10672 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10673 D->setInvalidDecl(); 10674 return; 10675 } 10676 10677 VD->setCXXForRangeDecl(true); 10678 10679 // for-range-declaration cannot be given a storage class specifier. 10680 int Error = -1; 10681 switch (VD->getStorageClass()) { 10682 case SC_None: 10683 break; 10684 case SC_Extern: 10685 Error = 0; 10686 break; 10687 case SC_Static: 10688 Error = 1; 10689 break; 10690 case SC_PrivateExtern: 10691 Error = 2; 10692 break; 10693 case SC_Auto: 10694 Error = 3; 10695 break; 10696 case SC_Register: 10697 Error = 4; 10698 break; 10699 } 10700 if (Error != -1) { 10701 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10702 << VD->getDeclName() << Error; 10703 D->setInvalidDecl(); 10704 } 10705 } 10706 10707 StmtResult 10708 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10709 IdentifierInfo *Ident, 10710 ParsedAttributes &Attrs, 10711 SourceLocation AttrEnd) { 10712 // C++1y [stmt.iter]p1: 10713 // A range-based for statement of the form 10714 // for ( for-range-identifier : for-range-initializer ) statement 10715 // is equivalent to 10716 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10717 DeclSpec DS(Attrs.getPool().getFactory()); 10718 10719 const char *PrevSpec; 10720 unsigned DiagID; 10721 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10722 getPrintingPolicy()); 10723 10724 Declarator D(DS, Declarator::ForContext); 10725 D.SetIdentifier(Ident, IdentLoc); 10726 D.takeAttributes(Attrs, AttrEnd); 10727 10728 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10729 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10730 EmptyAttrs, IdentLoc); 10731 Decl *Var = ActOnDeclarator(S, D); 10732 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10733 FinalizeDeclaration(Var); 10734 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10735 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10736 } 10737 10738 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10739 if (var->isInvalidDecl()) return; 10740 10741 if (getLangOpts().OpenCL) { 10742 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10743 // initialiser 10744 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10745 !var->hasInit()) { 10746 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10747 << 1 /*Init*/; 10748 var->setInvalidDecl(); 10749 return; 10750 } 10751 } 10752 10753 // In Objective-C, don't allow jumps past the implicit initialization of a 10754 // local retaining variable. 10755 if (getLangOpts().ObjC1 && 10756 var->hasLocalStorage()) { 10757 switch (var->getType().getObjCLifetime()) { 10758 case Qualifiers::OCL_None: 10759 case Qualifiers::OCL_ExplicitNone: 10760 case Qualifiers::OCL_Autoreleasing: 10761 break; 10762 10763 case Qualifiers::OCL_Weak: 10764 case Qualifiers::OCL_Strong: 10765 getCurFunction()->setHasBranchProtectedScope(); 10766 break; 10767 } 10768 } 10769 10770 // Warn about externally-visible variables being defined without a 10771 // prior declaration. We only want to do this for global 10772 // declarations, but we also specifically need to avoid doing it for 10773 // class members because the linkage of an anonymous class can 10774 // change if it's later given a typedef name. 10775 if (var->isThisDeclarationADefinition() && 10776 var->getDeclContext()->getRedeclContext()->isFileContext() && 10777 var->isExternallyVisible() && var->hasLinkage() && 10778 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10779 var->getLocation())) { 10780 // Find a previous declaration that's not a definition. 10781 VarDecl *prev = var->getPreviousDecl(); 10782 while (prev && prev->isThisDeclarationADefinition()) 10783 prev = prev->getPreviousDecl(); 10784 10785 if (!prev) 10786 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10787 } 10788 10789 // Cache the result of checking for constant initialization. 10790 Optional<bool> CacheHasConstInit; 10791 const Expr *CacheCulprit; 10792 auto checkConstInit = [&]() mutable { 10793 if (!CacheHasConstInit) 10794 CacheHasConstInit = var->getInit()->isConstantInitializer( 10795 Context, var->getType()->isReferenceType(), &CacheCulprit); 10796 return *CacheHasConstInit; 10797 }; 10798 10799 if (var->getTLSKind() == VarDecl::TLS_Static) { 10800 if (var->getType().isDestructedType()) { 10801 // GNU C++98 edits for __thread, [basic.start.term]p3: 10802 // The type of an object with thread storage duration shall not 10803 // have a non-trivial destructor. 10804 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10805 if (getLangOpts().CPlusPlus11) 10806 Diag(var->getLocation(), diag::note_use_thread_local); 10807 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10808 if (!checkConstInit()) { 10809 // GNU C++98 edits for __thread, [basic.start.init]p4: 10810 // An object of thread storage duration shall not require dynamic 10811 // initialization. 10812 // FIXME: Need strict checking here. 10813 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10814 << CacheCulprit->getSourceRange(); 10815 if (getLangOpts().CPlusPlus11) 10816 Diag(var->getLocation(), diag::note_use_thread_local); 10817 } 10818 } 10819 } 10820 10821 // Apply section attributes and pragmas to global variables. 10822 bool GlobalStorage = var->hasGlobalStorage(); 10823 if (GlobalStorage && var->isThisDeclarationADefinition() && 10824 !inTemplateInstantiation()) { 10825 PragmaStack<StringLiteral *> *Stack = nullptr; 10826 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10827 if (var->getType().isConstQualified()) 10828 Stack = &ConstSegStack; 10829 else if (!var->getInit()) { 10830 Stack = &BSSSegStack; 10831 SectionFlags |= ASTContext::PSF_Write; 10832 } else { 10833 Stack = &DataSegStack; 10834 SectionFlags |= ASTContext::PSF_Write; 10835 } 10836 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10837 var->addAttr(SectionAttr::CreateImplicit( 10838 Context, SectionAttr::Declspec_allocate, 10839 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10840 } 10841 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10842 if (UnifySection(SA->getName(), SectionFlags, var)) 10843 var->dropAttr<SectionAttr>(); 10844 10845 // Apply the init_seg attribute if this has an initializer. If the 10846 // initializer turns out to not be dynamic, we'll end up ignoring this 10847 // attribute. 10848 if (CurInitSeg && var->getInit()) 10849 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10850 CurInitSegLoc)); 10851 } 10852 10853 // All the following checks are C++ only. 10854 if (!getLangOpts().CPlusPlus) { 10855 // If this variable must be emitted, add it as an initializer for the 10856 // current module. 10857 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10858 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10859 return; 10860 } 10861 10862 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10863 CheckCompleteDecompositionDeclaration(DD); 10864 10865 QualType type = var->getType(); 10866 if (type->isDependentType()) return; 10867 10868 // __block variables might require us to capture a copy-initializer. 10869 if (var->hasAttr<BlocksAttr>()) { 10870 // It's currently invalid to ever have a __block variable with an 10871 // array type; should we diagnose that here? 10872 10873 // Regardless, we don't want to ignore array nesting when 10874 // constructing this copy. 10875 if (type->isStructureOrClassType()) { 10876 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10877 SourceLocation poi = var->getLocation(); 10878 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10879 ExprResult result 10880 = PerformMoveOrCopyInitialization( 10881 InitializedEntity::InitializeBlock(poi, type, false), 10882 var, var->getType(), varRef, /*AllowNRVO=*/true); 10883 if (!result.isInvalid()) { 10884 result = MaybeCreateExprWithCleanups(result); 10885 Expr *init = result.getAs<Expr>(); 10886 Context.setBlockVarCopyInits(var, init); 10887 } 10888 } 10889 } 10890 10891 Expr *Init = var->getInit(); 10892 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10893 QualType baseType = Context.getBaseElementType(type); 10894 10895 if (!var->getDeclContext()->isDependentContext() && 10896 Init && !Init->isValueDependent()) { 10897 10898 if (var->isConstexpr()) { 10899 SmallVector<PartialDiagnosticAt, 8> Notes; 10900 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10901 SourceLocation DiagLoc = var->getLocation(); 10902 // If the note doesn't add any useful information other than a source 10903 // location, fold it into the primary diagnostic. 10904 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10905 diag::note_invalid_subexpr_in_const_expr) { 10906 DiagLoc = Notes[0].first; 10907 Notes.clear(); 10908 } 10909 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10910 << var << Init->getSourceRange(); 10911 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10912 Diag(Notes[I].first, Notes[I].second); 10913 } 10914 } else if (var->isUsableInConstantExpressions(Context)) { 10915 // Check whether the initializer of a const variable of integral or 10916 // enumeration type is an ICE now, since we can't tell whether it was 10917 // initialized by a constant expression if we check later. 10918 var->checkInitIsICE(); 10919 } 10920 10921 // Don't emit further diagnostics about constexpr globals since they 10922 // were just diagnosed. 10923 if (!var->isConstexpr() && GlobalStorage && 10924 var->hasAttr<RequireConstantInitAttr>()) { 10925 // FIXME: Need strict checking in C++03 here. 10926 bool DiagErr = getLangOpts().CPlusPlus11 10927 ? !var->checkInitIsICE() : !checkConstInit(); 10928 if (DiagErr) { 10929 auto attr = var->getAttr<RequireConstantInitAttr>(); 10930 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10931 << Init->getSourceRange(); 10932 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10933 << attr->getRange(); 10934 } 10935 } 10936 else if (!var->isConstexpr() && IsGlobal && 10937 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10938 var->getLocation())) { 10939 // Warn about globals which don't have a constant initializer. Don't 10940 // warn about globals with a non-trivial destructor because we already 10941 // warned about them. 10942 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10943 if (!(RD && !RD->hasTrivialDestructor())) { 10944 if (!checkConstInit()) 10945 Diag(var->getLocation(), diag::warn_global_constructor) 10946 << Init->getSourceRange(); 10947 } 10948 } 10949 } 10950 10951 // Require the destructor. 10952 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10953 FinalizeVarWithDestructor(var, recordType); 10954 10955 // If this variable must be emitted, add it as an initializer for the current 10956 // module. 10957 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10958 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10959 } 10960 10961 /// \brief Determines if a variable's alignment is dependent. 10962 static bool hasDependentAlignment(VarDecl *VD) { 10963 if (VD->getType()->isDependentType()) 10964 return true; 10965 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10966 if (I->isAlignmentDependent()) 10967 return true; 10968 return false; 10969 } 10970 10971 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10972 /// any semantic actions necessary after any initializer has been attached. 10973 void 10974 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10975 // Note that we are no longer parsing the initializer for this declaration. 10976 ParsingInitForAutoVars.erase(ThisDecl); 10977 10978 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10979 if (!VD) 10980 return; 10981 10982 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10983 for (auto *BD : DD->bindings()) { 10984 FinalizeDeclaration(BD); 10985 } 10986 } 10987 10988 checkAttributesAfterMerging(*this, *VD); 10989 10990 // Perform TLS alignment check here after attributes attached to the variable 10991 // which may affect the alignment have been processed. Only perform the check 10992 // if the target has a maximum TLS alignment (zero means no constraints). 10993 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10994 // Protect the check so that it's not performed on dependent types and 10995 // dependent alignments (we can't determine the alignment in that case). 10996 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 10997 !VD->isInvalidDecl()) { 10998 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10999 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11000 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11001 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11002 << (unsigned)MaxAlignChars.getQuantity(); 11003 } 11004 } 11005 } 11006 11007 if (VD->isStaticLocal()) { 11008 if (FunctionDecl *FD = 11009 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11010 // Static locals inherit dll attributes from their function. 11011 if (Attr *A = getDLLAttr(FD)) { 11012 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11013 NewAttr->setInherited(true); 11014 VD->addAttr(NewAttr); 11015 } 11016 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11017 // function, only __shared__ variables may be declared with 11018 // static storage class. 11019 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11020 CUDADiagIfDeviceCode(VD->getLocation(), 11021 diag::err_device_static_local_var) 11022 << CurrentCUDATarget()) 11023 VD->setInvalidDecl(); 11024 } 11025 } 11026 11027 // Perform check for initializers of device-side global variables. 11028 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11029 // 7.5). We must also apply the same checks to all __shared__ 11030 // variables whether they are local or not. CUDA also allows 11031 // constant initializers for __constant__ and __device__ variables. 11032 if (getLangOpts().CUDA) { 11033 const Expr *Init = VD->getInit(); 11034 if (Init && VD->hasGlobalStorage()) { 11035 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11036 VD->hasAttr<CUDASharedAttr>()) { 11037 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11038 bool AllowedInit = false; 11039 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11040 AllowedInit = 11041 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11042 // We'll allow constant initializers even if it's a non-empty 11043 // constructor according to CUDA rules. This deviates from NVCC, 11044 // but allows us to handle things like constexpr constructors. 11045 if (!AllowedInit && 11046 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11047 AllowedInit = VD->getInit()->isConstantInitializer( 11048 Context, VD->getType()->isReferenceType()); 11049 11050 // Also make sure that destructor, if there is one, is empty. 11051 if (AllowedInit) 11052 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11053 AllowedInit = 11054 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11055 11056 if (!AllowedInit) { 11057 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11058 ? diag::err_shared_var_init 11059 : diag::err_dynamic_var_init) 11060 << Init->getSourceRange(); 11061 VD->setInvalidDecl(); 11062 } 11063 } else { 11064 // This is a host-side global variable. Check that the initializer is 11065 // callable from the host side. 11066 const FunctionDecl *InitFn = nullptr; 11067 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11068 InitFn = CE->getConstructor(); 11069 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11070 InitFn = CE->getDirectCallee(); 11071 } 11072 if (InitFn) { 11073 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11074 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11075 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11076 << InitFnTarget << InitFn; 11077 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11078 VD->setInvalidDecl(); 11079 } 11080 } 11081 } 11082 } 11083 } 11084 11085 // Grab the dllimport or dllexport attribute off of the VarDecl. 11086 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11087 11088 // Imported static data members cannot be defined out-of-line. 11089 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11090 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11091 VD->isThisDeclarationADefinition()) { 11092 // We allow definitions of dllimport class template static data members 11093 // with a warning. 11094 CXXRecordDecl *Context = 11095 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11096 bool IsClassTemplateMember = 11097 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11098 Context->getDescribedClassTemplate(); 11099 11100 Diag(VD->getLocation(), 11101 IsClassTemplateMember 11102 ? diag::warn_attribute_dllimport_static_field_definition 11103 : diag::err_attribute_dllimport_static_field_definition); 11104 Diag(IA->getLocation(), diag::note_attribute); 11105 if (!IsClassTemplateMember) 11106 VD->setInvalidDecl(); 11107 } 11108 } 11109 11110 // dllimport/dllexport variables cannot be thread local, their TLS index 11111 // isn't exported with the variable. 11112 if (DLLAttr && VD->getTLSKind()) { 11113 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11114 if (F && getDLLAttr(F)) { 11115 assert(VD->isStaticLocal()); 11116 // But if this is a static local in a dlimport/dllexport function, the 11117 // function will never be inlined, which means the var would never be 11118 // imported, so having it marked import/export is safe. 11119 } else { 11120 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11121 << DLLAttr; 11122 VD->setInvalidDecl(); 11123 } 11124 } 11125 11126 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11127 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11128 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11129 VD->dropAttr<UsedAttr>(); 11130 } 11131 } 11132 11133 const DeclContext *DC = VD->getDeclContext(); 11134 // If there's a #pragma GCC visibility in scope, and this isn't a class 11135 // member, set the visibility of this variable. 11136 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11137 AddPushedVisibilityAttribute(VD); 11138 11139 // FIXME: Warn on unused templates. 11140 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 11141 !isa<VarTemplatePartialSpecializationDecl>(VD)) 11142 MarkUnusedFileScopedDecl(VD); 11143 11144 // Now we have parsed the initializer and can update the table of magic 11145 // tag values. 11146 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11147 !VD->getType()->isIntegralOrEnumerationType()) 11148 return; 11149 11150 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11151 const Expr *MagicValueExpr = VD->getInit(); 11152 if (!MagicValueExpr) { 11153 continue; 11154 } 11155 llvm::APSInt MagicValueInt; 11156 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11157 Diag(I->getRange().getBegin(), 11158 diag::err_type_tag_for_datatype_not_ice) 11159 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11160 continue; 11161 } 11162 if (MagicValueInt.getActiveBits() > 64) { 11163 Diag(I->getRange().getBegin(), 11164 diag::err_type_tag_for_datatype_too_large) 11165 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11166 continue; 11167 } 11168 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11169 RegisterTypeTagForDatatype(I->getArgumentKind(), 11170 MagicValue, 11171 I->getMatchingCType(), 11172 I->getLayoutCompatible(), 11173 I->getMustBeNull()); 11174 } 11175 } 11176 11177 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11178 auto *VD = dyn_cast<VarDecl>(DD); 11179 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11180 } 11181 11182 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11183 ArrayRef<Decl *> Group) { 11184 SmallVector<Decl*, 8> Decls; 11185 11186 if (DS.isTypeSpecOwned()) 11187 Decls.push_back(DS.getRepAsDecl()); 11188 11189 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11190 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11191 bool DiagnosedMultipleDecomps = false; 11192 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11193 bool DiagnosedNonDeducedAuto = false; 11194 11195 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11196 if (Decl *D = Group[i]) { 11197 // For declarators, there are some additional syntactic-ish checks we need 11198 // to perform. 11199 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11200 if (!FirstDeclaratorInGroup) 11201 FirstDeclaratorInGroup = DD; 11202 if (!FirstDecompDeclaratorInGroup) 11203 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11204 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11205 !hasDeducedAuto(DD)) 11206 FirstNonDeducedAutoInGroup = DD; 11207 11208 if (FirstDeclaratorInGroup != DD) { 11209 // A decomposition declaration cannot be combined with any other 11210 // declaration in the same group. 11211 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11212 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11213 diag::err_decomp_decl_not_alone) 11214 << FirstDeclaratorInGroup->getSourceRange() 11215 << DD->getSourceRange(); 11216 DiagnosedMultipleDecomps = true; 11217 } 11218 11219 // A declarator that uses 'auto' in any way other than to declare a 11220 // variable with a deduced type cannot be combined with any other 11221 // declarator in the same group. 11222 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11223 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11224 diag::err_auto_non_deduced_not_alone) 11225 << FirstNonDeducedAutoInGroup->getType() 11226 ->hasAutoForTrailingReturnType() 11227 << FirstDeclaratorInGroup->getSourceRange() 11228 << DD->getSourceRange(); 11229 DiagnosedNonDeducedAuto = true; 11230 } 11231 } 11232 } 11233 11234 Decls.push_back(D); 11235 } 11236 } 11237 11238 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11239 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11240 handleTagNumbering(Tag, S); 11241 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11242 getLangOpts().CPlusPlus) 11243 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11244 } 11245 } 11246 11247 return BuildDeclaratorGroup(Decls); 11248 } 11249 11250 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11251 /// group, performing any necessary semantic checking. 11252 Sema::DeclGroupPtrTy 11253 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11254 // C++14 [dcl.spec.auto]p7: (DR1347) 11255 // If the type that replaces the placeholder type is not the same in each 11256 // deduction, the program is ill-formed. 11257 if (Group.size() > 1) { 11258 QualType Deduced; 11259 VarDecl *DeducedDecl = nullptr; 11260 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11261 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11262 if (!D || D->isInvalidDecl()) 11263 break; 11264 DeducedType *DT = D->getType()->getContainedDeducedType(); 11265 if (!DT || DT->getDeducedType().isNull()) 11266 continue; 11267 if (Deduced.isNull()) { 11268 Deduced = DT->getDeducedType(); 11269 DeducedDecl = D; 11270 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11271 auto *AT = dyn_cast<AutoType>(DT); 11272 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11273 diag::err_auto_different_deductions) 11274 << (AT ? (unsigned)AT->getKeyword() : 3) 11275 << Deduced << DeducedDecl->getDeclName() 11276 << DT->getDeducedType() << D->getDeclName() 11277 << DeducedDecl->getInit()->getSourceRange() 11278 << D->getInit()->getSourceRange(); 11279 D->setInvalidDecl(); 11280 break; 11281 } 11282 } 11283 } 11284 11285 ActOnDocumentableDecls(Group); 11286 11287 return DeclGroupPtrTy::make( 11288 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11289 } 11290 11291 void Sema::ActOnDocumentableDecl(Decl *D) { 11292 ActOnDocumentableDecls(D); 11293 } 11294 11295 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11296 // Don't parse the comment if Doxygen diagnostics are ignored. 11297 if (Group.empty() || !Group[0]) 11298 return; 11299 11300 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11301 Group[0]->getLocation()) && 11302 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11303 Group[0]->getLocation())) 11304 return; 11305 11306 if (Group.size() >= 2) { 11307 // This is a decl group. Normally it will contain only declarations 11308 // produced from declarator list. But in case we have any definitions or 11309 // additional declaration references: 11310 // 'typedef struct S {} S;' 11311 // 'typedef struct S *S;' 11312 // 'struct S *pS;' 11313 // FinalizeDeclaratorGroup adds these as separate declarations. 11314 Decl *MaybeTagDecl = Group[0]; 11315 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11316 Group = Group.slice(1); 11317 } 11318 } 11319 11320 // See if there are any new comments that are not attached to a decl. 11321 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11322 if (!Comments.empty() && 11323 !Comments.back()->isAttached()) { 11324 // There is at least one comment that not attached to a decl. 11325 // Maybe it should be attached to one of these decls? 11326 // 11327 // Note that this way we pick up not only comments that precede the 11328 // declaration, but also comments that *follow* the declaration -- thanks to 11329 // the lookahead in the lexer: we've consumed the semicolon and looked 11330 // ahead through comments. 11331 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11332 Context.getCommentForDecl(Group[i], &PP); 11333 } 11334 } 11335 11336 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11337 /// to introduce parameters into function prototype scope. 11338 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11339 const DeclSpec &DS = D.getDeclSpec(); 11340 11341 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11342 11343 // C++03 [dcl.stc]p2 also permits 'auto'. 11344 StorageClass SC = SC_None; 11345 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11346 SC = SC_Register; 11347 } else if (getLangOpts().CPlusPlus && 11348 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11349 SC = SC_Auto; 11350 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11351 Diag(DS.getStorageClassSpecLoc(), 11352 diag::err_invalid_storage_class_in_func_decl); 11353 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11354 } 11355 11356 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11357 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11358 << DeclSpec::getSpecifierName(TSCS); 11359 if (DS.isInlineSpecified()) 11360 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11361 << getLangOpts().CPlusPlus1z; 11362 if (DS.isConstexprSpecified()) 11363 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11364 << 0; 11365 if (DS.isConceptSpecified()) 11366 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11367 11368 DiagnoseFunctionSpecifiers(DS); 11369 11370 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11371 QualType parmDeclType = TInfo->getType(); 11372 11373 if (getLangOpts().CPlusPlus) { 11374 // Check that there are no default arguments inside the type of this 11375 // parameter. 11376 CheckExtraCXXDefaultArguments(D); 11377 11378 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11379 if (D.getCXXScopeSpec().isSet()) { 11380 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11381 << D.getCXXScopeSpec().getRange(); 11382 D.getCXXScopeSpec().clear(); 11383 } 11384 } 11385 11386 // Ensure we have a valid name 11387 IdentifierInfo *II = nullptr; 11388 if (D.hasName()) { 11389 II = D.getIdentifier(); 11390 if (!II) { 11391 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11392 << GetNameForDeclarator(D).getName(); 11393 D.setInvalidType(true); 11394 } 11395 } 11396 11397 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11398 if (II) { 11399 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11400 ForRedeclaration); 11401 LookupName(R, S); 11402 if (R.isSingleResult()) { 11403 NamedDecl *PrevDecl = R.getFoundDecl(); 11404 if (PrevDecl->isTemplateParameter()) { 11405 // Maybe we will complain about the shadowed template parameter. 11406 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11407 // Just pretend that we didn't see the previous declaration. 11408 PrevDecl = nullptr; 11409 } else if (S->isDeclScope(PrevDecl)) { 11410 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11411 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11412 11413 // Recover by removing the name 11414 II = nullptr; 11415 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11416 D.setInvalidType(true); 11417 } 11418 } 11419 } 11420 11421 // Temporarily put parameter variables in the translation unit, not 11422 // the enclosing context. This prevents them from accidentally 11423 // looking like class members in C++. 11424 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11425 D.getLocStart(), 11426 D.getIdentifierLoc(), II, 11427 parmDeclType, TInfo, 11428 SC); 11429 11430 if (D.isInvalidType()) 11431 New->setInvalidDecl(); 11432 11433 assert(S->isFunctionPrototypeScope()); 11434 assert(S->getFunctionPrototypeDepth() >= 1); 11435 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11436 S->getNextFunctionPrototypeIndex()); 11437 11438 // Add the parameter declaration into this scope. 11439 S->AddDecl(New); 11440 if (II) 11441 IdResolver.AddDecl(New); 11442 11443 ProcessDeclAttributes(S, New, D); 11444 11445 if (D.getDeclSpec().isModulePrivateSpecified()) 11446 Diag(New->getLocation(), diag::err_module_private_local) 11447 << 1 << New->getDeclName() 11448 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11449 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11450 11451 if (New->hasAttr<BlocksAttr>()) { 11452 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11453 } 11454 return New; 11455 } 11456 11457 /// \brief Synthesizes a variable for a parameter arising from a 11458 /// typedef. 11459 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11460 SourceLocation Loc, 11461 QualType T) { 11462 /* FIXME: setting StartLoc == Loc. 11463 Would it be worth to modify callers so as to provide proper source 11464 location for the unnamed parameters, embedding the parameter's type? */ 11465 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11466 T, Context.getTrivialTypeSourceInfo(T, Loc), 11467 SC_None, nullptr); 11468 Param->setImplicit(); 11469 return Param; 11470 } 11471 11472 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11473 // Don't diagnose unused-parameter errors in template instantiations; we 11474 // will already have done so in the template itself. 11475 if (inTemplateInstantiation()) 11476 return; 11477 11478 for (const ParmVarDecl *Parameter : Parameters) { 11479 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11480 !Parameter->hasAttr<UnusedAttr>()) { 11481 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11482 << Parameter->getDeclName(); 11483 } 11484 } 11485 } 11486 11487 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11488 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11489 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11490 return; 11491 11492 // Warn if the return value is pass-by-value and larger than the specified 11493 // threshold. 11494 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11495 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11496 if (Size > LangOpts.NumLargeByValueCopy) 11497 Diag(D->getLocation(), diag::warn_return_value_size) 11498 << D->getDeclName() << Size; 11499 } 11500 11501 // Warn if any parameter is pass-by-value and larger than the specified 11502 // threshold. 11503 for (const ParmVarDecl *Parameter : Parameters) { 11504 QualType T = Parameter->getType(); 11505 if (T->isDependentType() || !T.isPODType(Context)) 11506 continue; 11507 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11508 if (Size > LangOpts.NumLargeByValueCopy) 11509 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11510 << Parameter->getDeclName() << Size; 11511 } 11512 } 11513 11514 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11515 SourceLocation NameLoc, IdentifierInfo *Name, 11516 QualType T, TypeSourceInfo *TSInfo, 11517 StorageClass SC) { 11518 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11519 if (getLangOpts().ObjCAutoRefCount && 11520 T.getObjCLifetime() == Qualifiers::OCL_None && 11521 T->isObjCLifetimeType()) { 11522 11523 Qualifiers::ObjCLifetime lifetime; 11524 11525 // Special cases for arrays: 11526 // - if it's const, use __unsafe_unretained 11527 // - otherwise, it's an error 11528 if (T->isArrayType()) { 11529 if (!T.isConstQualified()) { 11530 DelayedDiagnostics.add( 11531 sema::DelayedDiagnostic::makeForbiddenType( 11532 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11533 } 11534 lifetime = Qualifiers::OCL_ExplicitNone; 11535 } else { 11536 lifetime = T->getObjCARCImplicitLifetime(); 11537 } 11538 T = Context.getLifetimeQualifiedType(T, lifetime); 11539 } 11540 11541 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11542 Context.getAdjustedParameterType(T), 11543 TSInfo, SC, nullptr); 11544 11545 // Parameters can not be abstract class types. 11546 // For record types, this is done by the AbstractClassUsageDiagnoser once 11547 // the class has been completely parsed. 11548 if (!CurContext->isRecord() && 11549 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11550 AbstractParamType)) 11551 New->setInvalidDecl(); 11552 11553 // Parameter declarators cannot be interface types. All ObjC objects are 11554 // passed by reference. 11555 if (T->isObjCObjectType()) { 11556 SourceLocation TypeEndLoc = 11557 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11558 Diag(NameLoc, 11559 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11560 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11561 T = Context.getObjCObjectPointerType(T); 11562 New->setType(T); 11563 } 11564 11565 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11566 // duration shall not be qualified by an address-space qualifier." 11567 // Since all parameters have automatic store duration, they can not have 11568 // an address space. 11569 if (T.getAddressSpace() != 0) { 11570 // OpenCL allows function arguments declared to be an array of a type 11571 // to be qualified with an address space. 11572 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11573 Diag(NameLoc, diag::err_arg_with_address_space); 11574 New->setInvalidDecl(); 11575 } 11576 } 11577 11578 return New; 11579 } 11580 11581 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11582 SourceLocation LocAfterDecls) { 11583 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11584 11585 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11586 // for a K&R function. 11587 if (!FTI.hasPrototype) { 11588 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11589 --i; 11590 if (FTI.Params[i].Param == nullptr) { 11591 SmallString<256> Code; 11592 llvm::raw_svector_ostream(Code) 11593 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11594 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11595 << FTI.Params[i].Ident 11596 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11597 11598 // Implicitly declare the argument as type 'int' for lack of a better 11599 // type. 11600 AttributeFactory attrs; 11601 DeclSpec DS(attrs); 11602 const char* PrevSpec; // unused 11603 unsigned DiagID; // unused 11604 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11605 DiagID, Context.getPrintingPolicy()); 11606 // Use the identifier location for the type source range. 11607 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11608 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11609 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11610 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11611 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11612 } 11613 } 11614 } 11615 } 11616 11617 Decl * 11618 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11619 MultiTemplateParamsArg TemplateParameterLists, 11620 SkipBodyInfo *SkipBody) { 11621 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11622 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11623 Scope *ParentScope = FnBodyScope->getParent(); 11624 11625 D.setFunctionDefinitionKind(FDK_Definition); 11626 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11627 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11628 } 11629 11630 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11631 Consumer.HandleInlineFunctionDefinition(D); 11632 } 11633 11634 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11635 const FunctionDecl*& PossibleZeroParamPrototype) { 11636 // Don't warn about invalid declarations. 11637 if (FD->isInvalidDecl()) 11638 return false; 11639 11640 // Or declarations that aren't global. 11641 if (!FD->isGlobal()) 11642 return false; 11643 11644 // Don't warn about C++ member functions. 11645 if (isa<CXXMethodDecl>(FD)) 11646 return false; 11647 11648 // Don't warn about 'main'. 11649 if (FD->isMain()) 11650 return false; 11651 11652 // Don't warn about inline functions. 11653 if (FD->isInlined()) 11654 return false; 11655 11656 // Don't warn about function templates. 11657 if (FD->getDescribedFunctionTemplate()) 11658 return false; 11659 11660 // Don't warn about function template specializations. 11661 if (FD->isFunctionTemplateSpecialization()) 11662 return false; 11663 11664 // Don't warn for OpenCL kernels. 11665 if (FD->hasAttr<OpenCLKernelAttr>()) 11666 return false; 11667 11668 // Don't warn on explicitly deleted functions. 11669 if (FD->isDeleted()) 11670 return false; 11671 11672 bool MissingPrototype = true; 11673 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11674 Prev; Prev = Prev->getPreviousDecl()) { 11675 // Ignore any declarations that occur in function or method 11676 // scope, because they aren't visible from the header. 11677 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11678 continue; 11679 11680 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11681 if (FD->getNumParams() == 0) 11682 PossibleZeroParamPrototype = Prev; 11683 break; 11684 } 11685 11686 return MissingPrototype; 11687 } 11688 11689 void 11690 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11691 const FunctionDecl *EffectiveDefinition, 11692 SkipBodyInfo *SkipBody) { 11693 const FunctionDecl *Definition = EffectiveDefinition; 11694 if (!Definition) 11695 if (!FD->isDefined(Definition)) 11696 return; 11697 11698 if (canRedefineFunction(Definition, getLangOpts())) 11699 return; 11700 11701 // If we don't have a visible definition of the function, and it's inline or 11702 // a template, skip the new definition. 11703 if (SkipBody && !hasVisibleDefinition(Definition) && 11704 (Definition->getFormalLinkage() == InternalLinkage || 11705 Definition->isInlined() || 11706 Definition->getDescribedFunctionTemplate() || 11707 Definition->getNumTemplateParameterLists())) { 11708 SkipBody->ShouldSkip = true; 11709 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11710 makeMergedDefinitionVisible(TD, FD->getLocation()); 11711 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11712 FD->getLocation()); 11713 return; 11714 } 11715 11716 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11717 Definition->getStorageClass() == SC_Extern) 11718 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11719 << FD->getDeclName() << getLangOpts().CPlusPlus; 11720 else 11721 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11722 11723 Diag(Definition->getLocation(), diag::note_previous_definition); 11724 FD->setInvalidDecl(); 11725 } 11726 11727 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11728 Sema &S) { 11729 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11730 11731 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11732 LSI->CallOperator = CallOperator; 11733 LSI->Lambda = LambdaClass; 11734 LSI->ReturnType = CallOperator->getReturnType(); 11735 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11736 11737 if (LCD == LCD_None) 11738 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11739 else if (LCD == LCD_ByCopy) 11740 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11741 else if (LCD == LCD_ByRef) 11742 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11743 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11744 11745 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11746 LSI->Mutable = !CallOperator->isConst(); 11747 11748 // Add the captures to the LSI so they can be noted as already 11749 // captured within tryCaptureVar. 11750 auto I = LambdaClass->field_begin(); 11751 for (const auto &C : LambdaClass->captures()) { 11752 if (C.capturesVariable()) { 11753 VarDecl *VD = C.getCapturedVar(); 11754 if (VD->isInitCapture()) 11755 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11756 QualType CaptureType = VD->getType(); 11757 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11758 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11759 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11760 /*EllipsisLoc*/C.isPackExpansion() 11761 ? C.getEllipsisLoc() : SourceLocation(), 11762 CaptureType, /*Expr*/ nullptr); 11763 11764 } else if (C.capturesThis()) { 11765 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11766 /*Expr*/ nullptr, 11767 C.getCaptureKind() == LCK_StarThis); 11768 } else { 11769 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11770 } 11771 ++I; 11772 } 11773 } 11774 11775 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11776 SkipBodyInfo *SkipBody) { 11777 if (!D) 11778 return D; 11779 FunctionDecl *FD = nullptr; 11780 11781 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11782 FD = FunTmpl->getTemplatedDecl(); 11783 else 11784 FD = cast<FunctionDecl>(D); 11785 11786 // Check for defining attributes before the check for redefinition. 11787 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 11788 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 11789 FD->dropAttr<AliasAttr>(); 11790 FD->setInvalidDecl(); 11791 } 11792 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 11793 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 11794 FD->dropAttr<IFuncAttr>(); 11795 FD->setInvalidDecl(); 11796 } 11797 11798 // See if this is a redefinition. 11799 if (!FD->isLateTemplateParsed()) { 11800 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11801 11802 // If we're skipping the body, we're done. Don't enter the scope. 11803 if (SkipBody && SkipBody->ShouldSkip) 11804 return D; 11805 } 11806 11807 // Mark this function as "will have a body eventually". This lets users to 11808 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11809 // this function. 11810 FD->setWillHaveBody(); 11811 11812 // If we are instantiating a generic lambda call operator, push 11813 // a LambdaScopeInfo onto the function stack. But use the information 11814 // that's already been calculated (ActOnLambdaExpr) to prime the current 11815 // LambdaScopeInfo. 11816 // When the template operator is being specialized, the LambdaScopeInfo, 11817 // has to be properly restored so that tryCaptureVariable doesn't try 11818 // and capture any new variables. In addition when calculating potential 11819 // captures during transformation of nested lambdas, it is necessary to 11820 // have the LSI properly restored. 11821 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11822 assert(inTemplateInstantiation() && 11823 "There should be an active template instantiation on the stack " 11824 "when instantiating a generic lambda!"); 11825 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11826 } else { 11827 // Enter a new function scope 11828 PushFunctionScope(); 11829 } 11830 11831 // Builtin functions cannot be defined. 11832 if (unsigned BuiltinID = FD->getBuiltinID()) { 11833 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11834 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11835 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11836 FD->setInvalidDecl(); 11837 } 11838 } 11839 11840 // The return type of a function definition must be complete 11841 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11842 QualType ResultType = FD->getReturnType(); 11843 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11844 !FD->isInvalidDecl() && 11845 RequireCompleteType(FD->getLocation(), ResultType, 11846 diag::err_func_def_incomplete_result)) 11847 FD->setInvalidDecl(); 11848 11849 if (FnBodyScope) 11850 PushDeclContext(FnBodyScope, FD); 11851 11852 // Check the validity of our function parameters 11853 CheckParmsForFunctionDef(FD->parameters(), 11854 /*CheckParameterNames=*/true); 11855 11856 // Add non-parameter declarations already in the function to the current 11857 // scope. 11858 if (FnBodyScope) { 11859 for (Decl *NPD : FD->decls()) { 11860 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 11861 if (!NonParmDecl) 11862 continue; 11863 assert(!isa<ParmVarDecl>(NonParmDecl) && 11864 "parameters should not be in newly created FD yet"); 11865 11866 // If the decl has a name, make it accessible in the current scope. 11867 if (NonParmDecl->getDeclName()) 11868 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 11869 11870 // Similarly, dive into enums and fish their constants out, making them 11871 // accessible in this scope. 11872 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 11873 for (auto *EI : ED->enumerators()) 11874 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11875 } 11876 } 11877 } 11878 11879 // Introduce our parameters into the function scope 11880 for (auto Param : FD->parameters()) { 11881 Param->setOwningFunction(FD); 11882 11883 // If this has an identifier, add it to the scope stack. 11884 if (Param->getIdentifier() && FnBodyScope) { 11885 CheckShadow(FnBodyScope, Param); 11886 11887 PushOnScopeChains(Param, FnBodyScope); 11888 } 11889 } 11890 11891 // Ensure that the function's exception specification is instantiated. 11892 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11893 ResolveExceptionSpec(D->getLocation(), FPT); 11894 11895 // dllimport cannot be applied to non-inline function definitions. 11896 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11897 !FD->isTemplateInstantiation()) { 11898 assert(!FD->hasAttr<DLLExportAttr>()); 11899 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11900 FD->setInvalidDecl(); 11901 return D; 11902 } 11903 // We want to attach documentation to original Decl (which might be 11904 // a function template). 11905 ActOnDocumentableDecl(D); 11906 if (getCurLexicalContext()->isObjCContainer() && 11907 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11908 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11909 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11910 11911 return D; 11912 } 11913 11914 /// \brief Given the set of return statements within a function body, 11915 /// compute the variables that are subject to the named return value 11916 /// optimization. 11917 /// 11918 /// Each of the variables that is subject to the named return value 11919 /// optimization will be marked as NRVO variables in the AST, and any 11920 /// return statement that has a marked NRVO variable as its NRVO candidate can 11921 /// use the named return value optimization. 11922 /// 11923 /// This function applies a very simplistic algorithm for NRVO: if every return 11924 /// statement in the scope of a variable has the same NRVO candidate, that 11925 /// candidate is an NRVO variable. 11926 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11927 ReturnStmt **Returns = Scope->Returns.data(); 11928 11929 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11930 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11931 if (!NRVOCandidate->isNRVOVariable()) 11932 Returns[I]->setNRVOCandidate(nullptr); 11933 } 11934 } 11935 } 11936 11937 bool Sema::canDelayFunctionBody(const Declarator &D) { 11938 // We can't delay parsing the body of a constexpr function template (yet). 11939 if (D.getDeclSpec().isConstexprSpecified()) 11940 return false; 11941 11942 // We can't delay parsing the body of a function template with a deduced 11943 // return type (yet). 11944 if (D.getDeclSpec().hasAutoTypeSpec()) { 11945 // If the placeholder introduces a non-deduced trailing return type, 11946 // we can still delay parsing it. 11947 if (D.getNumTypeObjects()) { 11948 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11949 if (Outer.Kind == DeclaratorChunk::Function && 11950 Outer.Fun.hasTrailingReturnType()) { 11951 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11952 return Ty.isNull() || !Ty->isUndeducedType(); 11953 } 11954 } 11955 return false; 11956 } 11957 11958 return true; 11959 } 11960 11961 bool Sema::canSkipFunctionBody(Decl *D) { 11962 // We cannot skip the body of a function (or function template) which is 11963 // constexpr, since we may need to evaluate its body in order to parse the 11964 // rest of the file. 11965 // We cannot skip the body of a function with an undeduced return type, 11966 // because any callers of that function need to know the type. 11967 if (const FunctionDecl *FD = D->getAsFunction()) 11968 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11969 return false; 11970 return Consumer.shouldSkipFunctionBody(D); 11971 } 11972 11973 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11974 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11975 FD->setHasSkippedBody(); 11976 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11977 MD->setHasSkippedBody(); 11978 return Decl; 11979 } 11980 11981 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11982 return ActOnFinishFunctionBody(D, BodyArg, false); 11983 } 11984 11985 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11986 bool IsInstantiation) { 11987 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11988 11989 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11990 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11991 11992 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11993 CheckCompletedCoroutineBody(FD, Body); 11994 11995 if (FD) { 11996 FD->setBody(Body); 11997 11998 if (getLangOpts().CPlusPlus14) { 11999 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12000 FD->getReturnType()->isUndeducedType()) { 12001 // If the function has a deduced result type but contains no 'return' 12002 // statements, the result type as written must be exactly 'auto', and 12003 // the deduced result type is 'void'. 12004 if (!FD->getReturnType()->getAs<AutoType>()) { 12005 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12006 << FD->getReturnType(); 12007 FD->setInvalidDecl(); 12008 } else { 12009 // Substitute 'void' for the 'auto' in the type. 12010 TypeLoc ResultType = getReturnTypeLoc(FD); 12011 Context.adjustDeducedFunctionResultType( 12012 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12013 } 12014 } 12015 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12016 // In C++11, we don't use 'auto' deduction rules for lambda call 12017 // operators because we don't support return type deduction. 12018 auto *LSI = getCurLambda(); 12019 if (LSI->HasImplicitReturnType) { 12020 deduceClosureReturnType(*LSI); 12021 12022 // C++11 [expr.prim.lambda]p4: 12023 // [...] if there are no return statements in the compound-statement 12024 // [the deduced type is] the type void 12025 QualType RetType = 12026 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12027 12028 // Update the return type to the deduced type. 12029 const FunctionProtoType *Proto = 12030 FD->getType()->getAs<FunctionProtoType>(); 12031 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12032 Proto->getExtProtoInfo())); 12033 } 12034 } 12035 12036 // The only way to be included in UndefinedButUsed is if there is an 12037 // ODR use before the definition. Avoid the expensive map lookup if this 12038 // is the first declaration. 12039 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12040 if (!FD->isExternallyVisible()) 12041 UndefinedButUsed.erase(FD); 12042 else if (FD->isInlined() && 12043 !LangOpts.GNUInline && 12044 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12045 UndefinedButUsed.erase(FD); 12046 } 12047 12048 // If the function implicitly returns zero (like 'main') or is naked, 12049 // don't complain about missing return statements. 12050 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12051 WP.disableCheckFallThrough(); 12052 12053 // MSVC permits the use of pure specifier (=0) on function definition, 12054 // defined at class scope, warn about this non-standard construct. 12055 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12056 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12057 12058 if (!FD->isInvalidDecl()) { 12059 // Don't diagnose unused parameters of defaulted or deleted functions. 12060 if (!FD->isDeleted() && !FD->isDefaulted()) 12061 DiagnoseUnusedParameters(FD->parameters()); 12062 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12063 FD->getReturnType(), FD); 12064 12065 // If this is a structor, we need a vtable. 12066 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12067 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12068 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12069 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12070 12071 // Try to apply the named return value optimization. We have to check 12072 // if we can do this here because lambdas keep return statements around 12073 // to deduce an implicit return type. 12074 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12075 !FD->isDependentContext()) 12076 computeNRVO(Body, getCurFunction()); 12077 } 12078 12079 // GNU warning -Wmissing-prototypes: 12080 // Warn if a global function is defined without a previous 12081 // prototype declaration. This warning is issued even if the 12082 // definition itself provides a prototype. The aim is to detect 12083 // global functions that fail to be declared in header files. 12084 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12085 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12086 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12087 12088 if (PossibleZeroParamPrototype) { 12089 // We found a declaration that is not a prototype, 12090 // but that could be a zero-parameter prototype 12091 if (TypeSourceInfo *TI = 12092 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12093 TypeLoc TL = TI->getTypeLoc(); 12094 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12095 Diag(PossibleZeroParamPrototype->getLocation(), 12096 diag::note_declaration_not_a_prototype) 12097 << PossibleZeroParamPrototype 12098 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12099 } 12100 } 12101 12102 // GNU warning -Wstrict-prototypes 12103 // Warn if K&R function is defined without a previous declaration. 12104 // This warning is issued only if the definition itself does not provide 12105 // a prototype. Only K&R definitions do not provide a prototype. 12106 // An empty list in a function declarator that is part of a definition 12107 // of that function specifies that the function has no parameters 12108 // (C99 6.7.5.3p14) 12109 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12110 !LangOpts.CPlusPlus) { 12111 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12112 TypeLoc TL = TI->getTypeLoc(); 12113 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12114 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12115 } 12116 } 12117 12118 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12119 const CXXMethodDecl *KeyFunction; 12120 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12121 MD->isVirtual() && 12122 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12123 MD == KeyFunction->getCanonicalDecl()) { 12124 // Update the key-function state if necessary for this ABI. 12125 if (FD->isInlined() && 12126 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12127 Context.setNonKeyFunction(MD); 12128 12129 // If the newly-chosen key function is already defined, then we 12130 // need to mark the vtable as used retroactively. 12131 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12132 const FunctionDecl *Definition; 12133 if (KeyFunction && KeyFunction->isDefined(Definition)) 12134 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12135 } else { 12136 // We just defined they key function; mark the vtable as used. 12137 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12138 } 12139 } 12140 } 12141 12142 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12143 "Function parsing confused"); 12144 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12145 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12146 MD->setBody(Body); 12147 if (!MD->isInvalidDecl()) { 12148 DiagnoseUnusedParameters(MD->parameters()); 12149 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12150 MD->getReturnType(), MD); 12151 12152 if (Body) 12153 computeNRVO(Body, getCurFunction()); 12154 } 12155 if (getCurFunction()->ObjCShouldCallSuper) { 12156 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12157 << MD->getSelector().getAsString(); 12158 getCurFunction()->ObjCShouldCallSuper = false; 12159 } 12160 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12161 const ObjCMethodDecl *InitMethod = nullptr; 12162 bool isDesignated = 12163 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12164 assert(isDesignated && InitMethod); 12165 (void)isDesignated; 12166 12167 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12168 auto IFace = MD->getClassInterface(); 12169 if (!IFace) 12170 return false; 12171 auto SuperD = IFace->getSuperClass(); 12172 if (!SuperD) 12173 return false; 12174 return SuperD->getIdentifier() == 12175 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12176 }; 12177 // Don't issue this warning for unavailable inits or direct subclasses 12178 // of NSObject. 12179 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12180 Diag(MD->getLocation(), 12181 diag::warn_objc_designated_init_missing_super_call); 12182 Diag(InitMethod->getLocation(), 12183 diag::note_objc_designated_init_marked_here); 12184 } 12185 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12186 } 12187 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12188 // Don't issue this warning for unavaialable inits. 12189 if (!MD->isUnavailable()) 12190 Diag(MD->getLocation(), 12191 diag::warn_objc_secondary_init_missing_init_call); 12192 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12193 } 12194 } else { 12195 return nullptr; 12196 } 12197 12198 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12199 DiagnoseUnguardedAvailabilityViolations(dcl); 12200 12201 assert(!getCurFunction()->ObjCShouldCallSuper && 12202 "This should only be set for ObjC methods, which should have been " 12203 "handled in the block above."); 12204 12205 // Verify and clean out per-function state. 12206 if (Body && (!FD || !FD->isDefaulted())) { 12207 // C++ constructors that have function-try-blocks can't have return 12208 // statements in the handlers of that block. (C++ [except.handle]p14) 12209 // Verify this. 12210 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12211 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12212 12213 // Verify that gotos and switch cases don't jump into scopes illegally. 12214 if (getCurFunction()->NeedsScopeChecking() && 12215 !PP.isCodeCompletionEnabled()) 12216 DiagnoseInvalidJumps(Body); 12217 12218 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12219 if (!Destructor->getParent()->isDependentType()) 12220 CheckDestructor(Destructor); 12221 12222 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12223 Destructor->getParent()); 12224 } 12225 12226 // If any errors have occurred, clear out any temporaries that may have 12227 // been leftover. This ensures that these temporaries won't be picked up for 12228 // deletion in some later function. 12229 if (getDiagnostics().hasErrorOccurred() || 12230 getDiagnostics().getSuppressAllDiagnostics()) { 12231 DiscardCleanupsInEvaluationContext(); 12232 } 12233 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12234 !isa<FunctionTemplateDecl>(dcl)) { 12235 // Since the body is valid, issue any analysis-based warnings that are 12236 // enabled. 12237 ActivePolicy = &WP; 12238 } 12239 12240 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12241 (!CheckConstexprFunctionDecl(FD) || 12242 !CheckConstexprFunctionBody(FD, Body))) 12243 FD->setInvalidDecl(); 12244 12245 if (FD && FD->hasAttr<NakedAttr>()) { 12246 for (const Stmt *S : Body->children()) { 12247 // Allow local register variables without initializer as they don't 12248 // require prologue. 12249 bool RegisterVariables = false; 12250 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12251 for (const auto *Decl : DS->decls()) { 12252 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12253 RegisterVariables = 12254 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12255 if (!RegisterVariables) 12256 break; 12257 } 12258 } 12259 } 12260 if (RegisterVariables) 12261 continue; 12262 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12263 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12264 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12265 FD->setInvalidDecl(); 12266 break; 12267 } 12268 } 12269 } 12270 12271 assert(ExprCleanupObjects.size() == 12272 ExprEvalContexts.back().NumCleanupObjects && 12273 "Leftover temporaries in function"); 12274 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12275 assert(MaybeODRUseExprs.empty() && 12276 "Leftover expressions for odr-use checking"); 12277 } 12278 12279 if (!IsInstantiation) 12280 PopDeclContext(); 12281 12282 PopFunctionScopeInfo(ActivePolicy, dcl); 12283 // If any errors have occurred, clear out any temporaries that may have 12284 // been leftover. This ensures that these temporaries won't be picked up for 12285 // deletion in some later function. 12286 if (getDiagnostics().hasErrorOccurred()) { 12287 DiscardCleanupsInEvaluationContext(); 12288 } 12289 12290 return dcl; 12291 } 12292 12293 /// When we finish delayed parsing of an attribute, we must attach it to the 12294 /// relevant Decl. 12295 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12296 ParsedAttributes &Attrs) { 12297 // Always attach attributes to the underlying decl. 12298 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12299 D = TD->getTemplatedDecl(); 12300 ProcessDeclAttributeList(S, D, Attrs.getList()); 12301 12302 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12303 if (Method->isStatic()) 12304 checkThisInStaticMemberFunctionAttributes(Method); 12305 } 12306 12307 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12308 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12309 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12310 IdentifierInfo &II, Scope *S) { 12311 // Before we produce a declaration for an implicitly defined 12312 // function, see whether there was a locally-scoped declaration of 12313 // this name as a function or variable. If so, use that 12314 // (non-visible) declaration, and complain about it. 12315 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12316 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12317 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12318 return ExternCPrev; 12319 } 12320 12321 // Extension in C99. Legal in C90, but warn about it. 12322 unsigned diag_id; 12323 if (II.getName().startswith("__builtin_")) 12324 diag_id = diag::warn_builtin_unknown; 12325 else if (getLangOpts().C99) 12326 diag_id = diag::ext_implicit_function_decl; 12327 else 12328 diag_id = diag::warn_implicit_function_decl; 12329 Diag(Loc, diag_id) << &II; 12330 12331 // Because typo correction is expensive, only do it if the implicit 12332 // function declaration is going to be treated as an error. 12333 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12334 TypoCorrection Corrected; 12335 if (S && 12336 (Corrected = CorrectTypo( 12337 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12338 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12339 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12340 /*ErrorRecovery*/false); 12341 } 12342 12343 // Set a Declarator for the implicit definition: int foo(); 12344 const char *Dummy; 12345 AttributeFactory attrFactory; 12346 DeclSpec DS(attrFactory); 12347 unsigned DiagID; 12348 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12349 Context.getPrintingPolicy()); 12350 (void)Error; // Silence warning. 12351 assert(!Error && "Error setting up implicit decl!"); 12352 SourceLocation NoLoc; 12353 Declarator D(DS, Declarator::BlockContext); 12354 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12355 /*IsAmbiguous=*/false, 12356 /*LParenLoc=*/NoLoc, 12357 /*Params=*/nullptr, 12358 /*NumParams=*/0, 12359 /*EllipsisLoc=*/NoLoc, 12360 /*RParenLoc=*/NoLoc, 12361 /*TypeQuals=*/0, 12362 /*RefQualifierIsLvalueRef=*/true, 12363 /*RefQualifierLoc=*/NoLoc, 12364 /*ConstQualifierLoc=*/NoLoc, 12365 /*VolatileQualifierLoc=*/NoLoc, 12366 /*RestrictQualifierLoc=*/NoLoc, 12367 /*MutableLoc=*/NoLoc, 12368 EST_None, 12369 /*ESpecRange=*/SourceRange(), 12370 /*Exceptions=*/nullptr, 12371 /*ExceptionRanges=*/nullptr, 12372 /*NumExceptions=*/0, 12373 /*NoexceptExpr=*/nullptr, 12374 /*ExceptionSpecTokens=*/nullptr, 12375 /*DeclsInPrototype=*/None, 12376 Loc, Loc, D), 12377 DS.getAttributes(), 12378 SourceLocation()); 12379 D.SetIdentifier(&II, Loc); 12380 12381 // Insert this function into translation-unit scope. 12382 12383 DeclContext *PrevDC = CurContext; 12384 CurContext = Context.getTranslationUnitDecl(); 12385 12386 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12387 FD->setImplicit(); 12388 12389 CurContext = PrevDC; 12390 12391 AddKnownFunctionAttributes(FD); 12392 12393 return FD; 12394 } 12395 12396 /// \brief Adds any function attributes that we know a priori based on 12397 /// the declaration of this function. 12398 /// 12399 /// These attributes can apply both to implicitly-declared builtins 12400 /// (like __builtin___printf_chk) or to library-declared functions 12401 /// like NSLog or printf. 12402 /// 12403 /// We need to check for duplicate attributes both here and where user-written 12404 /// attributes are applied to declarations. 12405 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12406 if (FD->isInvalidDecl()) 12407 return; 12408 12409 // If this is a built-in function, map its builtin attributes to 12410 // actual attributes. 12411 if (unsigned BuiltinID = FD->getBuiltinID()) { 12412 // Handle printf-formatting attributes. 12413 unsigned FormatIdx; 12414 bool HasVAListArg; 12415 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12416 if (!FD->hasAttr<FormatAttr>()) { 12417 const char *fmt = "printf"; 12418 unsigned int NumParams = FD->getNumParams(); 12419 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12420 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12421 fmt = "NSString"; 12422 FD->addAttr(FormatAttr::CreateImplicit(Context, 12423 &Context.Idents.get(fmt), 12424 FormatIdx+1, 12425 HasVAListArg ? 0 : FormatIdx+2, 12426 FD->getLocation())); 12427 } 12428 } 12429 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12430 HasVAListArg)) { 12431 if (!FD->hasAttr<FormatAttr>()) 12432 FD->addAttr(FormatAttr::CreateImplicit(Context, 12433 &Context.Idents.get("scanf"), 12434 FormatIdx+1, 12435 HasVAListArg ? 0 : FormatIdx+2, 12436 FD->getLocation())); 12437 } 12438 12439 // Mark const if we don't care about errno and that is the only 12440 // thing preventing the function from being const. This allows 12441 // IRgen to use LLVM intrinsics for such functions. 12442 if (!getLangOpts().MathErrno && 12443 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12444 if (!FD->hasAttr<ConstAttr>()) 12445 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12446 } 12447 12448 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12449 !FD->hasAttr<ReturnsTwiceAttr>()) 12450 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12451 FD->getLocation())); 12452 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12453 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12454 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12455 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12456 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12457 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12458 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12459 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12460 // Add the appropriate attribute, depending on the CUDA compilation mode 12461 // and which target the builtin belongs to. For example, during host 12462 // compilation, aux builtins are __device__, while the rest are __host__. 12463 if (getLangOpts().CUDAIsDevice != 12464 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12465 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12466 else 12467 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12468 } 12469 } 12470 12471 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12472 // throw, add an implicit nothrow attribute to any extern "C" function we come 12473 // across. 12474 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12475 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12476 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12477 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12478 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12479 } 12480 12481 IdentifierInfo *Name = FD->getIdentifier(); 12482 if (!Name) 12483 return; 12484 if ((!getLangOpts().CPlusPlus && 12485 FD->getDeclContext()->isTranslationUnit()) || 12486 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12487 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12488 LinkageSpecDecl::lang_c)) { 12489 // Okay: this could be a libc/libm/Objective-C function we know 12490 // about. 12491 } else 12492 return; 12493 12494 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12495 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12496 // target-specific builtins, perhaps? 12497 if (!FD->hasAttr<FormatAttr>()) 12498 FD->addAttr(FormatAttr::CreateImplicit(Context, 12499 &Context.Idents.get("printf"), 2, 12500 Name->isStr("vasprintf") ? 0 : 3, 12501 FD->getLocation())); 12502 } 12503 12504 if (Name->isStr("__CFStringMakeConstantString")) { 12505 // We already have a __builtin___CFStringMakeConstantString, 12506 // but builds that use -fno-constant-cfstrings don't go through that. 12507 if (!FD->hasAttr<FormatArgAttr>()) 12508 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12509 FD->getLocation())); 12510 } 12511 } 12512 12513 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12514 TypeSourceInfo *TInfo) { 12515 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12516 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12517 12518 if (!TInfo) { 12519 assert(D.isInvalidType() && "no declarator info for valid type"); 12520 TInfo = Context.getTrivialTypeSourceInfo(T); 12521 } 12522 12523 // Scope manipulation handled by caller. 12524 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12525 D.getLocStart(), 12526 D.getIdentifierLoc(), 12527 D.getIdentifier(), 12528 TInfo); 12529 12530 // Bail out immediately if we have an invalid declaration. 12531 if (D.isInvalidType()) { 12532 NewTD->setInvalidDecl(); 12533 return NewTD; 12534 } 12535 12536 if (D.getDeclSpec().isModulePrivateSpecified()) { 12537 if (CurContext->isFunctionOrMethod()) 12538 Diag(NewTD->getLocation(), diag::err_module_private_local) 12539 << 2 << NewTD->getDeclName() 12540 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12541 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12542 else 12543 NewTD->setModulePrivate(); 12544 } 12545 12546 // C++ [dcl.typedef]p8: 12547 // If the typedef declaration defines an unnamed class (or 12548 // enum), the first typedef-name declared by the declaration 12549 // to be that class type (or enum type) is used to denote the 12550 // class type (or enum type) for linkage purposes only. 12551 // We need to check whether the type was declared in the declaration. 12552 switch (D.getDeclSpec().getTypeSpecType()) { 12553 case TST_enum: 12554 case TST_struct: 12555 case TST_interface: 12556 case TST_union: 12557 case TST_class: { 12558 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12559 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12560 break; 12561 } 12562 12563 default: 12564 break; 12565 } 12566 12567 return NewTD; 12568 } 12569 12570 /// \brief Check that this is a valid underlying type for an enum declaration. 12571 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12572 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12573 QualType T = TI->getType(); 12574 12575 if (T->isDependentType()) 12576 return false; 12577 12578 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12579 if (BT->isInteger()) 12580 return false; 12581 12582 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12583 return true; 12584 } 12585 12586 /// Check whether this is a valid redeclaration of a previous enumeration. 12587 /// \return true if the redeclaration was invalid. 12588 bool Sema::CheckEnumRedeclaration( 12589 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12590 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12591 bool IsFixed = !EnumUnderlyingTy.isNull(); 12592 12593 if (IsScoped != Prev->isScoped()) { 12594 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12595 << Prev->isScoped(); 12596 Diag(Prev->getLocation(), diag::note_previous_declaration); 12597 return true; 12598 } 12599 12600 if (IsFixed && Prev->isFixed()) { 12601 if (!EnumUnderlyingTy->isDependentType() && 12602 !Prev->getIntegerType()->isDependentType() && 12603 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12604 Prev->getIntegerType())) { 12605 // TODO: Highlight the underlying type of the redeclaration. 12606 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12607 << EnumUnderlyingTy << Prev->getIntegerType(); 12608 Diag(Prev->getLocation(), diag::note_previous_declaration) 12609 << Prev->getIntegerTypeRange(); 12610 return true; 12611 } 12612 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12613 ; 12614 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12615 ; 12616 } else if (IsFixed != Prev->isFixed()) { 12617 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12618 << Prev->isFixed(); 12619 Diag(Prev->getLocation(), diag::note_previous_declaration); 12620 return true; 12621 } 12622 12623 return false; 12624 } 12625 12626 /// \brief Get diagnostic %select index for tag kind for 12627 /// redeclaration diagnostic message. 12628 /// WARNING: Indexes apply to particular diagnostics only! 12629 /// 12630 /// \returns diagnostic %select index. 12631 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12632 switch (Tag) { 12633 case TTK_Struct: return 0; 12634 case TTK_Interface: return 1; 12635 case TTK_Class: return 2; 12636 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12637 } 12638 } 12639 12640 /// \brief Determine if tag kind is a class-key compatible with 12641 /// class for redeclaration (class, struct, or __interface). 12642 /// 12643 /// \returns true iff the tag kind is compatible. 12644 static bool isClassCompatTagKind(TagTypeKind Tag) 12645 { 12646 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12647 } 12648 12649 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12650 TagTypeKind TTK) { 12651 if (isa<TypedefDecl>(PrevDecl)) 12652 return NTK_Typedef; 12653 else if (isa<TypeAliasDecl>(PrevDecl)) 12654 return NTK_TypeAlias; 12655 else if (isa<ClassTemplateDecl>(PrevDecl)) 12656 return NTK_Template; 12657 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12658 return NTK_TypeAliasTemplate; 12659 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12660 return NTK_TemplateTemplateArgument; 12661 switch (TTK) { 12662 case TTK_Struct: 12663 case TTK_Interface: 12664 case TTK_Class: 12665 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12666 case TTK_Union: 12667 return NTK_NonUnion; 12668 case TTK_Enum: 12669 return NTK_NonEnum; 12670 } 12671 llvm_unreachable("invalid TTK"); 12672 } 12673 12674 /// \brief Determine whether a tag with a given kind is acceptable 12675 /// as a redeclaration of the given tag declaration. 12676 /// 12677 /// \returns true if the new tag kind is acceptable, false otherwise. 12678 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12679 TagTypeKind NewTag, bool isDefinition, 12680 SourceLocation NewTagLoc, 12681 const IdentifierInfo *Name) { 12682 // C++ [dcl.type.elab]p3: 12683 // The class-key or enum keyword present in the 12684 // elaborated-type-specifier shall agree in kind with the 12685 // declaration to which the name in the elaborated-type-specifier 12686 // refers. This rule also applies to the form of 12687 // elaborated-type-specifier that declares a class-name or 12688 // friend class since it can be construed as referring to the 12689 // definition of the class. Thus, in any 12690 // elaborated-type-specifier, the enum keyword shall be used to 12691 // refer to an enumeration (7.2), the union class-key shall be 12692 // used to refer to a union (clause 9), and either the class or 12693 // struct class-key shall be used to refer to a class (clause 9) 12694 // declared using the class or struct class-key. 12695 TagTypeKind OldTag = Previous->getTagKind(); 12696 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12697 if (OldTag == NewTag) 12698 return true; 12699 12700 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12701 // Warn about the struct/class tag mismatch. 12702 bool isTemplate = false; 12703 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12704 isTemplate = Record->getDescribedClassTemplate(); 12705 12706 if (inTemplateInstantiation()) { 12707 // In a template instantiation, do not offer fix-its for tag mismatches 12708 // since they usually mess up the template instead of fixing the problem. 12709 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12710 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12711 << getRedeclDiagFromTagKind(OldTag); 12712 return true; 12713 } 12714 12715 if (isDefinition) { 12716 // On definitions, check previous tags and issue a fix-it for each 12717 // one that doesn't match the current tag. 12718 if (Previous->getDefinition()) { 12719 // Don't suggest fix-its for redefinitions. 12720 return true; 12721 } 12722 12723 bool previousMismatch = false; 12724 for (auto I : Previous->redecls()) { 12725 if (I->getTagKind() != NewTag) { 12726 if (!previousMismatch) { 12727 previousMismatch = true; 12728 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12729 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12730 << getRedeclDiagFromTagKind(I->getTagKind()); 12731 } 12732 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12733 << getRedeclDiagFromTagKind(NewTag) 12734 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12735 TypeWithKeyword::getTagTypeKindName(NewTag)); 12736 } 12737 } 12738 return true; 12739 } 12740 12741 // Check for a previous definition. If current tag and definition 12742 // are same type, do nothing. If no definition, but disagree with 12743 // with previous tag type, give a warning, but no fix-it. 12744 const TagDecl *Redecl = Previous->getDefinition() ? 12745 Previous->getDefinition() : Previous; 12746 if (Redecl->getTagKind() == NewTag) { 12747 return true; 12748 } 12749 12750 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12751 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12752 << getRedeclDiagFromTagKind(OldTag); 12753 Diag(Redecl->getLocation(), diag::note_previous_use); 12754 12755 // If there is a previous definition, suggest a fix-it. 12756 if (Previous->getDefinition()) { 12757 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12758 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12759 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12760 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12761 } 12762 12763 return true; 12764 } 12765 return false; 12766 } 12767 12768 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12769 /// from an outer enclosing namespace or file scope inside a friend declaration. 12770 /// This should provide the commented out code in the following snippet: 12771 /// namespace N { 12772 /// struct X; 12773 /// namespace M { 12774 /// struct Y { friend struct /*N::*/ X; }; 12775 /// } 12776 /// } 12777 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12778 SourceLocation NameLoc) { 12779 // While the decl is in a namespace, do repeated lookup of that name and see 12780 // if we get the same namespace back. If we do not, continue until 12781 // translation unit scope, at which point we have a fully qualified NNS. 12782 SmallVector<IdentifierInfo *, 4> Namespaces; 12783 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12784 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12785 // This tag should be declared in a namespace, which can only be enclosed by 12786 // other namespaces. Bail if there's an anonymous namespace in the chain. 12787 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12788 if (!Namespace || Namespace->isAnonymousNamespace()) 12789 return FixItHint(); 12790 IdentifierInfo *II = Namespace->getIdentifier(); 12791 Namespaces.push_back(II); 12792 NamedDecl *Lookup = SemaRef.LookupSingleName( 12793 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12794 if (Lookup == Namespace) 12795 break; 12796 } 12797 12798 // Once we have all the namespaces, reverse them to go outermost first, and 12799 // build an NNS. 12800 SmallString<64> Insertion; 12801 llvm::raw_svector_ostream OS(Insertion); 12802 if (DC->isTranslationUnit()) 12803 OS << "::"; 12804 std::reverse(Namespaces.begin(), Namespaces.end()); 12805 for (auto *II : Namespaces) 12806 OS << II->getName() << "::"; 12807 return FixItHint::CreateInsertion(NameLoc, Insertion); 12808 } 12809 12810 /// \brief Determine whether a tag originally declared in context \p OldDC can 12811 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12812 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12813 /// using-declaration). 12814 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12815 DeclContext *NewDC) { 12816 OldDC = OldDC->getRedeclContext(); 12817 NewDC = NewDC->getRedeclContext(); 12818 12819 if (OldDC->Equals(NewDC)) 12820 return true; 12821 12822 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12823 // encloses the other). 12824 if (S.getLangOpts().MSVCCompat && 12825 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12826 return true; 12827 12828 return false; 12829 } 12830 12831 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12832 /// former case, Name will be non-null. In the later case, Name will be null. 12833 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12834 /// reference/declaration/definition of a tag. 12835 /// 12836 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12837 /// trailing-type-specifier) other than one in an alias-declaration. 12838 /// 12839 /// \param SkipBody If non-null, will be set to indicate if the caller should 12840 /// skip the definition of this tag and treat it as if it were a declaration. 12841 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12842 SourceLocation KWLoc, CXXScopeSpec &SS, 12843 IdentifierInfo *Name, SourceLocation NameLoc, 12844 AttributeList *Attr, AccessSpecifier AS, 12845 SourceLocation ModulePrivateLoc, 12846 MultiTemplateParamsArg TemplateParameterLists, 12847 bool &OwnedDecl, bool &IsDependent, 12848 SourceLocation ScopedEnumKWLoc, 12849 bool ScopedEnumUsesClassTag, 12850 TypeResult UnderlyingType, 12851 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12852 // If this is not a definition, it must have a name. 12853 IdentifierInfo *OrigName = Name; 12854 assert((Name != nullptr || TUK == TUK_Definition) && 12855 "Nameless record must be a definition!"); 12856 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12857 12858 OwnedDecl = false; 12859 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12860 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12861 12862 // FIXME: Check member specializations more carefully. 12863 bool isMemberSpecialization = false; 12864 bool Invalid = false; 12865 12866 // We only need to do this matching if we have template parameters 12867 // or a scope specifier, which also conveniently avoids this work 12868 // for non-C++ cases. 12869 if (TemplateParameterLists.size() > 0 || 12870 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12871 if (TemplateParameterList *TemplateParams = 12872 MatchTemplateParametersToScopeSpecifier( 12873 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12874 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 12875 if (Kind == TTK_Enum) { 12876 Diag(KWLoc, diag::err_enum_template); 12877 return nullptr; 12878 } 12879 12880 if (TemplateParams->size() > 0) { 12881 // This is a declaration or definition of a class template (which may 12882 // be a member of another template). 12883 12884 if (Invalid) 12885 return nullptr; 12886 12887 OwnedDecl = false; 12888 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12889 SS, Name, NameLoc, Attr, 12890 TemplateParams, AS, 12891 ModulePrivateLoc, 12892 /*FriendLoc*/SourceLocation(), 12893 TemplateParameterLists.size()-1, 12894 TemplateParameterLists.data(), 12895 SkipBody); 12896 return Result.get(); 12897 } else { 12898 // The "template<>" header is extraneous. 12899 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12900 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12901 isMemberSpecialization = true; 12902 } 12903 } 12904 } 12905 12906 // Figure out the underlying type if this a enum declaration. We need to do 12907 // this early, because it's needed to detect if this is an incompatible 12908 // redeclaration. 12909 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12910 bool EnumUnderlyingIsImplicit = false; 12911 12912 if (Kind == TTK_Enum) { 12913 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12914 // No underlying type explicitly specified, or we failed to parse the 12915 // type, default to int. 12916 EnumUnderlying = Context.IntTy.getTypePtr(); 12917 else if (UnderlyingType.get()) { 12918 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12919 // integral type; any cv-qualification is ignored. 12920 TypeSourceInfo *TI = nullptr; 12921 GetTypeFromParser(UnderlyingType.get(), &TI); 12922 EnumUnderlying = TI; 12923 12924 if (CheckEnumUnderlyingType(TI)) 12925 // Recover by falling back to int. 12926 EnumUnderlying = Context.IntTy.getTypePtr(); 12927 12928 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12929 UPPC_FixedUnderlyingType)) 12930 EnumUnderlying = Context.IntTy.getTypePtr(); 12931 12932 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12933 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12934 // Microsoft enums are always of int type. 12935 EnumUnderlying = Context.IntTy.getTypePtr(); 12936 EnumUnderlyingIsImplicit = true; 12937 } 12938 } 12939 } 12940 12941 DeclContext *SearchDC = CurContext; 12942 DeclContext *DC = CurContext; 12943 bool isStdBadAlloc = false; 12944 bool isStdAlignValT = false; 12945 12946 RedeclarationKind Redecl = ForRedeclaration; 12947 if (TUK == TUK_Friend || TUK == TUK_Reference) 12948 Redecl = NotForRedeclaration; 12949 12950 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12951 if (Name && SS.isNotEmpty()) { 12952 // We have a nested-name tag ('struct foo::bar'). 12953 12954 // Check for invalid 'foo::'. 12955 if (SS.isInvalid()) { 12956 Name = nullptr; 12957 goto CreateNewDecl; 12958 } 12959 12960 // If this is a friend or a reference to a class in a dependent 12961 // context, don't try to make a decl for it. 12962 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12963 DC = computeDeclContext(SS, false); 12964 if (!DC) { 12965 IsDependent = true; 12966 return nullptr; 12967 } 12968 } else { 12969 DC = computeDeclContext(SS, true); 12970 if (!DC) { 12971 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12972 << SS.getRange(); 12973 return nullptr; 12974 } 12975 } 12976 12977 if (RequireCompleteDeclContext(SS, DC)) 12978 return nullptr; 12979 12980 SearchDC = DC; 12981 // Look-up name inside 'foo::'. 12982 LookupQualifiedName(Previous, DC); 12983 12984 if (Previous.isAmbiguous()) 12985 return nullptr; 12986 12987 if (Previous.empty()) { 12988 // Name lookup did not find anything. However, if the 12989 // nested-name-specifier refers to the current instantiation, 12990 // and that current instantiation has any dependent base 12991 // classes, we might find something at instantiation time: treat 12992 // this as a dependent elaborated-type-specifier. 12993 // But this only makes any sense for reference-like lookups. 12994 if (Previous.wasNotFoundInCurrentInstantiation() && 12995 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12996 IsDependent = true; 12997 return nullptr; 12998 } 12999 13000 // A tag 'foo::bar' must already exist. 13001 Diag(NameLoc, diag::err_not_tag_in_scope) 13002 << Kind << Name << DC << SS.getRange(); 13003 Name = nullptr; 13004 Invalid = true; 13005 goto CreateNewDecl; 13006 } 13007 } else if (Name) { 13008 // C++14 [class.mem]p14: 13009 // If T is the name of a class, then each of the following shall have a 13010 // name different from T: 13011 // -- every member of class T that is itself a type 13012 if (TUK != TUK_Reference && TUK != TUK_Friend && 13013 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13014 return nullptr; 13015 13016 // If this is a named struct, check to see if there was a previous forward 13017 // declaration or definition. 13018 // FIXME: We're looking into outer scopes here, even when we 13019 // shouldn't be. Doing so can result in ambiguities that we 13020 // shouldn't be diagnosing. 13021 LookupName(Previous, S); 13022 13023 // When declaring or defining a tag, ignore ambiguities introduced 13024 // by types using'ed into this scope. 13025 if (Previous.isAmbiguous() && 13026 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13027 LookupResult::Filter F = Previous.makeFilter(); 13028 while (F.hasNext()) { 13029 NamedDecl *ND = F.next(); 13030 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13031 SearchDC->getRedeclContext())) 13032 F.erase(); 13033 } 13034 F.done(); 13035 } 13036 13037 // C++11 [namespace.memdef]p3: 13038 // If the name in a friend declaration is neither qualified nor 13039 // a template-id and the declaration is a function or an 13040 // elaborated-type-specifier, the lookup to determine whether 13041 // the entity has been previously declared shall not consider 13042 // any scopes outside the innermost enclosing namespace. 13043 // 13044 // MSVC doesn't implement the above rule for types, so a friend tag 13045 // declaration may be a redeclaration of a type declared in an enclosing 13046 // scope. They do implement this rule for friend functions. 13047 // 13048 // Does it matter that this should be by scope instead of by 13049 // semantic context? 13050 if (!Previous.empty() && TUK == TUK_Friend) { 13051 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13052 LookupResult::Filter F = Previous.makeFilter(); 13053 bool FriendSawTagOutsideEnclosingNamespace = false; 13054 while (F.hasNext()) { 13055 NamedDecl *ND = F.next(); 13056 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13057 if (DC->isFileContext() && 13058 !EnclosingNS->Encloses(ND->getDeclContext())) { 13059 if (getLangOpts().MSVCCompat) 13060 FriendSawTagOutsideEnclosingNamespace = true; 13061 else 13062 F.erase(); 13063 } 13064 } 13065 F.done(); 13066 13067 // Diagnose this MSVC extension in the easy case where lookup would have 13068 // unambiguously found something outside the enclosing namespace. 13069 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13070 NamedDecl *ND = Previous.getFoundDecl(); 13071 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13072 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13073 } 13074 } 13075 13076 // Note: there used to be some attempt at recovery here. 13077 if (Previous.isAmbiguous()) 13078 return nullptr; 13079 13080 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13081 // FIXME: This makes sure that we ignore the contexts associated 13082 // with C structs, unions, and enums when looking for a matching 13083 // tag declaration or definition. See the similar lookup tweak 13084 // in Sema::LookupName; is there a better way to deal with this? 13085 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13086 SearchDC = SearchDC->getParent(); 13087 } 13088 } 13089 13090 if (Previous.isSingleResult() && 13091 Previous.getFoundDecl()->isTemplateParameter()) { 13092 // Maybe we will complain about the shadowed template parameter. 13093 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13094 // Just pretend that we didn't see the previous declaration. 13095 Previous.clear(); 13096 } 13097 13098 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13099 DC->Equals(getStdNamespace())) { 13100 if (Name->isStr("bad_alloc")) { 13101 // This is a declaration of or a reference to "std::bad_alloc". 13102 isStdBadAlloc = true; 13103 13104 // If std::bad_alloc has been implicitly declared (but made invisible to 13105 // name lookup), fill in this implicit declaration as the previous 13106 // declaration, so that the declarations get chained appropriately. 13107 if (Previous.empty() && StdBadAlloc) 13108 Previous.addDecl(getStdBadAlloc()); 13109 } else if (Name->isStr("align_val_t")) { 13110 isStdAlignValT = true; 13111 if (Previous.empty() && StdAlignValT) 13112 Previous.addDecl(getStdAlignValT()); 13113 } 13114 } 13115 13116 // If we didn't find a previous declaration, and this is a reference 13117 // (or friend reference), move to the correct scope. In C++, we 13118 // also need to do a redeclaration lookup there, just in case 13119 // there's a shadow friend decl. 13120 if (Name && Previous.empty() && 13121 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13122 if (Invalid) goto CreateNewDecl; 13123 assert(SS.isEmpty()); 13124 13125 if (TUK == TUK_Reference) { 13126 // C++ [basic.scope.pdecl]p5: 13127 // -- for an elaborated-type-specifier of the form 13128 // 13129 // class-key identifier 13130 // 13131 // if the elaborated-type-specifier is used in the 13132 // decl-specifier-seq or parameter-declaration-clause of a 13133 // function defined in namespace scope, the identifier is 13134 // declared as a class-name in the namespace that contains 13135 // the declaration; otherwise, except as a friend 13136 // declaration, the identifier is declared in the smallest 13137 // non-class, non-function-prototype scope that contains the 13138 // declaration. 13139 // 13140 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13141 // C structs and unions. 13142 // 13143 // It is an error in C++ to declare (rather than define) an enum 13144 // type, including via an elaborated type specifier. We'll 13145 // diagnose that later; for now, declare the enum in the same 13146 // scope as we would have picked for any other tag type. 13147 // 13148 // GNU C also supports this behavior as part of its incomplete 13149 // enum types extension, while GNU C++ does not. 13150 // 13151 // Find the context where we'll be declaring the tag. 13152 // FIXME: We would like to maintain the current DeclContext as the 13153 // lexical context, 13154 SearchDC = getTagInjectionContext(SearchDC); 13155 13156 // Find the scope where we'll be declaring the tag. 13157 S = getTagInjectionScope(S, getLangOpts()); 13158 } else { 13159 assert(TUK == TUK_Friend); 13160 // C++ [namespace.memdef]p3: 13161 // If a friend declaration in a non-local class first declares a 13162 // class or function, the friend class or function is a member of 13163 // the innermost enclosing namespace. 13164 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13165 } 13166 13167 // In C++, we need to do a redeclaration lookup to properly 13168 // diagnose some problems. 13169 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13170 // hidden declaration so that we don't get ambiguity errors when using a 13171 // type declared by an elaborated-type-specifier. In C that is not correct 13172 // and we should instead merge compatible types found by lookup. 13173 if (getLangOpts().CPlusPlus) { 13174 Previous.setRedeclarationKind(ForRedeclaration); 13175 LookupQualifiedName(Previous, SearchDC); 13176 } else { 13177 Previous.setRedeclarationKind(ForRedeclaration); 13178 LookupName(Previous, S); 13179 } 13180 } 13181 13182 // If we have a known previous declaration to use, then use it. 13183 if (Previous.empty() && SkipBody && SkipBody->Previous) 13184 Previous.addDecl(SkipBody->Previous); 13185 13186 if (!Previous.empty()) { 13187 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13188 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13189 13190 // It's okay to have a tag decl in the same scope as a typedef 13191 // which hides a tag decl in the same scope. Finding this 13192 // insanity with a redeclaration lookup can only actually happen 13193 // in C++. 13194 // 13195 // This is also okay for elaborated-type-specifiers, which is 13196 // technically forbidden by the current standard but which is 13197 // okay according to the likely resolution of an open issue; 13198 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13199 if (getLangOpts().CPlusPlus) { 13200 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13201 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13202 TagDecl *Tag = TT->getDecl(); 13203 if (Tag->getDeclName() == Name && 13204 Tag->getDeclContext()->getRedeclContext() 13205 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13206 PrevDecl = Tag; 13207 Previous.clear(); 13208 Previous.addDecl(Tag); 13209 Previous.resolveKind(); 13210 } 13211 } 13212 } 13213 } 13214 13215 // If this is a redeclaration of a using shadow declaration, it must 13216 // declare a tag in the same context. In MSVC mode, we allow a 13217 // redefinition if either context is within the other. 13218 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13219 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13220 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13221 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13222 !(OldTag && isAcceptableTagRedeclContext( 13223 *this, OldTag->getDeclContext(), SearchDC))) { 13224 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13225 Diag(Shadow->getTargetDecl()->getLocation(), 13226 diag::note_using_decl_target); 13227 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13228 << 0; 13229 // Recover by ignoring the old declaration. 13230 Previous.clear(); 13231 goto CreateNewDecl; 13232 } 13233 } 13234 13235 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13236 // If this is a use of a previous tag, or if the tag is already declared 13237 // in the same scope (so that the definition/declaration completes or 13238 // rementions the tag), reuse the decl. 13239 if (TUK == TUK_Reference || TUK == TUK_Friend || 13240 isDeclInScope(DirectPrevDecl, SearchDC, S, 13241 SS.isNotEmpty() || isMemberSpecialization)) { 13242 // Make sure that this wasn't declared as an enum and now used as a 13243 // struct or something similar. 13244 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13245 TUK == TUK_Definition, KWLoc, 13246 Name)) { 13247 bool SafeToContinue 13248 = (PrevTagDecl->getTagKind() != TTK_Enum && 13249 Kind != TTK_Enum); 13250 if (SafeToContinue) 13251 Diag(KWLoc, diag::err_use_with_wrong_tag) 13252 << Name 13253 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13254 PrevTagDecl->getKindName()); 13255 else 13256 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13257 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13258 13259 if (SafeToContinue) 13260 Kind = PrevTagDecl->getTagKind(); 13261 else { 13262 // Recover by making this an anonymous redefinition. 13263 Name = nullptr; 13264 Previous.clear(); 13265 Invalid = true; 13266 } 13267 } 13268 13269 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13270 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13271 13272 // If this is an elaborated-type-specifier for a scoped enumeration, 13273 // the 'class' keyword is not necessary and not permitted. 13274 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13275 if (ScopedEnum) 13276 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13277 << PrevEnum->isScoped() 13278 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13279 return PrevTagDecl; 13280 } 13281 13282 QualType EnumUnderlyingTy; 13283 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13284 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13285 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13286 EnumUnderlyingTy = QualType(T, 0); 13287 13288 // All conflicts with previous declarations are recovered by 13289 // returning the previous declaration, unless this is a definition, 13290 // in which case we want the caller to bail out. 13291 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13292 ScopedEnum, EnumUnderlyingTy, 13293 EnumUnderlyingIsImplicit, PrevEnum)) 13294 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13295 } 13296 13297 // C++11 [class.mem]p1: 13298 // A member shall not be declared twice in the member-specification, 13299 // except that a nested class or member class template can be declared 13300 // and then later defined. 13301 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13302 S->isDeclScope(PrevDecl)) { 13303 Diag(NameLoc, diag::ext_member_redeclared); 13304 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13305 } 13306 13307 if (!Invalid) { 13308 // If this is a use, just return the declaration we found, unless 13309 // we have attributes. 13310 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13311 if (Attr) { 13312 // FIXME: Diagnose these attributes. For now, we create a new 13313 // declaration to hold them. 13314 } else if (TUK == TUK_Reference && 13315 (PrevTagDecl->getFriendObjectKind() == 13316 Decl::FOK_Undeclared || 13317 PP.getModuleContainingLocation( 13318 PrevDecl->getLocation()) != 13319 PP.getModuleContainingLocation(KWLoc)) && 13320 SS.isEmpty()) { 13321 // This declaration is a reference to an existing entity, but 13322 // has different visibility from that entity: it either makes 13323 // a friend visible or it makes a type visible in a new module. 13324 // In either case, create a new declaration. We only do this if 13325 // the declaration would have meant the same thing if no prior 13326 // declaration were found, that is, if it was found in the same 13327 // scope where we would have injected a declaration. 13328 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13329 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13330 return PrevTagDecl; 13331 // This is in the injected scope, create a new declaration in 13332 // that scope. 13333 S = getTagInjectionScope(S, getLangOpts()); 13334 } else { 13335 return PrevTagDecl; 13336 } 13337 } 13338 13339 // Diagnose attempts to redefine a tag. 13340 if (TUK == TUK_Definition) { 13341 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13342 // If we're defining a specialization and the previous definition 13343 // is from an implicit instantiation, don't emit an error 13344 // here; we'll catch this in the general case below. 13345 bool IsExplicitSpecializationAfterInstantiation = false; 13346 if (isMemberSpecialization) { 13347 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13348 IsExplicitSpecializationAfterInstantiation = 13349 RD->getTemplateSpecializationKind() != 13350 TSK_ExplicitSpecialization; 13351 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13352 IsExplicitSpecializationAfterInstantiation = 13353 ED->getTemplateSpecializationKind() != 13354 TSK_ExplicitSpecialization; 13355 } 13356 13357 NamedDecl *Hidden = nullptr; 13358 if (SkipBody && getLangOpts().CPlusPlus && 13359 !hasVisibleDefinition(Def, &Hidden)) { 13360 // There is a definition of this tag, but it is not visible. We 13361 // explicitly make use of C++'s one definition rule here, and 13362 // assume that this definition is identical to the hidden one 13363 // we already have. Make the existing definition visible and 13364 // use it in place of this one. 13365 SkipBody->ShouldSkip = true; 13366 makeMergedDefinitionVisible(Hidden, KWLoc); 13367 return Def; 13368 } else if (!IsExplicitSpecializationAfterInstantiation) { 13369 // A redeclaration in function prototype scope in C isn't 13370 // visible elsewhere, so merely issue a warning. 13371 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13372 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13373 else 13374 Diag(NameLoc, diag::err_redefinition) << Name; 13375 Diag(Def->getLocation(), diag::note_previous_definition); 13376 // If this is a redefinition, recover by making this 13377 // struct be anonymous, which will make any later 13378 // references get the previous definition. 13379 Name = nullptr; 13380 Previous.clear(); 13381 Invalid = true; 13382 } 13383 } else { 13384 // If the type is currently being defined, complain 13385 // about a nested redefinition. 13386 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13387 if (TD->isBeingDefined()) { 13388 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13389 Diag(PrevTagDecl->getLocation(), 13390 diag::note_previous_definition); 13391 Name = nullptr; 13392 Previous.clear(); 13393 Invalid = true; 13394 } 13395 } 13396 13397 // Okay, this is definition of a previously declared or referenced 13398 // tag. We're going to create a new Decl for it. 13399 } 13400 13401 // Okay, we're going to make a redeclaration. If this is some kind 13402 // of reference, make sure we build the redeclaration in the same DC 13403 // as the original, and ignore the current access specifier. 13404 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13405 SearchDC = PrevTagDecl->getDeclContext(); 13406 AS = AS_none; 13407 } 13408 } 13409 // If we get here we have (another) forward declaration or we 13410 // have a definition. Just create a new decl. 13411 13412 } else { 13413 // If we get here, this is a definition of a new tag type in a nested 13414 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13415 // new decl/type. We set PrevDecl to NULL so that the entities 13416 // have distinct types. 13417 Previous.clear(); 13418 } 13419 // If we get here, we're going to create a new Decl. If PrevDecl 13420 // is non-NULL, it's a definition of the tag declared by 13421 // PrevDecl. If it's NULL, we have a new definition. 13422 13423 // Otherwise, PrevDecl is not a tag, but was found with tag 13424 // lookup. This is only actually possible in C++, where a few 13425 // things like templates still live in the tag namespace. 13426 } else { 13427 // Use a better diagnostic if an elaborated-type-specifier 13428 // found the wrong kind of type on the first 13429 // (non-redeclaration) lookup. 13430 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13431 !Previous.isForRedeclaration()) { 13432 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13433 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13434 << Kind; 13435 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13436 Invalid = true; 13437 13438 // Otherwise, only diagnose if the declaration is in scope. 13439 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13440 SS.isNotEmpty() || isMemberSpecialization)) { 13441 // do nothing 13442 13443 // Diagnose implicit declarations introduced by elaborated types. 13444 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13445 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13446 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13447 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13448 Invalid = true; 13449 13450 // Otherwise it's a declaration. Call out a particularly common 13451 // case here. 13452 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13453 unsigned Kind = 0; 13454 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13455 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13456 << Name << Kind << TND->getUnderlyingType(); 13457 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13458 Invalid = true; 13459 13460 // Otherwise, diagnose. 13461 } else { 13462 // The tag name clashes with something else in the target scope, 13463 // issue an error and recover by making this tag be anonymous. 13464 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13465 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13466 Name = nullptr; 13467 Invalid = true; 13468 } 13469 13470 // The existing declaration isn't relevant to us; we're in a 13471 // new scope, so clear out the previous declaration. 13472 Previous.clear(); 13473 } 13474 } 13475 13476 CreateNewDecl: 13477 13478 TagDecl *PrevDecl = nullptr; 13479 if (Previous.isSingleResult()) 13480 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13481 13482 // If there is an identifier, use the location of the identifier as the 13483 // location of the decl, otherwise use the location of the struct/union 13484 // keyword. 13485 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13486 13487 // Otherwise, create a new declaration. If there is a previous 13488 // declaration of the same entity, the two will be linked via 13489 // PrevDecl. 13490 TagDecl *New; 13491 13492 bool IsForwardReference = false; 13493 if (Kind == TTK_Enum) { 13494 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13495 // enum X { A, B, C } D; D should chain to X. 13496 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13497 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13498 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13499 13500 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13501 StdAlignValT = cast<EnumDecl>(New); 13502 13503 // If this is an undefined enum, warn. 13504 if (TUK != TUK_Definition && !Invalid) { 13505 TagDecl *Def; 13506 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13507 cast<EnumDecl>(New)->isFixed()) { 13508 // C++0x: 7.2p2: opaque-enum-declaration. 13509 // Conflicts are diagnosed above. Do nothing. 13510 } 13511 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13512 Diag(Loc, diag::ext_forward_ref_enum_def) 13513 << New; 13514 Diag(Def->getLocation(), diag::note_previous_definition); 13515 } else { 13516 unsigned DiagID = diag::ext_forward_ref_enum; 13517 if (getLangOpts().MSVCCompat) 13518 DiagID = diag::ext_ms_forward_ref_enum; 13519 else if (getLangOpts().CPlusPlus) 13520 DiagID = diag::err_forward_ref_enum; 13521 Diag(Loc, DiagID); 13522 13523 // If this is a forward-declared reference to an enumeration, make a 13524 // note of it; we won't actually be introducing the declaration into 13525 // the declaration context. 13526 if (TUK == TUK_Reference) 13527 IsForwardReference = true; 13528 } 13529 } 13530 13531 if (EnumUnderlying) { 13532 EnumDecl *ED = cast<EnumDecl>(New); 13533 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13534 ED->setIntegerTypeSourceInfo(TI); 13535 else 13536 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13537 ED->setPromotionType(ED->getIntegerType()); 13538 } 13539 } else { 13540 // struct/union/class 13541 13542 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13543 // struct X { int A; } D; D should chain to X. 13544 if (getLangOpts().CPlusPlus) { 13545 // FIXME: Look for a way to use RecordDecl for simple structs. 13546 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13547 cast_or_null<CXXRecordDecl>(PrevDecl)); 13548 13549 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13550 StdBadAlloc = cast<CXXRecordDecl>(New); 13551 } else 13552 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13553 cast_or_null<RecordDecl>(PrevDecl)); 13554 } 13555 13556 // C++11 [dcl.type]p3: 13557 // A type-specifier-seq shall not define a class or enumeration [...]. 13558 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13559 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13560 << Context.getTagDeclType(New); 13561 Invalid = true; 13562 } 13563 13564 // Maybe add qualifier info. 13565 if (SS.isNotEmpty()) { 13566 if (SS.isSet()) { 13567 // If this is either a declaration or a definition, check the 13568 // nested-name-specifier against the current context. We don't do this 13569 // for explicit specializations, because they have similar checking 13570 // (with more specific diagnostics) in the call to 13571 // CheckMemberSpecialization, below. 13572 if (!isMemberSpecialization && 13573 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13574 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13575 Invalid = true; 13576 13577 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13578 if (TemplateParameterLists.size() > 0) { 13579 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13580 } 13581 } 13582 else 13583 Invalid = true; 13584 } 13585 13586 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13587 // Add alignment attributes if necessary; these attributes are checked when 13588 // the ASTContext lays out the structure. 13589 // 13590 // It is important for implementing the correct semantics that this 13591 // happen here (in act on tag decl). The #pragma pack stack is 13592 // maintained as a result of parser callbacks which can occur at 13593 // many points during the parsing of a struct declaration (because 13594 // the #pragma tokens are effectively skipped over during the 13595 // parsing of the struct). 13596 if (TUK == TUK_Definition) { 13597 AddAlignmentAttributesForRecord(RD); 13598 AddMsStructLayoutForRecord(RD); 13599 } 13600 } 13601 13602 if (ModulePrivateLoc.isValid()) { 13603 if (isMemberSpecialization) 13604 Diag(New->getLocation(), diag::err_module_private_specialization) 13605 << 2 13606 << FixItHint::CreateRemoval(ModulePrivateLoc); 13607 // __module_private__ does not apply to local classes. However, we only 13608 // diagnose this as an error when the declaration specifiers are 13609 // freestanding. Here, we just ignore the __module_private__. 13610 else if (!SearchDC->isFunctionOrMethod()) 13611 New->setModulePrivate(); 13612 } 13613 13614 // If this is a specialization of a member class (of a class template), 13615 // check the specialization. 13616 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13617 Invalid = true; 13618 13619 // If we're declaring or defining a tag in function prototype scope in C, 13620 // note that this type can only be used within the function and add it to 13621 // the list of decls to inject into the function definition scope. 13622 if ((Name || Kind == TTK_Enum) && 13623 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13624 if (getLangOpts().CPlusPlus) { 13625 // C++ [dcl.fct]p6: 13626 // Types shall not be defined in return or parameter types. 13627 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13628 Diag(Loc, diag::err_type_defined_in_param_type) 13629 << Name; 13630 Invalid = true; 13631 } 13632 } else if (!PrevDecl) { 13633 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13634 } 13635 } 13636 13637 if (Invalid) 13638 New->setInvalidDecl(); 13639 13640 // Set the lexical context. If the tag has a C++ scope specifier, the 13641 // lexical context will be different from the semantic context. 13642 New->setLexicalDeclContext(CurContext); 13643 13644 // Mark this as a friend decl if applicable. 13645 // In Microsoft mode, a friend declaration also acts as a forward 13646 // declaration so we always pass true to setObjectOfFriendDecl to make 13647 // the tag name visible. 13648 if (TUK == TUK_Friend) 13649 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13650 13651 // Set the access specifier. 13652 if (!Invalid && SearchDC->isRecord()) 13653 SetMemberAccessSpecifier(New, PrevDecl, AS); 13654 13655 if (TUK == TUK_Definition) 13656 New->startDefinition(); 13657 13658 if (Attr) 13659 ProcessDeclAttributeList(S, New, Attr); 13660 13661 // If this has an identifier, add it to the scope stack. 13662 if (TUK == TUK_Friend) { 13663 // We might be replacing an existing declaration in the lookup tables; 13664 // if so, borrow its access specifier. 13665 if (PrevDecl) 13666 New->setAccess(PrevDecl->getAccess()); 13667 13668 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13669 DC->makeDeclVisibleInContext(New); 13670 if (Name) // can be null along some error paths 13671 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13672 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13673 } else if (Name) { 13674 S = getNonFieldDeclScope(S); 13675 PushOnScopeChains(New, S, !IsForwardReference); 13676 if (IsForwardReference) 13677 SearchDC->makeDeclVisibleInContext(New); 13678 } else { 13679 CurContext->addDecl(New); 13680 } 13681 13682 // If this is the C FILE type, notify the AST context. 13683 if (IdentifierInfo *II = New->getIdentifier()) 13684 if (!New->isInvalidDecl() && 13685 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13686 II->isStr("FILE")) 13687 Context.setFILEDecl(New); 13688 13689 if (PrevDecl) 13690 mergeDeclAttributes(New, PrevDecl); 13691 13692 // If there's a #pragma GCC visibility in scope, set the visibility of this 13693 // record. 13694 AddPushedVisibilityAttribute(New); 13695 13696 OwnedDecl = true; 13697 // In C++, don't return an invalid declaration. We can't recover well from 13698 // the cases where we make the type anonymous. 13699 if (Invalid && getLangOpts().CPlusPlus) { 13700 if (New->isBeingDefined()) 13701 if (auto RD = dyn_cast<RecordDecl>(New)) 13702 RD->completeDefinition(); 13703 return nullptr; 13704 } else { 13705 return New; 13706 } 13707 } 13708 13709 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13710 AdjustDeclIfTemplate(TagD); 13711 TagDecl *Tag = cast<TagDecl>(TagD); 13712 13713 // Enter the tag context. 13714 PushDeclContext(S, Tag); 13715 13716 ActOnDocumentableDecl(TagD); 13717 13718 // If there's a #pragma GCC visibility in scope, set the visibility of this 13719 // record. 13720 AddPushedVisibilityAttribute(Tag); 13721 } 13722 13723 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13724 assert(isa<ObjCContainerDecl>(IDecl) && 13725 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13726 DeclContext *OCD = cast<DeclContext>(IDecl); 13727 assert(getContainingDC(OCD) == CurContext && 13728 "The next DeclContext should be lexically contained in the current one."); 13729 CurContext = OCD; 13730 return IDecl; 13731 } 13732 13733 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13734 SourceLocation FinalLoc, 13735 bool IsFinalSpelledSealed, 13736 SourceLocation LBraceLoc) { 13737 AdjustDeclIfTemplate(TagD); 13738 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13739 13740 FieldCollector->StartClass(); 13741 13742 if (!Record->getIdentifier()) 13743 return; 13744 13745 if (FinalLoc.isValid()) 13746 Record->addAttr(new (Context) 13747 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13748 13749 // C++ [class]p2: 13750 // [...] The class-name is also inserted into the scope of the 13751 // class itself; this is known as the injected-class-name. For 13752 // purposes of access checking, the injected-class-name is treated 13753 // as if it were a public member name. 13754 CXXRecordDecl *InjectedClassName 13755 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13756 Record->getLocStart(), Record->getLocation(), 13757 Record->getIdentifier(), 13758 /*PrevDecl=*/nullptr, 13759 /*DelayTypeCreation=*/true); 13760 Context.getTypeDeclType(InjectedClassName, Record); 13761 InjectedClassName->setImplicit(); 13762 InjectedClassName->setAccess(AS_public); 13763 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13764 InjectedClassName->setDescribedClassTemplate(Template); 13765 PushOnScopeChains(InjectedClassName, S); 13766 assert(InjectedClassName->isInjectedClassName() && 13767 "Broken injected-class-name"); 13768 } 13769 13770 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13771 SourceRange BraceRange) { 13772 AdjustDeclIfTemplate(TagD); 13773 TagDecl *Tag = cast<TagDecl>(TagD); 13774 Tag->setBraceRange(BraceRange); 13775 13776 // Make sure we "complete" the definition even it is invalid. 13777 if (Tag->isBeingDefined()) { 13778 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13779 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13780 RD->completeDefinition(); 13781 } 13782 13783 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 13784 FieldCollector->FinishClass(); 13785 if (Context.getLangOpts().Modules) 13786 RD->computeODRHash(); 13787 } 13788 13789 // Exit this scope of this tag's definition. 13790 PopDeclContext(); 13791 13792 if (getCurLexicalContext()->isObjCContainer() && 13793 Tag->getDeclContext()->isFileContext()) 13794 Tag->setTopLevelDeclInObjCContainer(); 13795 13796 // Notify the consumer that we've defined a tag. 13797 if (!Tag->isInvalidDecl()) 13798 Consumer.HandleTagDeclDefinition(Tag); 13799 } 13800 13801 void Sema::ActOnObjCContainerFinishDefinition() { 13802 // Exit this scope of this interface definition. 13803 PopDeclContext(); 13804 } 13805 13806 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13807 assert(DC == CurContext && "Mismatch of container contexts"); 13808 OriginalLexicalContext = DC; 13809 ActOnObjCContainerFinishDefinition(); 13810 } 13811 13812 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13813 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13814 OriginalLexicalContext = nullptr; 13815 } 13816 13817 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13818 AdjustDeclIfTemplate(TagD); 13819 TagDecl *Tag = cast<TagDecl>(TagD); 13820 Tag->setInvalidDecl(); 13821 13822 // Make sure we "complete" the definition even it is invalid. 13823 if (Tag->isBeingDefined()) { 13824 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13825 RD->completeDefinition(); 13826 } 13827 13828 // We're undoing ActOnTagStartDefinition here, not 13829 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13830 // the FieldCollector. 13831 13832 PopDeclContext(); 13833 } 13834 13835 // Note that FieldName may be null for anonymous bitfields. 13836 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13837 IdentifierInfo *FieldName, 13838 QualType FieldTy, bool IsMsStruct, 13839 Expr *BitWidth, bool *ZeroWidth) { 13840 // Default to true; that shouldn't confuse checks for emptiness 13841 if (ZeroWidth) 13842 *ZeroWidth = true; 13843 13844 // C99 6.7.2.1p4 - verify the field type. 13845 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13846 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13847 // Handle incomplete types with specific error. 13848 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13849 return ExprError(); 13850 if (FieldName) 13851 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13852 << FieldName << FieldTy << BitWidth->getSourceRange(); 13853 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13854 << FieldTy << BitWidth->getSourceRange(); 13855 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13856 UPPC_BitFieldWidth)) 13857 return ExprError(); 13858 13859 // If the bit-width is type- or value-dependent, don't try to check 13860 // it now. 13861 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13862 return BitWidth; 13863 13864 llvm::APSInt Value; 13865 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13866 if (ICE.isInvalid()) 13867 return ICE; 13868 BitWidth = ICE.get(); 13869 13870 if (Value != 0 && ZeroWidth) 13871 *ZeroWidth = false; 13872 13873 // Zero-width bitfield is ok for anonymous field. 13874 if (Value == 0 && FieldName) 13875 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13876 13877 if (Value.isSigned() && Value.isNegative()) { 13878 if (FieldName) 13879 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13880 << FieldName << Value.toString(10); 13881 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13882 << Value.toString(10); 13883 } 13884 13885 if (!FieldTy->isDependentType()) { 13886 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13887 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13888 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13889 13890 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13891 // ABI. 13892 bool CStdConstraintViolation = 13893 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13894 bool MSBitfieldViolation = 13895 Value.ugt(TypeStorageSize) && 13896 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13897 if (CStdConstraintViolation || MSBitfieldViolation) { 13898 unsigned DiagWidth = 13899 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13900 if (FieldName) 13901 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13902 << FieldName << (unsigned)Value.getZExtValue() 13903 << !CStdConstraintViolation << DiagWidth; 13904 13905 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13906 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13907 << DiagWidth; 13908 } 13909 13910 // Warn on types where the user might conceivably expect to get all 13911 // specified bits as value bits: that's all integral types other than 13912 // 'bool'. 13913 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13914 if (FieldName) 13915 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13916 << FieldName << (unsigned)Value.getZExtValue() 13917 << (unsigned)TypeWidth; 13918 else 13919 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13920 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13921 } 13922 } 13923 13924 return BitWidth; 13925 } 13926 13927 /// ActOnField - Each field of a C struct/union is passed into this in order 13928 /// to create a FieldDecl object for it. 13929 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13930 Declarator &D, Expr *BitfieldWidth) { 13931 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13932 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13933 /*InitStyle=*/ICIS_NoInit, AS_public); 13934 return Res; 13935 } 13936 13937 /// HandleField - Analyze a field of a C struct or a C++ data member. 13938 /// 13939 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13940 SourceLocation DeclStart, 13941 Declarator &D, Expr *BitWidth, 13942 InClassInitStyle InitStyle, 13943 AccessSpecifier AS) { 13944 if (D.isDecompositionDeclarator()) { 13945 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13946 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13947 << Decomp.getSourceRange(); 13948 return nullptr; 13949 } 13950 13951 IdentifierInfo *II = D.getIdentifier(); 13952 SourceLocation Loc = DeclStart; 13953 if (II) Loc = D.getIdentifierLoc(); 13954 13955 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13956 QualType T = TInfo->getType(); 13957 if (getLangOpts().CPlusPlus) { 13958 CheckExtraCXXDefaultArguments(D); 13959 13960 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13961 UPPC_DataMemberType)) { 13962 D.setInvalidType(); 13963 T = Context.IntTy; 13964 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13965 } 13966 } 13967 13968 // TR 18037 does not allow fields to be declared with address spaces. 13969 if (T.getQualifiers().hasAddressSpace()) { 13970 Diag(Loc, diag::err_field_with_address_space); 13971 D.setInvalidType(); 13972 } 13973 13974 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13975 // used as structure or union field: image, sampler, event or block types. 13976 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13977 T->isSamplerT() || T->isBlockPointerType())) { 13978 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13979 D.setInvalidType(); 13980 } 13981 13982 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13983 13984 if (D.getDeclSpec().isInlineSpecified()) 13985 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13986 << getLangOpts().CPlusPlus1z; 13987 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13988 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13989 diag::err_invalid_thread) 13990 << DeclSpec::getSpecifierName(TSCS); 13991 13992 // Check to see if this name was declared as a member previously 13993 NamedDecl *PrevDecl = nullptr; 13994 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13995 LookupName(Previous, S); 13996 switch (Previous.getResultKind()) { 13997 case LookupResult::Found: 13998 case LookupResult::FoundUnresolvedValue: 13999 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14000 break; 14001 14002 case LookupResult::FoundOverloaded: 14003 PrevDecl = Previous.getRepresentativeDecl(); 14004 break; 14005 14006 case LookupResult::NotFound: 14007 case LookupResult::NotFoundInCurrentInstantiation: 14008 case LookupResult::Ambiguous: 14009 break; 14010 } 14011 Previous.suppressDiagnostics(); 14012 14013 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14014 // Maybe we will complain about the shadowed template parameter. 14015 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14016 // Just pretend that we didn't see the previous declaration. 14017 PrevDecl = nullptr; 14018 } 14019 14020 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14021 PrevDecl = nullptr; 14022 14023 bool Mutable 14024 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14025 SourceLocation TSSL = D.getLocStart(); 14026 FieldDecl *NewFD 14027 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14028 TSSL, AS, PrevDecl, &D); 14029 14030 if (NewFD->isInvalidDecl()) 14031 Record->setInvalidDecl(); 14032 14033 if (D.getDeclSpec().isModulePrivateSpecified()) 14034 NewFD->setModulePrivate(); 14035 14036 if (NewFD->isInvalidDecl() && PrevDecl) { 14037 // Don't introduce NewFD into scope; there's already something 14038 // with the same name in the same scope. 14039 } else if (II) { 14040 PushOnScopeChains(NewFD, S); 14041 } else 14042 Record->addDecl(NewFD); 14043 14044 return NewFD; 14045 } 14046 14047 /// \brief Build a new FieldDecl and check its well-formedness. 14048 /// 14049 /// This routine builds a new FieldDecl given the fields name, type, 14050 /// record, etc. \p PrevDecl should refer to any previous declaration 14051 /// with the same name and in the same scope as the field to be 14052 /// created. 14053 /// 14054 /// \returns a new FieldDecl. 14055 /// 14056 /// \todo The Declarator argument is a hack. It will be removed once 14057 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14058 TypeSourceInfo *TInfo, 14059 RecordDecl *Record, SourceLocation Loc, 14060 bool Mutable, Expr *BitWidth, 14061 InClassInitStyle InitStyle, 14062 SourceLocation TSSL, 14063 AccessSpecifier AS, NamedDecl *PrevDecl, 14064 Declarator *D) { 14065 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14066 bool InvalidDecl = false; 14067 if (D) InvalidDecl = D->isInvalidType(); 14068 14069 // If we receive a broken type, recover by assuming 'int' and 14070 // marking this declaration as invalid. 14071 if (T.isNull()) { 14072 InvalidDecl = true; 14073 T = Context.IntTy; 14074 } 14075 14076 QualType EltTy = Context.getBaseElementType(T); 14077 if (!EltTy->isDependentType()) { 14078 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14079 // Fields of incomplete type force their record to be invalid. 14080 Record->setInvalidDecl(); 14081 InvalidDecl = true; 14082 } else { 14083 NamedDecl *Def; 14084 EltTy->isIncompleteType(&Def); 14085 if (Def && Def->isInvalidDecl()) { 14086 Record->setInvalidDecl(); 14087 InvalidDecl = true; 14088 } 14089 } 14090 } 14091 14092 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14093 if (BitWidth && getLangOpts().OpenCL) { 14094 Diag(Loc, diag::err_opencl_bitfields); 14095 InvalidDecl = true; 14096 } 14097 14098 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14099 // than a variably modified type. 14100 if (!InvalidDecl && T->isVariablyModifiedType()) { 14101 bool SizeIsNegative; 14102 llvm::APSInt Oversized; 14103 14104 TypeSourceInfo *FixedTInfo = 14105 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14106 SizeIsNegative, 14107 Oversized); 14108 if (FixedTInfo) { 14109 Diag(Loc, diag::warn_illegal_constant_array_size); 14110 TInfo = FixedTInfo; 14111 T = FixedTInfo->getType(); 14112 } else { 14113 if (SizeIsNegative) 14114 Diag(Loc, diag::err_typecheck_negative_array_size); 14115 else if (Oversized.getBoolValue()) 14116 Diag(Loc, diag::err_array_too_large) 14117 << Oversized.toString(10); 14118 else 14119 Diag(Loc, diag::err_typecheck_field_variable_size); 14120 InvalidDecl = true; 14121 } 14122 } 14123 14124 // Fields can not have abstract class types 14125 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14126 diag::err_abstract_type_in_decl, 14127 AbstractFieldType)) 14128 InvalidDecl = true; 14129 14130 bool ZeroWidth = false; 14131 if (InvalidDecl) 14132 BitWidth = nullptr; 14133 // If this is declared as a bit-field, check the bit-field. 14134 if (BitWidth) { 14135 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14136 &ZeroWidth).get(); 14137 if (!BitWidth) { 14138 InvalidDecl = true; 14139 BitWidth = nullptr; 14140 ZeroWidth = false; 14141 } 14142 } 14143 14144 // Check that 'mutable' is consistent with the type of the declaration. 14145 if (!InvalidDecl && Mutable) { 14146 unsigned DiagID = 0; 14147 if (T->isReferenceType()) 14148 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14149 : diag::err_mutable_reference; 14150 else if (T.isConstQualified()) 14151 DiagID = diag::err_mutable_const; 14152 14153 if (DiagID) { 14154 SourceLocation ErrLoc = Loc; 14155 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14156 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14157 Diag(ErrLoc, DiagID); 14158 if (DiagID != diag::ext_mutable_reference) { 14159 Mutable = false; 14160 InvalidDecl = true; 14161 } 14162 } 14163 } 14164 14165 // C++11 [class.union]p8 (DR1460): 14166 // At most one variant member of a union may have a 14167 // brace-or-equal-initializer. 14168 if (InitStyle != ICIS_NoInit) 14169 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14170 14171 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14172 BitWidth, Mutable, InitStyle); 14173 if (InvalidDecl) 14174 NewFD->setInvalidDecl(); 14175 14176 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14177 Diag(Loc, diag::err_duplicate_member) << II; 14178 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14179 NewFD->setInvalidDecl(); 14180 } 14181 14182 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14183 if (Record->isUnion()) { 14184 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14185 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14186 if (RDecl->getDefinition()) { 14187 // C++ [class.union]p1: An object of a class with a non-trivial 14188 // constructor, a non-trivial copy constructor, a non-trivial 14189 // destructor, or a non-trivial copy assignment operator 14190 // cannot be a member of a union, nor can an array of such 14191 // objects. 14192 if (CheckNontrivialField(NewFD)) 14193 NewFD->setInvalidDecl(); 14194 } 14195 } 14196 14197 // C++ [class.union]p1: If a union contains a member of reference type, 14198 // the program is ill-formed, except when compiling with MSVC extensions 14199 // enabled. 14200 if (EltTy->isReferenceType()) { 14201 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14202 diag::ext_union_member_of_reference_type : 14203 diag::err_union_member_of_reference_type) 14204 << NewFD->getDeclName() << EltTy; 14205 if (!getLangOpts().MicrosoftExt) 14206 NewFD->setInvalidDecl(); 14207 } 14208 } 14209 } 14210 14211 // FIXME: We need to pass in the attributes given an AST 14212 // representation, not a parser representation. 14213 if (D) { 14214 // FIXME: The current scope is almost... but not entirely... correct here. 14215 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14216 14217 if (NewFD->hasAttrs()) 14218 CheckAlignasUnderalignment(NewFD); 14219 } 14220 14221 // In auto-retain/release, infer strong retension for fields of 14222 // retainable type. 14223 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14224 NewFD->setInvalidDecl(); 14225 14226 if (T.isObjCGCWeak()) 14227 Diag(Loc, diag::warn_attribute_weak_on_field); 14228 14229 NewFD->setAccess(AS); 14230 return NewFD; 14231 } 14232 14233 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14234 assert(FD); 14235 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14236 14237 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14238 return false; 14239 14240 QualType EltTy = Context.getBaseElementType(FD->getType()); 14241 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14242 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14243 if (RDecl->getDefinition()) { 14244 // We check for copy constructors before constructors 14245 // because otherwise we'll never get complaints about 14246 // copy constructors. 14247 14248 CXXSpecialMember member = CXXInvalid; 14249 // We're required to check for any non-trivial constructors. Since the 14250 // implicit default constructor is suppressed if there are any 14251 // user-declared constructors, we just need to check that there is a 14252 // trivial default constructor and a trivial copy constructor. (We don't 14253 // worry about move constructors here, since this is a C++98 check.) 14254 if (RDecl->hasNonTrivialCopyConstructor()) 14255 member = CXXCopyConstructor; 14256 else if (!RDecl->hasTrivialDefaultConstructor()) 14257 member = CXXDefaultConstructor; 14258 else if (RDecl->hasNonTrivialCopyAssignment()) 14259 member = CXXCopyAssignment; 14260 else if (RDecl->hasNonTrivialDestructor()) 14261 member = CXXDestructor; 14262 14263 if (member != CXXInvalid) { 14264 if (!getLangOpts().CPlusPlus11 && 14265 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14266 // Objective-C++ ARC: it is an error to have a non-trivial field of 14267 // a union. However, system headers in Objective-C programs 14268 // occasionally have Objective-C lifetime objects within unions, 14269 // and rather than cause the program to fail, we make those 14270 // members unavailable. 14271 SourceLocation Loc = FD->getLocation(); 14272 if (getSourceManager().isInSystemHeader(Loc)) { 14273 if (!FD->hasAttr<UnavailableAttr>()) 14274 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14275 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14276 return false; 14277 } 14278 } 14279 14280 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14281 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14282 diag::err_illegal_union_or_anon_struct_member) 14283 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14284 DiagnoseNontrivial(RDecl, member); 14285 return !getLangOpts().CPlusPlus11; 14286 } 14287 } 14288 } 14289 14290 return false; 14291 } 14292 14293 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14294 /// AST enum value. 14295 static ObjCIvarDecl::AccessControl 14296 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14297 switch (ivarVisibility) { 14298 default: llvm_unreachable("Unknown visitibility kind"); 14299 case tok::objc_private: return ObjCIvarDecl::Private; 14300 case tok::objc_public: return ObjCIvarDecl::Public; 14301 case tok::objc_protected: return ObjCIvarDecl::Protected; 14302 case tok::objc_package: return ObjCIvarDecl::Package; 14303 } 14304 } 14305 14306 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14307 /// in order to create an IvarDecl object for it. 14308 Decl *Sema::ActOnIvar(Scope *S, 14309 SourceLocation DeclStart, 14310 Declarator &D, Expr *BitfieldWidth, 14311 tok::ObjCKeywordKind Visibility) { 14312 14313 IdentifierInfo *II = D.getIdentifier(); 14314 Expr *BitWidth = (Expr*)BitfieldWidth; 14315 SourceLocation Loc = DeclStart; 14316 if (II) Loc = D.getIdentifierLoc(); 14317 14318 // FIXME: Unnamed fields can be handled in various different ways, for 14319 // example, unnamed unions inject all members into the struct namespace! 14320 14321 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14322 QualType T = TInfo->getType(); 14323 14324 if (BitWidth) { 14325 // 6.7.2.1p3, 6.7.2.1p4 14326 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14327 if (!BitWidth) 14328 D.setInvalidType(); 14329 } else { 14330 // Not a bitfield. 14331 14332 // validate II. 14333 14334 } 14335 if (T->isReferenceType()) { 14336 Diag(Loc, diag::err_ivar_reference_type); 14337 D.setInvalidType(); 14338 } 14339 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14340 // than a variably modified type. 14341 else if (T->isVariablyModifiedType()) { 14342 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14343 D.setInvalidType(); 14344 } 14345 14346 // Get the visibility (access control) for this ivar. 14347 ObjCIvarDecl::AccessControl ac = 14348 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14349 : ObjCIvarDecl::None; 14350 // Must set ivar's DeclContext to its enclosing interface. 14351 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14352 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14353 return nullptr; 14354 ObjCContainerDecl *EnclosingContext; 14355 if (ObjCImplementationDecl *IMPDecl = 14356 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14357 if (LangOpts.ObjCRuntime.isFragile()) { 14358 // Case of ivar declared in an implementation. Context is that of its class. 14359 EnclosingContext = IMPDecl->getClassInterface(); 14360 assert(EnclosingContext && "Implementation has no class interface!"); 14361 } 14362 else 14363 EnclosingContext = EnclosingDecl; 14364 } else { 14365 if (ObjCCategoryDecl *CDecl = 14366 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14367 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14368 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14369 return nullptr; 14370 } 14371 } 14372 EnclosingContext = EnclosingDecl; 14373 } 14374 14375 // Construct the decl. 14376 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14377 DeclStart, Loc, II, T, 14378 TInfo, ac, (Expr *)BitfieldWidth); 14379 14380 if (II) { 14381 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14382 ForRedeclaration); 14383 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14384 && !isa<TagDecl>(PrevDecl)) { 14385 Diag(Loc, diag::err_duplicate_member) << II; 14386 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14387 NewID->setInvalidDecl(); 14388 } 14389 } 14390 14391 // Process attributes attached to the ivar. 14392 ProcessDeclAttributes(S, NewID, D); 14393 14394 if (D.isInvalidType()) 14395 NewID->setInvalidDecl(); 14396 14397 // In ARC, infer 'retaining' for ivars of retainable type. 14398 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14399 NewID->setInvalidDecl(); 14400 14401 if (D.getDeclSpec().isModulePrivateSpecified()) 14402 NewID->setModulePrivate(); 14403 14404 if (II) { 14405 // FIXME: When interfaces are DeclContexts, we'll need to add 14406 // these to the interface. 14407 S->AddDecl(NewID); 14408 IdResolver.AddDecl(NewID); 14409 } 14410 14411 if (LangOpts.ObjCRuntime.isNonFragile() && 14412 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14413 Diag(Loc, diag::warn_ivars_in_interface); 14414 14415 return NewID; 14416 } 14417 14418 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14419 /// class and class extensions. For every class \@interface and class 14420 /// extension \@interface, if the last ivar is a bitfield of any type, 14421 /// then add an implicit `char :0` ivar to the end of that interface. 14422 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14423 SmallVectorImpl<Decl *> &AllIvarDecls) { 14424 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14425 return; 14426 14427 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14428 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14429 14430 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14431 return; 14432 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14433 if (!ID) { 14434 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14435 if (!CD->IsClassExtension()) 14436 return; 14437 } 14438 // No need to add this to end of @implementation. 14439 else 14440 return; 14441 } 14442 // All conditions are met. Add a new bitfield to the tail end of ivars. 14443 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14444 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14445 14446 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14447 DeclLoc, DeclLoc, nullptr, 14448 Context.CharTy, 14449 Context.getTrivialTypeSourceInfo(Context.CharTy, 14450 DeclLoc), 14451 ObjCIvarDecl::Private, BW, 14452 true); 14453 AllIvarDecls.push_back(Ivar); 14454 } 14455 14456 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14457 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14458 SourceLocation RBrac, AttributeList *Attr) { 14459 assert(EnclosingDecl && "missing record or interface decl"); 14460 14461 // If this is an Objective-C @implementation or category and we have 14462 // new fields here we should reset the layout of the interface since 14463 // it will now change. 14464 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14465 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14466 switch (DC->getKind()) { 14467 default: break; 14468 case Decl::ObjCCategory: 14469 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14470 break; 14471 case Decl::ObjCImplementation: 14472 Context. 14473 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14474 break; 14475 } 14476 } 14477 14478 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14479 14480 // Start counting up the number of named members; make sure to include 14481 // members of anonymous structs and unions in the total. 14482 unsigned NumNamedMembers = 0; 14483 if (Record) { 14484 for (const auto *I : Record->decls()) { 14485 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14486 if (IFD->getDeclName()) 14487 ++NumNamedMembers; 14488 } 14489 } 14490 14491 // Verify that all the fields are okay. 14492 SmallVector<FieldDecl*, 32> RecFields; 14493 14494 bool ARCErrReported = false; 14495 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14496 i != end; ++i) { 14497 FieldDecl *FD = cast<FieldDecl>(*i); 14498 14499 // Get the type for the field. 14500 const Type *FDTy = FD->getType().getTypePtr(); 14501 14502 if (!FD->isAnonymousStructOrUnion()) { 14503 // Remember all fields written by the user. 14504 RecFields.push_back(FD); 14505 } 14506 14507 // If the field is already invalid for some reason, don't emit more 14508 // diagnostics about it. 14509 if (FD->isInvalidDecl()) { 14510 EnclosingDecl->setInvalidDecl(); 14511 continue; 14512 } 14513 14514 // C99 6.7.2.1p2: 14515 // A structure or union shall not contain a member with 14516 // incomplete or function type (hence, a structure shall not 14517 // contain an instance of itself, but may contain a pointer to 14518 // an instance of itself), except that the last member of a 14519 // structure with more than one named member may have incomplete 14520 // array type; such a structure (and any union containing, 14521 // possibly recursively, a member that is such a structure) 14522 // shall not be a member of a structure or an element of an 14523 // array. 14524 if (FDTy->isFunctionType()) { 14525 // Field declared as a function. 14526 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14527 << FD->getDeclName(); 14528 FD->setInvalidDecl(); 14529 EnclosingDecl->setInvalidDecl(); 14530 continue; 14531 } else if (FDTy->isIncompleteArrayType() && Record && 14532 ((i + 1 == Fields.end() && !Record->isUnion()) || 14533 ((getLangOpts().MicrosoftExt || 14534 getLangOpts().CPlusPlus) && 14535 (i + 1 == Fields.end() || Record->isUnion())))) { 14536 // Flexible array member. 14537 // Microsoft and g++ is more permissive regarding flexible array. 14538 // It will accept flexible array in union and also 14539 // as the sole element of a struct/class. 14540 unsigned DiagID = 0; 14541 if (Record->isUnion()) 14542 DiagID = getLangOpts().MicrosoftExt 14543 ? diag::ext_flexible_array_union_ms 14544 : getLangOpts().CPlusPlus 14545 ? diag::ext_flexible_array_union_gnu 14546 : diag::err_flexible_array_union; 14547 else if (NumNamedMembers < 1) 14548 DiagID = getLangOpts().MicrosoftExt 14549 ? diag::ext_flexible_array_empty_aggregate_ms 14550 : getLangOpts().CPlusPlus 14551 ? diag::ext_flexible_array_empty_aggregate_gnu 14552 : diag::err_flexible_array_empty_aggregate; 14553 14554 if (DiagID) 14555 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14556 << Record->getTagKind(); 14557 // While the layout of types that contain virtual bases is not specified 14558 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14559 // virtual bases after the derived members. This would make a flexible 14560 // array member declared at the end of an object not adjacent to the end 14561 // of the type. 14562 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14563 if (RD->getNumVBases() != 0) 14564 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14565 << FD->getDeclName() << Record->getTagKind(); 14566 if (!getLangOpts().C99) 14567 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14568 << FD->getDeclName() << Record->getTagKind(); 14569 14570 // If the element type has a non-trivial destructor, we would not 14571 // implicitly destroy the elements, so disallow it for now. 14572 // 14573 // FIXME: GCC allows this. We should probably either implicitly delete 14574 // the destructor of the containing class, or just allow this. 14575 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14576 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14577 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14578 << FD->getDeclName() << FD->getType(); 14579 FD->setInvalidDecl(); 14580 EnclosingDecl->setInvalidDecl(); 14581 continue; 14582 } 14583 // Okay, we have a legal flexible array member at the end of the struct. 14584 Record->setHasFlexibleArrayMember(true); 14585 } else if (!FDTy->isDependentType() && 14586 RequireCompleteType(FD->getLocation(), FD->getType(), 14587 diag::err_field_incomplete)) { 14588 // Incomplete type 14589 FD->setInvalidDecl(); 14590 EnclosingDecl->setInvalidDecl(); 14591 continue; 14592 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14593 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14594 // A type which contains a flexible array member is considered to be a 14595 // flexible array member. 14596 Record->setHasFlexibleArrayMember(true); 14597 if (!Record->isUnion()) { 14598 // If this is a struct/class and this is not the last element, reject 14599 // it. Note that GCC supports variable sized arrays in the middle of 14600 // structures. 14601 if (i + 1 != Fields.end()) 14602 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14603 << FD->getDeclName() << FD->getType(); 14604 else { 14605 // We support flexible arrays at the end of structs in 14606 // other structs as an extension. 14607 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14608 << FD->getDeclName(); 14609 } 14610 } 14611 } 14612 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14613 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14614 diag::err_abstract_type_in_decl, 14615 AbstractIvarType)) { 14616 // Ivars can not have abstract class types 14617 FD->setInvalidDecl(); 14618 } 14619 if (Record && FDTTy->getDecl()->hasObjectMember()) 14620 Record->setHasObjectMember(true); 14621 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14622 Record->setHasVolatileMember(true); 14623 } else if (FDTy->isObjCObjectType()) { 14624 /// A field cannot be an Objective-c object 14625 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14626 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14627 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14628 FD->setType(T); 14629 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14630 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14631 // It's an error in ARC if a field has lifetime. 14632 // We don't want to report this in a system header, though, 14633 // so we just make the field unavailable. 14634 // FIXME: that's really not sufficient; we need to make the type 14635 // itself invalid to, say, initialize or copy. 14636 QualType T = FD->getType(); 14637 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14638 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14639 SourceLocation loc = FD->getLocation(); 14640 if (getSourceManager().isInSystemHeader(loc)) { 14641 if (!FD->hasAttr<UnavailableAttr>()) { 14642 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14643 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14644 } 14645 } else { 14646 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14647 << T->isBlockPointerType() << Record->getTagKind(); 14648 } 14649 ARCErrReported = true; 14650 } 14651 } else if (getLangOpts().ObjC1 && 14652 getLangOpts().getGC() != LangOptions::NonGC && 14653 Record && !Record->hasObjectMember()) { 14654 if (FD->getType()->isObjCObjectPointerType() || 14655 FD->getType().isObjCGCStrong()) 14656 Record->setHasObjectMember(true); 14657 else if (Context.getAsArrayType(FD->getType())) { 14658 QualType BaseType = Context.getBaseElementType(FD->getType()); 14659 if (BaseType->isRecordType() && 14660 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14661 Record->setHasObjectMember(true); 14662 else if (BaseType->isObjCObjectPointerType() || 14663 BaseType.isObjCGCStrong()) 14664 Record->setHasObjectMember(true); 14665 } 14666 } 14667 if (Record && FD->getType().isVolatileQualified()) 14668 Record->setHasVolatileMember(true); 14669 // Keep track of the number of named members. 14670 if (FD->getIdentifier()) 14671 ++NumNamedMembers; 14672 } 14673 14674 // Okay, we successfully defined 'Record'. 14675 if (Record) { 14676 bool Completed = false; 14677 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14678 if (!CXXRecord->isInvalidDecl()) { 14679 // Set access bits correctly on the directly-declared conversions. 14680 for (CXXRecordDecl::conversion_iterator 14681 I = CXXRecord->conversion_begin(), 14682 E = CXXRecord->conversion_end(); I != E; ++I) 14683 I.setAccess((*I)->getAccess()); 14684 } 14685 14686 if (!CXXRecord->isDependentType()) { 14687 if (CXXRecord->hasUserDeclaredDestructor()) { 14688 // Adjust user-defined destructor exception spec. 14689 if (getLangOpts().CPlusPlus11) 14690 AdjustDestructorExceptionSpec(CXXRecord, 14691 CXXRecord->getDestructor()); 14692 } 14693 14694 if (!CXXRecord->isInvalidDecl()) { 14695 // Add any implicitly-declared members to this class. 14696 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14697 14698 // If we have virtual base classes, we may end up finding multiple 14699 // final overriders for a given virtual function. Check for this 14700 // problem now. 14701 if (CXXRecord->getNumVBases()) { 14702 CXXFinalOverriderMap FinalOverriders; 14703 CXXRecord->getFinalOverriders(FinalOverriders); 14704 14705 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14706 MEnd = FinalOverriders.end(); 14707 M != MEnd; ++M) { 14708 for (OverridingMethods::iterator SO = M->second.begin(), 14709 SOEnd = M->second.end(); 14710 SO != SOEnd; ++SO) { 14711 assert(SO->second.size() > 0 && 14712 "Virtual function without overridding functions?"); 14713 if (SO->second.size() == 1) 14714 continue; 14715 14716 // C++ [class.virtual]p2: 14717 // In a derived class, if a virtual member function of a base 14718 // class subobject has more than one final overrider the 14719 // program is ill-formed. 14720 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14721 << (const NamedDecl *)M->first << Record; 14722 Diag(M->first->getLocation(), 14723 diag::note_overridden_virtual_function); 14724 for (OverridingMethods::overriding_iterator 14725 OM = SO->second.begin(), 14726 OMEnd = SO->second.end(); 14727 OM != OMEnd; ++OM) 14728 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14729 << (const NamedDecl *)M->first << OM->Method->getParent(); 14730 14731 Record->setInvalidDecl(); 14732 } 14733 } 14734 CXXRecord->completeDefinition(&FinalOverriders); 14735 Completed = true; 14736 } 14737 } 14738 } 14739 } 14740 14741 if (!Completed) 14742 Record->completeDefinition(); 14743 14744 // We may have deferred checking for a deleted destructor. Check now. 14745 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14746 auto *Dtor = CXXRecord->getDestructor(); 14747 if (Dtor && Dtor->isImplicit() && 14748 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14749 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14750 } 14751 14752 if (Record->hasAttrs()) { 14753 CheckAlignasUnderalignment(Record); 14754 14755 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14756 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14757 IA->getRange(), IA->getBestCase(), 14758 IA->getSemanticSpelling()); 14759 } 14760 14761 // Check if the structure/union declaration is a type that can have zero 14762 // size in C. For C this is a language extension, for C++ it may cause 14763 // compatibility problems. 14764 bool CheckForZeroSize; 14765 if (!getLangOpts().CPlusPlus) { 14766 CheckForZeroSize = true; 14767 } else { 14768 // For C++ filter out types that cannot be referenced in C code. 14769 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14770 CheckForZeroSize = 14771 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14772 !CXXRecord->isDependentType() && 14773 CXXRecord->isCLike(); 14774 } 14775 if (CheckForZeroSize) { 14776 bool ZeroSize = true; 14777 bool IsEmpty = true; 14778 unsigned NonBitFields = 0; 14779 for (RecordDecl::field_iterator I = Record->field_begin(), 14780 E = Record->field_end(); 14781 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14782 IsEmpty = false; 14783 if (I->isUnnamedBitfield()) { 14784 if (I->getBitWidthValue(Context) > 0) 14785 ZeroSize = false; 14786 } else { 14787 ++NonBitFields; 14788 QualType FieldType = I->getType(); 14789 if (FieldType->isIncompleteType() || 14790 !Context.getTypeSizeInChars(FieldType).isZero()) 14791 ZeroSize = false; 14792 } 14793 } 14794 14795 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14796 // allowed in C++, but warn if its declaration is inside 14797 // extern "C" block. 14798 if (ZeroSize) { 14799 Diag(RecLoc, getLangOpts().CPlusPlus ? 14800 diag::warn_zero_size_struct_union_in_extern_c : 14801 diag::warn_zero_size_struct_union_compat) 14802 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14803 } 14804 14805 // Structs without named members are extension in C (C99 6.7.2.1p7), 14806 // but are accepted by GCC. 14807 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14808 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14809 diag::ext_no_named_members_in_struct_union) 14810 << Record->isUnion(); 14811 } 14812 } 14813 } else { 14814 ObjCIvarDecl **ClsFields = 14815 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14816 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14817 ID->setEndOfDefinitionLoc(RBrac); 14818 // Add ivar's to class's DeclContext. 14819 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14820 ClsFields[i]->setLexicalDeclContext(ID); 14821 ID->addDecl(ClsFields[i]); 14822 } 14823 // Must enforce the rule that ivars in the base classes may not be 14824 // duplicates. 14825 if (ID->getSuperClass()) 14826 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14827 } else if (ObjCImplementationDecl *IMPDecl = 14828 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14829 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14830 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14831 // Ivar declared in @implementation never belongs to the implementation. 14832 // Only it is in implementation's lexical context. 14833 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14834 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14835 IMPDecl->setIvarLBraceLoc(LBrac); 14836 IMPDecl->setIvarRBraceLoc(RBrac); 14837 } else if (ObjCCategoryDecl *CDecl = 14838 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14839 // case of ivars in class extension; all other cases have been 14840 // reported as errors elsewhere. 14841 // FIXME. Class extension does not have a LocEnd field. 14842 // CDecl->setLocEnd(RBrac); 14843 // Add ivar's to class extension's DeclContext. 14844 // Diagnose redeclaration of private ivars. 14845 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14846 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14847 if (IDecl) { 14848 if (const ObjCIvarDecl *ClsIvar = 14849 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14850 Diag(ClsFields[i]->getLocation(), 14851 diag::err_duplicate_ivar_declaration); 14852 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14853 continue; 14854 } 14855 for (const auto *Ext : IDecl->known_extensions()) { 14856 if (const ObjCIvarDecl *ClsExtIvar 14857 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14858 Diag(ClsFields[i]->getLocation(), 14859 diag::err_duplicate_ivar_declaration); 14860 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14861 continue; 14862 } 14863 } 14864 } 14865 ClsFields[i]->setLexicalDeclContext(CDecl); 14866 CDecl->addDecl(ClsFields[i]); 14867 } 14868 CDecl->setIvarLBraceLoc(LBrac); 14869 CDecl->setIvarRBraceLoc(RBrac); 14870 } 14871 } 14872 14873 if (Attr) 14874 ProcessDeclAttributeList(S, Record, Attr); 14875 } 14876 14877 /// \brief Determine whether the given integral value is representable within 14878 /// the given type T. 14879 static bool isRepresentableIntegerValue(ASTContext &Context, 14880 llvm::APSInt &Value, 14881 QualType T) { 14882 assert(T->isIntegralType(Context) && "Integral type required!"); 14883 unsigned BitWidth = Context.getIntWidth(T); 14884 14885 if (Value.isUnsigned() || Value.isNonNegative()) { 14886 if (T->isSignedIntegerOrEnumerationType()) 14887 --BitWidth; 14888 return Value.getActiveBits() <= BitWidth; 14889 } 14890 return Value.getMinSignedBits() <= BitWidth; 14891 } 14892 14893 // \brief Given an integral type, return the next larger integral type 14894 // (or a NULL type of no such type exists). 14895 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14896 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14897 // enum checking below. 14898 assert(T->isIntegralType(Context) && "Integral type required!"); 14899 const unsigned NumTypes = 4; 14900 QualType SignedIntegralTypes[NumTypes] = { 14901 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14902 }; 14903 QualType UnsignedIntegralTypes[NumTypes] = { 14904 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14905 Context.UnsignedLongLongTy 14906 }; 14907 14908 unsigned BitWidth = Context.getTypeSize(T); 14909 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14910 : UnsignedIntegralTypes; 14911 for (unsigned I = 0; I != NumTypes; ++I) 14912 if (Context.getTypeSize(Types[I]) > BitWidth) 14913 return Types[I]; 14914 14915 return QualType(); 14916 } 14917 14918 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14919 EnumConstantDecl *LastEnumConst, 14920 SourceLocation IdLoc, 14921 IdentifierInfo *Id, 14922 Expr *Val) { 14923 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14924 llvm::APSInt EnumVal(IntWidth); 14925 QualType EltTy; 14926 14927 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14928 Val = nullptr; 14929 14930 if (Val) 14931 Val = DefaultLvalueConversion(Val).get(); 14932 14933 if (Val) { 14934 if (Enum->isDependentType() || Val->isTypeDependent()) 14935 EltTy = Context.DependentTy; 14936 else { 14937 SourceLocation ExpLoc; 14938 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14939 !getLangOpts().MSVCCompat) { 14940 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14941 // constant-expression in the enumerator-definition shall be a converted 14942 // constant expression of the underlying type. 14943 EltTy = Enum->getIntegerType(); 14944 ExprResult Converted = 14945 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14946 CCEK_Enumerator); 14947 if (Converted.isInvalid()) 14948 Val = nullptr; 14949 else 14950 Val = Converted.get(); 14951 } else if (!Val->isValueDependent() && 14952 !(Val = VerifyIntegerConstantExpression(Val, 14953 &EnumVal).get())) { 14954 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14955 } else { 14956 if (Enum->isFixed()) { 14957 EltTy = Enum->getIntegerType(); 14958 14959 // In Obj-C and Microsoft mode, require the enumeration value to be 14960 // representable in the underlying type of the enumeration. In C++11, 14961 // we perform a non-narrowing conversion as part of converted constant 14962 // expression checking. 14963 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14964 if (getLangOpts().MSVCCompat) { 14965 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14966 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14967 } else 14968 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14969 } else 14970 Val = ImpCastExprToType(Val, EltTy, 14971 EltTy->isBooleanType() ? 14972 CK_IntegralToBoolean : CK_IntegralCast) 14973 .get(); 14974 } else if (getLangOpts().CPlusPlus) { 14975 // C++11 [dcl.enum]p5: 14976 // If the underlying type is not fixed, the type of each enumerator 14977 // is the type of its initializing value: 14978 // - If an initializer is specified for an enumerator, the 14979 // initializing value has the same type as the expression. 14980 EltTy = Val->getType(); 14981 } else { 14982 // C99 6.7.2.2p2: 14983 // The expression that defines the value of an enumeration constant 14984 // shall be an integer constant expression that has a value 14985 // representable as an int. 14986 14987 // Complain if the value is not representable in an int. 14988 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14989 Diag(IdLoc, diag::ext_enum_value_not_int) 14990 << EnumVal.toString(10) << Val->getSourceRange() 14991 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14992 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14993 // Force the type of the expression to 'int'. 14994 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14995 } 14996 EltTy = Val->getType(); 14997 } 14998 } 14999 } 15000 } 15001 15002 if (!Val) { 15003 if (Enum->isDependentType()) 15004 EltTy = Context.DependentTy; 15005 else if (!LastEnumConst) { 15006 // C++0x [dcl.enum]p5: 15007 // If the underlying type is not fixed, the type of each enumerator 15008 // is the type of its initializing value: 15009 // - If no initializer is specified for the first enumerator, the 15010 // initializing value has an unspecified integral type. 15011 // 15012 // GCC uses 'int' for its unspecified integral type, as does 15013 // C99 6.7.2.2p3. 15014 if (Enum->isFixed()) { 15015 EltTy = Enum->getIntegerType(); 15016 } 15017 else { 15018 EltTy = Context.IntTy; 15019 } 15020 } else { 15021 // Assign the last value + 1. 15022 EnumVal = LastEnumConst->getInitVal(); 15023 ++EnumVal; 15024 EltTy = LastEnumConst->getType(); 15025 15026 // Check for overflow on increment. 15027 if (EnumVal < LastEnumConst->getInitVal()) { 15028 // C++0x [dcl.enum]p5: 15029 // If the underlying type is not fixed, the type of each enumerator 15030 // is the type of its initializing value: 15031 // 15032 // - Otherwise the type of the initializing value is the same as 15033 // the type of the initializing value of the preceding enumerator 15034 // unless the incremented value is not representable in that type, 15035 // in which case the type is an unspecified integral type 15036 // sufficient to contain the incremented value. If no such type 15037 // exists, the program is ill-formed. 15038 QualType T = getNextLargerIntegralType(Context, EltTy); 15039 if (T.isNull() || Enum->isFixed()) { 15040 // There is no integral type larger enough to represent this 15041 // value. Complain, then allow the value to wrap around. 15042 EnumVal = LastEnumConst->getInitVal(); 15043 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15044 ++EnumVal; 15045 if (Enum->isFixed()) 15046 // When the underlying type is fixed, this is ill-formed. 15047 Diag(IdLoc, diag::err_enumerator_wrapped) 15048 << EnumVal.toString(10) 15049 << EltTy; 15050 else 15051 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15052 << EnumVal.toString(10); 15053 } else { 15054 EltTy = T; 15055 } 15056 15057 // Retrieve the last enumerator's value, extent that type to the 15058 // type that is supposed to be large enough to represent the incremented 15059 // value, then increment. 15060 EnumVal = LastEnumConst->getInitVal(); 15061 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15062 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15063 ++EnumVal; 15064 15065 // If we're not in C++, diagnose the overflow of enumerator values, 15066 // which in C99 means that the enumerator value is not representable in 15067 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15068 // permits enumerator values that are representable in some larger 15069 // integral type. 15070 if (!getLangOpts().CPlusPlus && !T.isNull()) 15071 Diag(IdLoc, diag::warn_enum_value_overflow); 15072 } else if (!getLangOpts().CPlusPlus && 15073 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15074 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15075 Diag(IdLoc, diag::ext_enum_value_not_int) 15076 << EnumVal.toString(10) << 1; 15077 } 15078 } 15079 } 15080 15081 if (!EltTy->isDependentType()) { 15082 // Make the enumerator value match the signedness and size of the 15083 // enumerator's type. 15084 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15085 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15086 } 15087 15088 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15089 Val, EnumVal); 15090 } 15091 15092 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15093 SourceLocation IILoc) { 15094 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15095 !getLangOpts().CPlusPlus) 15096 return SkipBodyInfo(); 15097 15098 // We have an anonymous enum definition. Look up the first enumerator to 15099 // determine if we should merge the definition with an existing one and 15100 // skip the body. 15101 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15102 ForRedeclaration); 15103 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15104 if (!PrevECD) 15105 return SkipBodyInfo(); 15106 15107 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15108 NamedDecl *Hidden; 15109 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15110 SkipBodyInfo Skip; 15111 Skip.Previous = Hidden; 15112 return Skip; 15113 } 15114 15115 return SkipBodyInfo(); 15116 } 15117 15118 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15119 SourceLocation IdLoc, IdentifierInfo *Id, 15120 AttributeList *Attr, 15121 SourceLocation EqualLoc, Expr *Val) { 15122 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15123 EnumConstantDecl *LastEnumConst = 15124 cast_or_null<EnumConstantDecl>(lastEnumConst); 15125 15126 // The scope passed in may not be a decl scope. Zip up the scope tree until 15127 // we find one that is. 15128 S = getNonFieldDeclScope(S); 15129 15130 // Verify that there isn't already something declared with this name in this 15131 // scope. 15132 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15133 ForRedeclaration); 15134 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15135 // Maybe we will complain about the shadowed template parameter. 15136 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15137 // Just pretend that we didn't see the previous declaration. 15138 PrevDecl = nullptr; 15139 } 15140 15141 // C++ [class.mem]p15: 15142 // If T is the name of a class, then each of the following shall have a name 15143 // different from T: 15144 // - every enumerator of every member of class T that is an unscoped 15145 // enumerated type 15146 if (!TheEnumDecl->isScoped()) 15147 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15148 DeclarationNameInfo(Id, IdLoc)); 15149 15150 EnumConstantDecl *New = 15151 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15152 if (!New) 15153 return nullptr; 15154 15155 if (PrevDecl) { 15156 // When in C++, we may get a TagDecl with the same name; in this case the 15157 // enum constant will 'hide' the tag. 15158 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15159 "Received TagDecl when not in C++!"); 15160 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15161 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15162 if (isa<EnumConstantDecl>(PrevDecl)) 15163 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15164 else 15165 Diag(IdLoc, diag::err_redefinition) << Id; 15166 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15167 return nullptr; 15168 } 15169 } 15170 15171 // Process attributes. 15172 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15173 15174 // Register this decl in the current scope stack. 15175 New->setAccess(TheEnumDecl->getAccess()); 15176 PushOnScopeChains(New, S); 15177 15178 ActOnDocumentableDecl(New); 15179 15180 return New; 15181 } 15182 15183 // Returns true when the enum initial expression does not trigger the 15184 // duplicate enum warning. A few common cases are exempted as follows: 15185 // Element2 = Element1 15186 // Element2 = Element1 + 1 15187 // Element2 = Element1 - 1 15188 // Where Element2 and Element1 are from the same enum. 15189 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15190 Expr *InitExpr = ECD->getInitExpr(); 15191 if (!InitExpr) 15192 return true; 15193 InitExpr = InitExpr->IgnoreImpCasts(); 15194 15195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15196 if (!BO->isAdditiveOp()) 15197 return true; 15198 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15199 if (!IL) 15200 return true; 15201 if (IL->getValue() != 1) 15202 return true; 15203 15204 InitExpr = BO->getLHS(); 15205 } 15206 15207 // This checks if the elements are from the same enum. 15208 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15209 if (!DRE) 15210 return true; 15211 15212 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15213 if (!EnumConstant) 15214 return true; 15215 15216 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15217 Enum) 15218 return true; 15219 15220 return false; 15221 } 15222 15223 namespace { 15224 struct DupKey { 15225 int64_t val; 15226 bool isTombstoneOrEmptyKey; 15227 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15228 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15229 }; 15230 15231 static DupKey GetDupKey(const llvm::APSInt& Val) { 15232 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15233 false); 15234 } 15235 15236 struct DenseMapInfoDupKey { 15237 static DupKey getEmptyKey() { return DupKey(0, true); } 15238 static DupKey getTombstoneKey() { return DupKey(1, true); } 15239 static unsigned getHashValue(const DupKey Key) { 15240 return (unsigned)(Key.val * 37); 15241 } 15242 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15243 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15244 LHS.val == RHS.val; 15245 } 15246 }; 15247 } // end anonymous namespace 15248 15249 // Emits a warning when an element is implicitly set a value that 15250 // a previous element has already been set to. 15251 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15252 EnumDecl *Enum, 15253 QualType EnumType) { 15254 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15255 return; 15256 // Avoid anonymous enums 15257 if (!Enum->getIdentifier()) 15258 return; 15259 15260 // Only check for small enums. 15261 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15262 return; 15263 15264 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15265 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15266 15267 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15268 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15269 ValueToVectorMap; 15270 15271 DuplicatesVector DupVector; 15272 ValueToVectorMap EnumMap; 15273 15274 // Populate the EnumMap with all values represented by enum constants without 15275 // an initialier. 15276 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15277 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15278 15279 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15280 // this constant. Skip this enum since it may be ill-formed. 15281 if (!ECD) { 15282 return; 15283 } 15284 15285 if (ECD->getInitExpr()) 15286 continue; 15287 15288 DupKey Key = GetDupKey(ECD->getInitVal()); 15289 DeclOrVector &Entry = EnumMap[Key]; 15290 15291 // First time encountering this value. 15292 if (Entry.isNull()) 15293 Entry = ECD; 15294 } 15295 15296 // Create vectors for any values that has duplicates. 15297 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15298 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15299 if (!ValidDuplicateEnum(ECD, Enum)) 15300 continue; 15301 15302 DupKey Key = GetDupKey(ECD->getInitVal()); 15303 15304 DeclOrVector& Entry = EnumMap[Key]; 15305 if (Entry.isNull()) 15306 continue; 15307 15308 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15309 // Ensure constants are different. 15310 if (D == ECD) 15311 continue; 15312 15313 // Create new vector and push values onto it. 15314 ECDVector *Vec = new ECDVector(); 15315 Vec->push_back(D); 15316 Vec->push_back(ECD); 15317 15318 // Update entry to point to the duplicates vector. 15319 Entry = Vec; 15320 15321 // Store the vector somewhere we can consult later for quick emission of 15322 // diagnostics. 15323 DupVector.push_back(Vec); 15324 continue; 15325 } 15326 15327 ECDVector *Vec = Entry.get<ECDVector*>(); 15328 // Make sure constants are not added more than once. 15329 if (*Vec->begin() == ECD) 15330 continue; 15331 15332 Vec->push_back(ECD); 15333 } 15334 15335 // Emit diagnostics. 15336 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15337 DupVectorEnd = DupVector.end(); 15338 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15339 ECDVector *Vec = *DupVectorIter; 15340 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15341 15342 // Emit warning for one enum constant. 15343 ECDVector::iterator I = Vec->begin(); 15344 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15345 << (*I)->getName() << (*I)->getInitVal().toString(10) 15346 << (*I)->getSourceRange(); 15347 ++I; 15348 15349 // Emit one note for each of the remaining enum constants with 15350 // the same value. 15351 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15352 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15353 << (*I)->getName() << (*I)->getInitVal().toString(10) 15354 << (*I)->getSourceRange(); 15355 delete Vec; 15356 } 15357 } 15358 15359 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15360 bool AllowMask) const { 15361 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 15362 assert(ED->isCompleteDefinition() && "expected enum definition"); 15363 15364 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15365 llvm::APInt &FlagBits = R.first->second; 15366 15367 if (R.second) { 15368 for (auto *E : ED->enumerators()) { 15369 const auto &EVal = E->getInitVal(); 15370 // Only single-bit enumerators introduce new flag values. 15371 if (EVal.isPowerOf2()) 15372 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15373 } 15374 } 15375 15376 // A value is in a flag enum if either its bits are a subset of the enum's 15377 // flag bits (the first condition) or we are allowing masks and the same is 15378 // true of its complement (the second condition). When masks are allowed, we 15379 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15380 // 15381 // While it's true that any value could be used as a mask, the assumption is 15382 // that a mask will have all of the insignificant bits set. Anything else is 15383 // likely a logic error. 15384 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15385 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15386 } 15387 15388 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15389 Decl *EnumDeclX, 15390 ArrayRef<Decl *> Elements, 15391 Scope *S, AttributeList *Attr) { 15392 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15393 QualType EnumType = Context.getTypeDeclType(Enum); 15394 15395 if (Attr) 15396 ProcessDeclAttributeList(S, Enum, Attr); 15397 15398 if (Enum->isDependentType()) { 15399 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15400 EnumConstantDecl *ECD = 15401 cast_or_null<EnumConstantDecl>(Elements[i]); 15402 if (!ECD) continue; 15403 15404 ECD->setType(EnumType); 15405 } 15406 15407 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15408 return; 15409 } 15410 15411 // TODO: If the result value doesn't fit in an int, it must be a long or long 15412 // long value. ISO C does not support this, but GCC does as an extension, 15413 // emit a warning. 15414 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15415 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15416 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15417 15418 // Verify that all the values are okay, compute the size of the values, and 15419 // reverse the list. 15420 unsigned NumNegativeBits = 0; 15421 unsigned NumPositiveBits = 0; 15422 15423 // Keep track of whether all elements have type int. 15424 bool AllElementsInt = true; 15425 15426 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15427 EnumConstantDecl *ECD = 15428 cast_or_null<EnumConstantDecl>(Elements[i]); 15429 if (!ECD) continue; // Already issued a diagnostic. 15430 15431 const llvm::APSInt &InitVal = ECD->getInitVal(); 15432 15433 // Keep track of the size of positive and negative values. 15434 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15435 NumPositiveBits = std::max(NumPositiveBits, 15436 (unsigned)InitVal.getActiveBits()); 15437 else 15438 NumNegativeBits = std::max(NumNegativeBits, 15439 (unsigned)InitVal.getMinSignedBits()); 15440 15441 // Keep track of whether every enum element has type int (very commmon). 15442 if (AllElementsInt) 15443 AllElementsInt = ECD->getType() == Context.IntTy; 15444 } 15445 15446 // Figure out the type that should be used for this enum. 15447 QualType BestType; 15448 unsigned BestWidth; 15449 15450 // C++0x N3000 [conv.prom]p3: 15451 // An rvalue of an unscoped enumeration type whose underlying 15452 // type is not fixed can be converted to an rvalue of the first 15453 // of the following types that can represent all the values of 15454 // the enumeration: int, unsigned int, long int, unsigned long 15455 // int, long long int, or unsigned long long int. 15456 // C99 6.4.4.3p2: 15457 // An identifier declared as an enumeration constant has type int. 15458 // The C99 rule is modified by a gcc extension 15459 QualType BestPromotionType; 15460 15461 bool Packed = Enum->hasAttr<PackedAttr>(); 15462 // -fshort-enums is the equivalent to specifying the packed attribute on all 15463 // enum definitions. 15464 if (LangOpts.ShortEnums) 15465 Packed = true; 15466 15467 if (Enum->isFixed()) { 15468 BestType = Enum->getIntegerType(); 15469 if (BestType->isPromotableIntegerType()) 15470 BestPromotionType = Context.getPromotedIntegerType(BestType); 15471 else 15472 BestPromotionType = BestType; 15473 15474 BestWidth = Context.getIntWidth(BestType); 15475 } 15476 else if (NumNegativeBits) { 15477 // If there is a negative value, figure out the smallest integer type (of 15478 // int/long/longlong) that fits. 15479 // If it's packed, check also if it fits a char or a short. 15480 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15481 BestType = Context.SignedCharTy; 15482 BestWidth = CharWidth; 15483 } else if (Packed && NumNegativeBits <= ShortWidth && 15484 NumPositiveBits < ShortWidth) { 15485 BestType = Context.ShortTy; 15486 BestWidth = ShortWidth; 15487 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15488 BestType = Context.IntTy; 15489 BestWidth = IntWidth; 15490 } else { 15491 BestWidth = Context.getTargetInfo().getLongWidth(); 15492 15493 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15494 BestType = Context.LongTy; 15495 } else { 15496 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15497 15498 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15499 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15500 BestType = Context.LongLongTy; 15501 } 15502 } 15503 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15504 } else { 15505 // If there is no negative value, figure out the smallest type that fits 15506 // all of the enumerator values. 15507 // If it's packed, check also if it fits a char or a short. 15508 if (Packed && NumPositiveBits <= CharWidth) { 15509 BestType = Context.UnsignedCharTy; 15510 BestPromotionType = Context.IntTy; 15511 BestWidth = CharWidth; 15512 } else if (Packed && NumPositiveBits <= ShortWidth) { 15513 BestType = Context.UnsignedShortTy; 15514 BestPromotionType = Context.IntTy; 15515 BestWidth = ShortWidth; 15516 } else if (NumPositiveBits <= IntWidth) { 15517 BestType = Context.UnsignedIntTy; 15518 BestWidth = IntWidth; 15519 BestPromotionType 15520 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15521 ? Context.UnsignedIntTy : Context.IntTy; 15522 } else if (NumPositiveBits <= 15523 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15524 BestType = Context.UnsignedLongTy; 15525 BestPromotionType 15526 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15527 ? Context.UnsignedLongTy : Context.LongTy; 15528 } else { 15529 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15530 assert(NumPositiveBits <= BestWidth && 15531 "How could an initializer get larger than ULL?"); 15532 BestType = Context.UnsignedLongLongTy; 15533 BestPromotionType 15534 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15535 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15536 } 15537 } 15538 15539 // Loop over all of the enumerator constants, changing their types to match 15540 // the type of the enum if needed. 15541 for (auto *D : Elements) { 15542 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15543 if (!ECD) continue; // Already issued a diagnostic. 15544 15545 // Standard C says the enumerators have int type, but we allow, as an 15546 // extension, the enumerators to be larger than int size. If each 15547 // enumerator value fits in an int, type it as an int, otherwise type it the 15548 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15549 // that X has type 'int', not 'unsigned'. 15550 15551 // Determine whether the value fits into an int. 15552 llvm::APSInt InitVal = ECD->getInitVal(); 15553 15554 // If it fits into an integer type, force it. Otherwise force it to match 15555 // the enum decl type. 15556 QualType NewTy; 15557 unsigned NewWidth; 15558 bool NewSign; 15559 if (!getLangOpts().CPlusPlus && 15560 !Enum->isFixed() && 15561 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15562 NewTy = Context.IntTy; 15563 NewWidth = IntWidth; 15564 NewSign = true; 15565 } else if (ECD->getType() == BestType) { 15566 // Already the right type! 15567 if (getLangOpts().CPlusPlus) 15568 // C++ [dcl.enum]p4: Following the closing brace of an 15569 // enum-specifier, each enumerator has the type of its 15570 // enumeration. 15571 ECD->setType(EnumType); 15572 continue; 15573 } else { 15574 NewTy = BestType; 15575 NewWidth = BestWidth; 15576 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15577 } 15578 15579 // Adjust the APSInt value. 15580 InitVal = InitVal.extOrTrunc(NewWidth); 15581 InitVal.setIsSigned(NewSign); 15582 ECD->setInitVal(InitVal); 15583 15584 // Adjust the Expr initializer and type. 15585 if (ECD->getInitExpr() && 15586 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15587 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15588 CK_IntegralCast, 15589 ECD->getInitExpr(), 15590 /*base paths*/ nullptr, 15591 VK_RValue)); 15592 if (getLangOpts().CPlusPlus) 15593 // C++ [dcl.enum]p4: Following the closing brace of an 15594 // enum-specifier, each enumerator has the type of its 15595 // enumeration. 15596 ECD->setType(EnumType); 15597 else 15598 ECD->setType(NewTy); 15599 } 15600 15601 Enum->completeDefinition(BestType, BestPromotionType, 15602 NumPositiveBits, NumNegativeBits); 15603 15604 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15605 15606 if (Enum->hasAttr<FlagEnumAttr>()) { 15607 for (Decl *D : Elements) { 15608 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15609 if (!ECD) continue; // Already issued a diagnostic. 15610 15611 llvm::APSInt InitVal = ECD->getInitVal(); 15612 if (InitVal != 0 && !InitVal.isPowerOf2() && 15613 !IsValueInFlagEnum(Enum, InitVal, true)) 15614 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15615 << ECD << Enum; 15616 } 15617 } 15618 15619 // Now that the enum type is defined, ensure it's not been underaligned. 15620 if (Enum->hasAttrs()) 15621 CheckAlignasUnderalignment(Enum); 15622 } 15623 15624 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15625 SourceLocation StartLoc, 15626 SourceLocation EndLoc) { 15627 StringLiteral *AsmString = cast<StringLiteral>(expr); 15628 15629 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15630 AsmString, StartLoc, 15631 EndLoc); 15632 CurContext->addDecl(New); 15633 return New; 15634 } 15635 15636 static void checkModuleImportContext(Sema &S, Module *M, 15637 SourceLocation ImportLoc, DeclContext *DC, 15638 bool FromInclude = false) { 15639 SourceLocation ExternCLoc; 15640 15641 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15642 switch (LSD->getLanguage()) { 15643 case LinkageSpecDecl::lang_c: 15644 if (ExternCLoc.isInvalid()) 15645 ExternCLoc = LSD->getLocStart(); 15646 break; 15647 case LinkageSpecDecl::lang_cxx: 15648 break; 15649 } 15650 DC = LSD->getParent(); 15651 } 15652 15653 while (isa<LinkageSpecDecl>(DC)) 15654 DC = DC->getParent(); 15655 15656 if (!isa<TranslationUnitDecl>(DC)) { 15657 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15658 ? diag::ext_module_import_not_at_top_level_noop 15659 : diag::err_module_import_not_at_top_level_fatal) 15660 << M->getFullModuleName() << DC; 15661 S.Diag(cast<Decl>(DC)->getLocStart(), 15662 diag::note_module_import_not_at_top_level) << DC; 15663 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15664 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15665 << M->getFullModuleName(); 15666 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15667 } 15668 } 15669 15670 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15671 ModuleDeclKind MDK, 15672 ModuleIdPath Path) { 15673 // 'module implementation' requires that we are not compiling a module of any 15674 // kind. 'module' and 'module partition' require that we are compiling a 15675 // module inteface (not a module map). 15676 auto CMK = getLangOpts().getCompilingModule(); 15677 if (MDK == ModuleDeclKind::Implementation 15678 ? CMK != LangOptions::CMK_None 15679 : CMK != LangOptions::CMK_ModuleInterface) { 15680 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15681 << (unsigned)MDK; 15682 return nullptr; 15683 } 15684 15685 // FIXME: Create a ModuleDecl and return it. 15686 15687 // FIXME: Most of this work should be done by the preprocessor rather than 15688 // here, in case we look ahead across something where the current 15689 // module matters (eg a #include). 15690 15691 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15692 // hierarchical module map modules, the dots here are just another character 15693 // that can appear in a module name. Flatten down to the actual module name. 15694 std::string ModuleName; 15695 for (auto &Piece : Path) { 15696 if (!ModuleName.empty()) 15697 ModuleName += "."; 15698 ModuleName += Piece.first->getName(); 15699 } 15700 15701 // If a module name was explicitly specified on the command line, it must be 15702 // correct. 15703 if (!getLangOpts().CurrentModule.empty() && 15704 getLangOpts().CurrentModule != ModuleName) { 15705 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15706 << SourceRange(Path.front().second, Path.back().second) 15707 << getLangOpts().CurrentModule; 15708 return nullptr; 15709 } 15710 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15711 15712 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15713 15714 switch (MDK) { 15715 case ModuleDeclKind::Module: { 15716 // FIXME: Check we're not in a submodule. 15717 15718 // We can't have imported a definition of this module or parsed a module 15719 // map defining it already. 15720 if (auto *M = Map.findModule(ModuleName)) { 15721 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15722 if (M->DefinitionLoc.isValid()) 15723 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15724 else if (const auto *FE = M->getASTFile()) 15725 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15726 << FE->getName(); 15727 return nullptr; 15728 } 15729 15730 // Create a Module for the module that we're defining. 15731 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15732 assert(Mod && "module creation should not fail"); 15733 15734 // Enter the semantic scope of the module. 15735 ActOnModuleBegin(ModuleLoc, Mod); 15736 return nullptr; 15737 } 15738 15739 case ModuleDeclKind::Partition: 15740 // FIXME: Check we are in a submodule of the named module. 15741 return nullptr; 15742 15743 case ModuleDeclKind::Implementation: 15744 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15745 PP.getIdentifierInfo(ModuleName), Path[0].second); 15746 15747 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15748 if (Import.isInvalid()) 15749 return nullptr; 15750 return ConvertDeclToDeclGroup(Import.get()); 15751 } 15752 15753 llvm_unreachable("unexpected module decl kind"); 15754 } 15755 15756 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15757 SourceLocation ImportLoc, 15758 ModuleIdPath Path) { 15759 Module *Mod = 15760 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15761 /*IsIncludeDirective=*/false); 15762 if (!Mod) 15763 return true; 15764 15765 VisibleModules.setVisible(Mod, ImportLoc); 15766 15767 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15768 15769 // FIXME: we should support importing a submodule within a different submodule 15770 // of the same top-level module. Until we do, make it an error rather than 15771 // silently ignoring the import. 15772 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15773 // warn on a redundant import of the current module? 15774 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15775 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15776 Diag(ImportLoc, getLangOpts().isCompilingModule() 15777 ? diag::err_module_self_import 15778 : diag::err_module_import_in_implementation) 15779 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15780 15781 SmallVector<SourceLocation, 2> IdentifierLocs; 15782 Module *ModCheck = Mod; 15783 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15784 // If we've run out of module parents, just drop the remaining identifiers. 15785 // We need the length to be consistent. 15786 if (!ModCheck) 15787 break; 15788 ModCheck = ModCheck->Parent; 15789 15790 IdentifierLocs.push_back(Path[I].second); 15791 } 15792 15793 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15794 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15795 Mod, IdentifierLocs); 15796 if (!ModuleScopes.empty()) 15797 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15798 TU->addDecl(Import); 15799 return Import; 15800 } 15801 15802 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15803 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15804 BuildModuleInclude(DirectiveLoc, Mod); 15805 } 15806 15807 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15808 // Determine whether we're in the #include buffer for a module. The #includes 15809 // in that buffer do not qualify as module imports; they're just an 15810 // implementation detail of us building the module. 15811 // 15812 // FIXME: Should we even get ActOnModuleInclude calls for those? 15813 bool IsInModuleIncludes = 15814 TUKind == TU_Module && 15815 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15816 15817 bool ShouldAddImport = !IsInModuleIncludes; 15818 15819 // If this module import was due to an inclusion directive, create an 15820 // implicit import declaration to capture it in the AST. 15821 if (ShouldAddImport) { 15822 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15823 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15824 DirectiveLoc, Mod, 15825 DirectiveLoc); 15826 if (!ModuleScopes.empty()) 15827 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15828 TU->addDecl(ImportD); 15829 Consumer.HandleImplicitImportDecl(ImportD); 15830 } 15831 15832 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15833 VisibleModules.setVisible(Mod, DirectiveLoc); 15834 } 15835 15836 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15837 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15838 15839 ModuleScopes.push_back({}); 15840 ModuleScopes.back().Module = Mod; 15841 if (getLangOpts().ModulesLocalVisibility) 15842 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15843 15844 VisibleModules.setVisible(Mod, DirectiveLoc); 15845 } 15846 15847 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15848 if (getLangOpts().ModulesLocalVisibility) { 15849 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15850 // Leaving a module hides namespace names, so our visible namespace cache 15851 // is now out of date. 15852 VisibleNamespaceCache.clear(); 15853 } 15854 15855 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15856 "left the wrong module scope"); 15857 ModuleScopes.pop_back(); 15858 15859 // We got to the end of processing a #include of a local module. Create an 15860 // ImportDecl as we would for an imported module. 15861 FileID File = getSourceManager().getFileID(EofLoc); 15862 assert(File != getSourceManager().getMainFileID() && 15863 "end of submodule in main source file"); 15864 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15865 BuildModuleInclude(DirectiveLoc, Mod); 15866 } 15867 15868 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15869 Module *Mod) { 15870 // Bail if we're not allowed to implicitly import a module here. 15871 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15872 return; 15873 15874 // Create the implicit import declaration. 15875 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15876 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15877 Loc, Mod, Loc); 15878 TU->addDecl(ImportD); 15879 Consumer.HandleImplicitImportDecl(ImportD); 15880 15881 // Make the module visible. 15882 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15883 VisibleModules.setVisible(Mod, Loc); 15884 } 15885 15886 /// We have parsed the start of an export declaration, including the '{' 15887 /// (if present). 15888 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15889 SourceLocation LBraceLoc) { 15890 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15891 15892 // C++ Modules TS draft: 15893 // An export-declaration [...] shall not contain more than one 15894 // export keyword. 15895 // 15896 // The intent here is that an export-declaration cannot appear within another 15897 // export-declaration. 15898 if (D->isExported()) 15899 Diag(ExportLoc, diag::err_export_within_export); 15900 15901 CurContext->addDecl(D); 15902 PushDeclContext(S, D); 15903 return D; 15904 } 15905 15906 /// Complete the definition of an export declaration. 15907 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15908 auto *ED = cast<ExportDecl>(D); 15909 if (RBraceLoc.isValid()) 15910 ED->setRBraceLoc(RBraceLoc); 15911 15912 // FIXME: Diagnose export of internal-linkage declaration (including 15913 // anonymous namespace). 15914 15915 PopDeclContext(); 15916 return D; 15917 } 15918 15919 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15920 IdentifierInfo* AliasName, 15921 SourceLocation PragmaLoc, 15922 SourceLocation NameLoc, 15923 SourceLocation AliasNameLoc) { 15924 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15925 LookupOrdinaryName); 15926 AsmLabelAttr *Attr = 15927 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15928 15929 // If a declaration that: 15930 // 1) declares a function or a variable 15931 // 2) has external linkage 15932 // already exists, add a label attribute to it. 15933 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15934 if (isDeclExternC(PrevDecl)) 15935 PrevDecl->addAttr(Attr); 15936 else 15937 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15938 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15939 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15940 } else 15941 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15942 } 15943 15944 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15945 SourceLocation PragmaLoc, 15946 SourceLocation NameLoc) { 15947 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15948 15949 if (PrevDecl) { 15950 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15951 } else { 15952 (void)WeakUndeclaredIdentifiers.insert( 15953 std::pair<IdentifierInfo*,WeakInfo> 15954 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15955 } 15956 } 15957 15958 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15959 IdentifierInfo* AliasName, 15960 SourceLocation PragmaLoc, 15961 SourceLocation NameLoc, 15962 SourceLocation AliasNameLoc) { 15963 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15964 LookupOrdinaryName); 15965 WeakInfo W = WeakInfo(Name, NameLoc); 15966 15967 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15968 if (!PrevDecl->hasAttr<AliasAttr>()) 15969 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15970 DeclApplyPragmaWeak(TUScope, ND, W); 15971 } else { 15972 (void)WeakUndeclaredIdentifiers.insert( 15973 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15974 } 15975 } 15976 15977 Decl *Sema::getObjCDeclContext() const { 15978 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15979 } 15980