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 (ActiveTemplateInstantiations.empty()) { 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_OperatorFunctionId: 4679 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4680 Name.OperatorFunctionId.Operator)); 4681 NameInfo.setLoc(Name.StartLocation); 4682 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4683 = Name.OperatorFunctionId.SymbolLocations[0]; 4684 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4685 = Name.EndLocation.getRawEncoding(); 4686 return NameInfo; 4687 4688 case UnqualifiedId::IK_LiteralOperatorId: 4689 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4690 Name.Identifier)); 4691 NameInfo.setLoc(Name.StartLocation); 4692 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4693 return NameInfo; 4694 4695 case UnqualifiedId::IK_ConversionFunctionId: { 4696 TypeSourceInfo *TInfo; 4697 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4698 if (Ty.isNull()) 4699 return DeclarationNameInfo(); 4700 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4701 Context.getCanonicalType(Ty))); 4702 NameInfo.setLoc(Name.StartLocation); 4703 NameInfo.setNamedTypeInfo(TInfo); 4704 return NameInfo; 4705 } 4706 4707 case UnqualifiedId::IK_ConstructorName: { 4708 TypeSourceInfo *TInfo; 4709 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4710 if (Ty.isNull()) 4711 return DeclarationNameInfo(); 4712 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4713 Context.getCanonicalType(Ty))); 4714 NameInfo.setLoc(Name.StartLocation); 4715 NameInfo.setNamedTypeInfo(TInfo); 4716 return NameInfo; 4717 } 4718 4719 case UnqualifiedId::IK_ConstructorTemplateId: { 4720 // In well-formed code, we can only have a constructor 4721 // template-id that refers to the current context, so go there 4722 // to find the actual type being constructed. 4723 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4724 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4725 return DeclarationNameInfo(); 4726 4727 // Determine the type of the class being constructed. 4728 QualType CurClassType = Context.getTypeDeclType(CurClass); 4729 4730 // FIXME: Check two things: that the template-id names the same type as 4731 // CurClassType, and that the template-id does not occur when the name 4732 // was qualified. 4733 4734 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4735 Context.getCanonicalType(CurClassType))); 4736 NameInfo.setLoc(Name.StartLocation); 4737 // FIXME: should we retrieve TypeSourceInfo? 4738 NameInfo.setNamedTypeInfo(nullptr); 4739 return NameInfo; 4740 } 4741 4742 case UnqualifiedId::IK_DestructorName: { 4743 TypeSourceInfo *TInfo; 4744 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4745 if (Ty.isNull()) 4746 return DeclarationNameInfo(); 4747 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4748 Context.getCanonicalType(Ty))); 4749 NameInfo.setLoc(Name.StartLocation); 4750 NameInfo.setNamedTypeInfo(TInfo); 4751 return NameInfo; 4752 } 4753 4754 case UnqualifiedId::IK_TemplateId: { 4755 TemplateName TName = Name.TemplateId->Template.get(); 4756 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4757 return Context.getNameForTemplate(TName, TNameLoc); 4758 } 4759 4760 } // switch (Name.getKind()) 4761 4762 llvm_unreachable("Unknown name kind"); 4763 } 4764 4765 static QualType getCoreType(QualType Ty) { 4766 do { 4767 if (Ty->isPointerType() || Ty->isReferenceType()) 4768 Ty = Ty->getPointeeType(); 4769 else if (Ty->isArrayType()) 4770 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4771 else 4772 return Ty.withoutLocalFastQualifiers(); 4773 } while (true); 4774 } 4775 4776 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4777 /// and Definition have "nearly" matching parameters. This heuristic is 4778 /// used to improve diagnostics in the case where an out-of-line function 4779 /// definition doesn't match any declaration within the class or namespace. 4780 /// Also sets Params to the list of indices to the parameters that differ 4781 /// between the declaration and the definition. If hasSimilarParameters 4782 /// returns true and Params is empty, then all of the parameters match. 4783 static bool hasSimilarParameters(ASTContext &Context, 4784 FunctionDecl *Declaration, 4785 FunctionDecl *Definition, 4786 SmallVectorImpl<unsigned> &Params) { 4787 Params.clear(); 4788 if (Declaration->param_size() != Definition->param_size()) 4789 return false; 4790 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4791 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4792 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4793 4794 // The parameter types are identical 4795 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4796 continue; 4797 4798 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4799 QualType DefParamBaseTy = getCoreType(DefParamTy); 4800 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4801 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4802 4803 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4804 (DeclTyName && DeclTyName == DefTyName)) 4805 Params.push_back(Idx); 4806 else // The two parameters aren't even close 4807 return false; 4808 } 4809 4810 return true; 4811 } 4812 4813 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4814 /// declarator needs to be rebuilt in the current instantiation. 4815 /// Any bits of declarator which appear before the name are valid for 4816 /// consideration here. That's specifically the type in the decl spec 4817 /// and the base type in any member-pointer chunks. 4818 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4819 DeclarationName Name) { 4820 // The types we specifically need to rebuild are: 4821 // - typenames, typeofs, and decltypes 4822 // - types which will become injected class names 4823 // Of course, we also need to rebuild any type referencing such a 4824 // type. It's safest to just say "dependent", but we call out a 4825 // few cases here. 4826 4827 DeclSpec &DS = D.getMutableDeclSpec(); 4828 switch (DS.getTypeSpecType()) { 4829 case DeclSpec::TST_typename: 4830 case DeclSpec::TST_typeofType: 4831 case DeclSpec::TST_underlyingType: 4832 case DeclSpec::TST_atomic: { 4833 // Grab the type from the parser. 4834 TypeSourceInfo *TSI = nullptr; 4835 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4836 if (T.isNull() || !T->isDependentType()) break; 4837 4838 // Make sure there's a type source info. This isn't really much 4839 // of a waste; most dependent types should have type source info 4840 // attached already. 4841 if (!TSI) 4842 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4843 4844 // Rebuild the type in the current instantiation. 4845 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4846 if (!TSI) return true; 4847 4848 // Store the new type back in the decl spec. 4849 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4850 DS.UpdateTypeRep(LocType); 4851 break; 4852 } 4853 4854 case DeclSpec::TST_decltype: 4855 case DeclSpec::TST_typeofExpr: { 4856 Expr *E = DS.getRepAsExpr(); 4857 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4858 if (Result.isInvalid()) return true; 4859 DS.UpdateExprRep(Result.get()); 4860 break; 4861 } 4862 4863 default: 4864 // Nothing to do for these decl specs. 4865 break; 4866 } 4867 4868 // It doesn't matter what order we do this in. 4869 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4870 DeclaratorChunk &Chunk = D.getTypeObject(I); 4871 4872 // The only type information in the declarator which can come 4873 // before the declaration name is the base type of a member 4874 // pointer. 4875 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4876 continue; 4877 4878 // Rebuild the scope specifier in-place. 4879 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4880 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4881 return true; 4882 } 4883 4884 return false; 4885 } 4886 4887 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4888 D.setFunctionDefinitionKind(FDK_Declaration); 4889 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4890 4891 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4892 Dcl && Dcl->getDeclContext()->isFileContext()) 4893 Dcl->setTopLevelDeclInObjCContainer(); 4894 4895 if (getLangOpts().OpenCL) 4896 setCurrentOpenCLExtensionForDecl(Dcl); 4897 4898 return Dcl; 4899 } 4900 4901 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4902 /// If T is the name of a class, then each of the following shall have a 4903 /// name different from T: 4904 /// - every static data member of class T; 4905 /// - every member function of class T 4906 /// - every member of class T that is itself a type; 4907 /// \returns true if the declaration name violates these rules. 4908 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4909 DeclarationNameInfo NameInfo) { 4910 DeclarationName Name = NameInfo.getName(); 4911 4912 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4913 while (Record && Record->isAnonymousStructOrUnion()) 4914 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4915 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4916 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4917 return true; 4918 } 4919 4920 return false; 4921 } 4922 4923 /// \brief Diagnose a declaration whose declarator-id has the given 4924 /// nested-name-specifier. 4925 /// 4926 /// \param SS The nested-name-specifier of the declarator-id. 4927 /// 4928 /// \param DC The declaration context to which the nested-name-specifier 4929 /// resolves. 4930 /// 4931 /// \param Name The name of the entity being declared. 4932 /// 4933 /// \param Loc The location of the name of the entity being declared. 4934 /// 4935 /// \returns true if we cannot safely recover from this error, false otherwise. 4936 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4937 DeclarationName Name, 4938 SourceLocation Loc) { 4939 DeclContext *Cur = CurContext; 4940 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4941 Cur = Cur->getParent(); 4942 4943 // If the user provided a superfluous scope specifier that refers back to the 4944 // class in which the entity is already declared, diagnose and ignore it. 4945 // 4946 // class X { 4947 // void X::f(); 4948 // }; 4949 // 4950 // Note, it was once ill-formed to give redundant qualification in all 4951 // contexts, but that rule was removed by DR482. 4952 if (Cur->Equals(DC)) { 4953 if (Cur->isRecord()) { 4954 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4955 : diag::err_member_extra_qualification) 4956 << Name << FixItHint::CreateRemoval(SS.getRange()); 4957 SS.clear(); 4958 } else { 4959 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4960 } 4961 return false; 4962 } 4963 4964 // Check whether the qualifying scope encloses the scope of the original 4965 // declaration. 4966 if (!Cur->Encloses(DC)) { 4967 if (Cur->isRecord()) 4968 Diag(Loc, diag::err_member_qualification) 4969 << Name << SS.getRange(); 4970 else if (isa<TranslationUnitDecl>(DC)) 4971 Diag(Loc, diag::err_invalid_declarator_global_scope) 4972 << Name << SS.getRange(); 4973 else if (isa<FunctionDecl>(Cur)) 4974 Diag(Loc, diag::err_invalid_declarator_in_function) 4975 << Name << SS.getRange(); 4976 else if (isa<BlockDecl>(Cur)) 4977 Diag(Loc, diag::err_invalid_declarator_in_block) 4978 << Name << SS.getRange(); 4979 else 4980 Diag(Loc, diag::err_invalid_declarator_scope) 4981 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4982 4983 return true; 4984 } 4985 4986 if (Cur->isRecord()) { 4987 // Cannot qualify members within a class. 4988 Diag(Loc, diag::err_member_qualification) 4989 << Name << SS.getRange(); 4990 SS.clear(); 4991 4992 // C++ constructors and destructors with incorrect scopes can break 4993 // our AST invariants by having the wrong underlying types. If 4994 // that's the case, then drop this declaration entirely. 4995 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4996 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4997 !Context.hasSameType(Name.getCXXNameType(), 4998 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4999 return true; 5000 5001 return false; 5002 } 5003 5004 // C++11 [dcl.meaning]p1: 5005 // [...] "The nested-name-specifier of the qualified declarator-id shall 5006 // not begin with a decltype-specifer" 5007 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5008 while (SpecLoc.getPrefix()) 5009 SpecLoc = SpecLoc.getPrefix(); 5010 if (dyn_cast_or_null<DecltypeType>( 5011 SpecLoc.getNestedNameSpecifier()->getAsType())) 5012 Diag(Loc, diag::err_decltype_in_declarator) 5013 << SpecLoc.getTypeLoc().getSourceRange(); 5014 5015 return false; 5016 } 5017 5018 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5019 MultiTemplateParamsArg TemplateParamLists) { 5020 // TODO: consider using NameInfo for diagnostic. 5021 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5022 DeclarationName Name = NameInfo.getName(); 5023 5024 // All of these full declarators require an identifier. If it doesn't have 5025 // one, the ParsedFreeStandingDeclSpec action should be used. 5026 if (D.isDecompositionDeclarator()) { 5027 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5028 } else if (!Name) { 5029 if (!D.isInvalidType()) // Reject this if we think it is valid. 5030 Diag(D.getDeclSpec().getLocStart(), 5031 diag::err_declarator_need_ident) 5032 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5033 return nullptr; 5034 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5035 return nullptr; 5036 5037 // The scope passed in may not be a decl scope. Zip up the scope tree until 5038 // we find one that is. 5039 while ((S->getFlags() & Scope::DeclScope) == 0 || 5040 (S->getFlags() & Scope::TemplateParamScope) != 0) 5041 S = S->getParent(); 5042 5043 DeclContext *DC = CurContext; 5044 if (D.getCXXScopeSpec().isInvalid()) 5045 D.setInvalidType(); 5046 else if (D.getCXXScopeSpec().isSet()) { 5047 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5048 UPPC_DeclarationQualifier)) 5049 return nullptr; 5050 5051 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5052 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5053 if (!DC || isa<EnumDecl>(DC)) { 5054 // If we could not compute the declaration context, it's because the 5055 // declaration context is dependent but does not refer to a class, 5056 // class template, or class template partial specialization. Complain 5057 // and return early, to avoid the coming semantic disaster. 5058 Diag(D.getIdentifierLoc(), 5059 diag::err_template_qualified_declarator_no_match) 5060 << D.getCXXScopeSpec().getScopeRep() 5061 << D.getCXXScopeSpec().getRange(); 5062 return nullptr; 5063 } 5064 bool IsDependentContext = DC->isDependentContext(); 5065 5066 if (!IsDependentContext && 5067 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5068 return nullptr; 5069 5070 // If a class is incomplete, do not parse entities inside it. 5071 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5072 Diag(D.getIdentifierLoc(), 5073 diag::err_member_def_undefined_record) 5074 << Name << DC << D.getCXXScopeSpec().getRange(); 5075 return nullptr; 5076 } 5077 if (!D.getDeclSpec().isFriendSpecified()) { 5078 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5079 Name, D.getIdentifierLoc())) { 5080 if (DC->isRecord()) 5081 return nullptr; 5082 5083 D.setInvalidType(); 5084 } 5085 } 5086 5087 // Check whether we need to rebuild the type of the given 5088 // declaration in the current instantiation. 5089 if (EnteringContext && IsDependentContext && 5090 TemplateParamLists.size() != 0) { 5091 ContextRAII SavedContext(*this, DC); 5092 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5093 D.setInvalidType(); 5094 } 5095 } 5096 5097 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5098 QualType R = TInfo->getType(); 5099 5100 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5101 // If this is a typedef, we'll end up spewing multiple diagnostics. 5102 // Just return early; it's safer. If this is a function, let the 5103 // "constructor cannot have a return type" diagnostic handle it. 5104 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5105 return nullptr; 5106 5107 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5108 UPPC_DeclarationType)) 5109 D.setInvalidType(); 5110 5111 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5112 ForRedeclaration); 5113 5114 // See if this is a redefinition of a variable in the same scope. 5115 if (!D.getCXXScopeSpec().isSet()) { 5116 bool IsLinkageLookup = false; 5117 bool CreateBuiltins = false; 5118 5119 // If the declaration we're planning to build will be a function 5120 // or object with linkage, then look for another declaration with 5121 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5122 // 5123 // If the declaration we're planning to build will be declared with 5124 // external linkage in the translation unit, create any builtin with 5125 // the same name. 5126 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5127 /* Do nothing*/; 5128 else if (CurContext->isFunctionOrMethod() && 5129 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5130 R->isFunctionType())) { 5131 IsLinkageLookup = true; 5132 CreateBuiltins = 5133 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5134 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5135 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5136 CreateBuiltins = true; 5137 5138 if (IsLinkageLookup) 5139 Previous.clear(LookupRedeclarationWithLinkage); 5140 5141 LookupName(Previous, S, CreateBuiltins); 5142 } else { // Something like "int foo::x;" 5143 LookupQualifiedName(Previous, DC); 5144 5145 // C++ [dcl.meaning]p1: 5146 // When the declarator-id is qualified, the declaration shall refer to a 5147 // previously declared member of the class or namespace to which the 5148 // qualifier refers (or, in the case of a namespace, of an element of the 5149 // inline namespace set of that namespace (7.3.1)) or to a specialization 5150 // thereof; [...] 5151 // 5152 // Note that we already checked the context above, and that we do not have 5153 // enough information to make sure that Previous contains the declaration 5154 // we want to match. For example, given: 5155 // 5156 // class X { 5157 // void f(); 5158 // void f(float); 5159 // }; 5160 // 5161 // void X::f(int) { } // ill-formed 5162 // 5163 // In this case, Previous will point to the overload set 5164 // containing the two f's declared in X, but neither of them 5165 // matches. 5166 5167 // C++ [dcl.meaning]p1: 5168 // [...] the member shall not merely have been introduced by a 5169 // using-declaration in the scope of the class or namespace nominated by 5170 // the nested-name-specifier of the declarator-id. 5171 RemoveUsingDecls(Previous); 5172 } 5173 5174 if (Previous.isSingleResult() && 5175 Previous.getFoundDecl()->isTemplateParameter()) { 5176 // Maybe we will complain about the shadowed template parameter. 5177 if (!D.isInvalidType()) 5178 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5179 Previous.getFoundDecl()); 5180 5181 // Just pretend that we didn't see the previous declaration. 5182 Previous.clear(); 5183 } 5184 5185 // In C++, the previous declaration we find might be a tag type 5186 // (class or enum). In this case, the new declaration will hide the 5187 // tag type. Note that this does does not apply if we're declaring a 5188 // typedef (C++ [dcl.typedef]p4). 5189 if (Previous.isSingleTagDecl() && 5190 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5191 Previous.clear(); 5192 5193 // Check that there are no default arguments other than in the parameters 5194 // of a function declaration (C++ only). 5195 if (getLangOpts().CPlusPlus) 5196 CheckExtraCXXDefaultArguments(D); 5197 5198 if (D.getDeclSpec().isConceptSpecified()) { 5199 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5200 // applied only to the definition of a function template or variable 5201 // template, declared in namespace scope 5202 if (!TemplateParamLists.size()) { 5203 Diag(D.getDeclSpec().getConceptSpecLoc(), 5204 diag:: err_concept_wrong_decl_kind); 5205 return nullptr; 5206 } 5207 5208 if (!DC->getRedeclContext()->isFileContext()) { 5209 Diag(D.getIdentifierLoc(), 5210 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5211 return nullptr; 5212 } 5213 } 5214 5215 NamedDecl *New; 5216 5217 bool AddToScope = true; 5218 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5219 if (TemplateParamLists.size()) { 5220 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5221 return nullptr; 5222 } 5223 5224 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5225 } else if (R->isFunctionType()) { 5226 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5227 TemplateParamLists, 5228 AddToScope); 5229 } else { 5230 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5231 AddToScope); 5232 } 5233 5234 if (!New) 5235 return nullptr; 5236 5237 // If this has an identifier and is not a function template specialization, 5238 // add it to the scope stack. 5239 if (New->getDeclName() && AddToScope) { 5240 // Only make a locally-scoped extern declaration visible if it is the first 5241 // declaration of this entity. Qualified lookup for such an entity should 5242 // only find this declaration if there is no visible declaration of it. 5243 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5244 PushOnScopeChains(New, S, AddToContext); 5245 if (!AddToContext) 5246 CurContext->addHiddenDecl(New); 5247 } 5248 5249 if (isInOpenMPDeclareTargetContext()) 5250 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5251 5252 return New; 5253 } 5254 5255 /// Helper method to turn variable array types into constant array 5256 /// types in certain situations which would otherwise be errors (for 5257 /// GCC compatibility). 5258 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5259 ASTContext &Context, 5260 bool &SizeIsNegative, 5261 llvm::APSInt &Oversized) { 5262 // This method tries to turn a variable array into a constant 5263 // array even when the size isn't an ICE. This is necessary 5264 // for compatibility with code that depends on gcc's buggy 5265 // constant expression folding, like struct {char x[(int)(char*)2];} 5266 SizeIsNegative = false; 5267 Oversized = 0; 5268 5269 if (T->isDependentType()) 5270 return QualType(); 5271 5272 QualifierCollector Qs; 5273 const Type *Ty = Qs.strip(T); 5274 5275 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5276 QualType Pointee = PTy->getPointeeType(); 5277 QualType FixedType = 5278 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5279 Oversized); 5280 if (FixedType.isNull()) return FixedType; 5281 FixedType = Context.getPointerType(FixedType); 5282 return Qs.apply(Context, FixedType); 5283 } 5284 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5285 QualType Inner = PTy->getInnerType(); 5286 QualType FixedType = 5287 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5288 Oversized); 5289 if (FixedType.isNull()) return FixedType; 5290 FixedType = Context.getParenType(FixedType); 5291 return Qs.apply(Context, FixedType); 5292 } 5293 5294 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5295 if (!VLATy) 5296 return QualType(); 5297 // FIXME: We should probably handle this case 5298 if (VLATy->getElementType()->isVariablyModifiedType()) 5299 return QualType(); 5300 5301 llvm::APSInt Res; 5302 if (!VLATy->getSizeExpr() || 5303 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5304 return QualType(); 5305 5306 // Check whether the array size is negative. 5307 if (Res.isSigned() && Res.isNegative()) { 5308 SizeIsNegative = true; 5309 return QualType(); 5310 } 5311 5312 // Check whether the array is too large to be addressed. 5313 unsigned ActiveSizeBits 5314 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5315 Res); 5316 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5317 Oversized = Res; 5318 return QualType(); 5319 } 5320 5321 return Context.getConstantArrayType(VLATy->getElementType(), 5322 Res, ArrayType::Normal, 0); 5323 } 5324 5325 static void 5326 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5327 SrcTL = SrcTL.getUnqualifiedLoc(); 5328 DstTL = DstTL.getUnqualifiedLoc(); 5329 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5330 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5331 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5332 DstPTL.getPointeeLoc()); 5333 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5334 return; 5335 } 5336 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5337 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5338 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5339 DstPTL.getInnerLoc()); 5340 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5341 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5342 return; 5343 } 5344 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5345 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5346 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5347 TypeLoc DstElemTL = DstATL.getElementLoc(); 5348 DstElemTL.initializeFullCopy(SrcElemTL); 5349 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5350 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5351 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5352 } 5353 5354 /// Helper method to turn variable array types into constant array 5355 /// types in certain situations which would otherwise be errors (for 5356 /// GCC compatibility). 5357 static TypeSourceInfo* 5358 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5359 ASTContext &Context, 5360 bool &SizeIsNegative, 5361 llvm::APSInt &Oversized) { 5362 QualType FixedTy 5363 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5364 SizeIsNegative, Oversized); 5365 if (FixedTy.isNull()) 5366 return nullptr; 5367 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5368 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5369 FixedTInfo->getTypeLoc()); 5370 return FixedTInfo; 5371 } 5372 5373 /// \brief Register the given locally-scoped extern "C" declaration so 5374 /// that it can be found later for redeclarations. We include any extern "C" 5375 /// declaration that is not visible in the translation unit here, not just 5376 /// function-scope declarations. 5377 void 5378 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5379 if (!getLangOpts().CPlusPlus && 5380 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5381 // Don't need to track declarations in the TU in C. 5382 return; 5383 5384 // Note that we have a locally-scoped external with this name. 5385 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5386 } 5387 5388 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5389 // FIXME: We can have multiple results via __attribute__((overloadable)). 5390 auto Result = Context.getExternCContextDecl()->lookup(Name); 5391 return Result.empty() ? nullptr : *Result.begin(); 5392 } 5393 5394 /// \brief Diagnose function specifiers on a declaration of an identifier that 5395 /// does not identify a function. 5396 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5397 // FIXME: We should probably indicate the identifier in question to avoid 5398 // confusion for constructs like "virtual int a(), b;" 5399 if (DS.isVirtualSpecified()) 5400 Diag(DS.getVirtualSpecLoc(), 5401 diag::err_virtual_non_function); 5402 5403 if (DS.isExplicitSpecified()) 5404 Diag(DS.getExplicitSpecLoc(), 5405 diag::err_explicit_non_function); 5406 5407 if (DS.isNoreturnSpecified()) 5408 Diag(DS.getNoreturnSpecLoc(), 5409 diag::err_noreturn_non_function); 5410 } 5411 5412 NamedDecl* 5413 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5414 TypeSourceInfo *TInfo, LookupResult &Previous) { 5415 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5416 if (D.getCXXScopeSpec().isSet()) { 5417 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5418 << D.getCXXScopeSpec().getRange(); 5419 D.setInvalidType(); 5420 // Pretend we didn't see the scope specifier. 5421 DC = CurContext; 5422 Previous.clear(); 5423 } 5424 5425 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5426 5427 if (D.getDeclSpec().isInlineSpecified()) 5428 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5429 << getLangOpts().CPlusPlus1z; 5430 if (D.getDeclSpec().isConstexprSpecified()) 5431 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5432 << 1; 5433 if (D.getDeclSpec().isConceptSpecified()) 5434 Diag(D.getDeclSpec().getConceptSpecLoc(), 5435 diag::err_concept_wrong_decl_kind); 5436 5437 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5438 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5439 << D.getName().getSourceRange(); 5440 return nullptr; 5441 } 5442 5443 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5444 if (!NewTD) return nullptr; 5445 5446 // Handle attributes prior to checking for duplicates in MergeVarDecl 5447 ProcessDeclAttributes(S, NewTD, D); 5448 5449 CheckTypedefForVariablyModifiedType(S, NewTD); 5450 5451 bool Redeclaration = D.isRedeclaration(); 5452 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5453 D.setRedeclaration(Redeclaration); 5454 return ND; 5455 } 5456 5457 void 5458 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5459 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5460 // then it shall have block scope. 5461 // Note that variably modified types must be fixed before merging the decl so 5462 // that redeclarations will match. 5463 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5464 QualType T = TInfo->getType(); 5465 if (T->isVariablyModifiedType()) { 5466 getCurFunction()->setHasBranchProtectedScope(); 5467 5468 if (S->getFnParent() == nullptr) { 5469 bool SizeIsNegative; 5470 llvm::APSInt Oversized; 5471 TypeSourceInfo *FixedTInfo = 5472 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5473 SizeIsNegative, 5474 Oversized); 5475 if (FixedTInfo) { 5476 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5477 NewTD->setTypeSourceInfo(FixedTInfo); 5478 } else { 5479 if (SizeIsNegative) 5480 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5481 else if (T->isVariableArrayType()) 5482 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5483 else if (Oversized.getBoolValue()) 5484 Diag(NewTD->getLocation(), diag::err_array_too_large) 5485 << Oversized.toString(10); 5486 else 5487 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5488 NewTD->setInvalidDecl(); 5489 } 5490 } 5491 } 5492 } 5493 5494 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5495 /// declares a typedef-name, either using the 'typedef' type specifier or via 5496 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5497 NamedDecl* 5498 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5499 LookupResult &Previous, bool &Redeclaration) { 5500 // Merge the decl with the existing one if appropriate. If the decl is 5501 // in an outer scope, it isn't the same thing. 5502 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5503 /*AllowInlineNamespace*/false); 5504 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5505 if (!Previous.empty()) { 5506 Redeclaration = true; 5507 MergeTypedefNameDecl(S, NewTD, Previous); 5508 } 5509 5510 // If this is the C FILE type, notify the AST context. 5511 if (IdentifierInfo *II = NewTD->getIdentifier()) 5512 if (!NewTD->isInvalidDecl() && 5513 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5514 if (II->isStr("FILE")) 5515 Context.setFILEDecl(NewTD); 5516 else if (II->isStr("jmp_buf")) 5517 Context.setjmp_bufDecl(NewTD); 5518 else if (II->isStr("sigjmp_buf")) 5519 Context.setsigjmp_bufDecl(NewTD); 5520 else if (II->isStr("ucontext_t")) 5521 Context.setucontext_tDecl(NewTD); 5522 } 5523 5524 return NewTD; 5525 } 5526 5527 /// \brief Determines whether the given declaration is an out-of-scope 5528 /// previous declaration. 5529 /// 5530 /// This routine should be invoked when name lookup has found a 5531 /// previous declaration (PrevDecl) that is not in the scope where a 5532 /// new declaration by the same name is being introduced. If the new 5533 /// declaration occurs in a local scope, previous declarations with 5534 /// linkage may still be considered previous declarations (C99 5535 /// 6.2.2p4-5, C++ [basic.link]p6). 5536 /// 5537 /// \param PrevDecl the previous declaration found by name 5538 /// lookup 5539 /// 5540 /// \param DC the context in which the new declaration is being 5541 /// declared. 5542 /// 5543 /// \returns true if PrevDecl is an out-of-scope previous declaration 5544 /// for a new delcaration with the same name. 5545 static bool 5546 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5547 ASTContext &Context) { 5548 if (!PrevDecl) 5549 return false; 5550 5551 if (!PrevDecl->hasLinkage()) 5552 return false; 5553 5554 if (Context.getLangOpts().CPlusPlus) { 5555 // C++ [basic.link]p6: 5556 // If there is a visible declaration of an entity with linkage 5557 // having the same name and type, ignoring entities declared 5558 // outside the innermost enclosing namespace scope, the block 5559 // scope declaration declares that same entity and receives the 5560 // linkage of the previous declaration. 5561 DeclContext *OuterContext = DC->getRedeclContext(); 5562 if (!OuterContext->isFunctionOrMethod()) 5563 // This rule only applies to block-scope declarations. 5564 return false; 5565 5566 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5567 if (PrevOuterContext->isRecord()) 5568 // We found a member function: ignore it. 5569 return false; 5570 5571 // Find the innermost enclosing namespace for the new and 5572 // previous declarations. 5573 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5574 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5575 5576 // The previous declaration is in a different namespace, so it 5577 // isn't the same function. 5578 if (!OuterContext->Equals(PrevOuterContext)) 5579 return false; 5580 } 5581 5582 return true; 5583 } 5584 5585 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5586 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5587 if (!SS.isSet()) return; 5588 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5589 } 5590 5591 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5592 QualType type = decl->getType(); 5593 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5594 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5595 // Various kinds of declaration aren't allowed to be __autoreleasing. 5596 unsigned kind = -1U; 5597 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5598 if (var->hasAttr<BlocksAttr>()) 5599 kind = 0; // __block 5600 else if (!var->hasLocalStorage()) 5601 kind = 1; // global 5602 } else if (isa<ObjCIvarDecl>(decl)) { 5603 kind = 3; // ivar 5604 } else if (isa<FieldDecl>(decl)) { 5605 kind = 2; // field 5606 } 5607 5608 if (kind != -1U) { 5609 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5610 << kind; 5611 } 5612 } else if (lifetime == Qualifiers::OCL_None) { 5613 // Try to infer lifetime. 5614 if (!type->isObjCLifetimeType()) 5615 return false; 5616 5617 lifetime = type->getObjCARCImplicitLifetime(); 5618 type = Context.getLifetimeQualifiedType(type, lifetime); 5619 decl->setType(type); 5620 } 5621 5622 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5623 // Thread-local variables cannot have lifetime. 5624 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5625 var->getTLSKind()) { 5626 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5627 << var->getType(); 5628 return true; 5629 } 5630 } 5631 5632 return false; 5633 } 5634 5635 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5636 // Ensure that an auto decl is deduced otherwise the checks below might cache 5637 // the wrong linkage. 5638 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5639 5640 // 'weak' only applies to declarations with external linkage. 5641 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5642 if (!ND.isExternallyVisible()) { 5643 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5644 ND.dropAttr<WeakAttr>(); 5645 } 5646 } 5647 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5648 if (ND.isExternallyVisible()) { 5649 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5650 ND.dropAttr<WeakRefAttr>(); 5651 ND.dropAttr<AliasAttr>(); 5652 } 5653 } 5654 5655 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5656 if (VD->hasInit()) { 5657 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5658 assert(VD->isThisDeclarationADefinition() && 5659 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5660 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5661 VD->dropAttr<AliasAttr>(); 5662 } 5663 } 5664 } 5665 5666 // 'selectany' only applies to externally visible variable declarations. 5667 // It does not apply to functions. 5668 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5669 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5670 S.Diag(Attr->getLocation(), 5671 diag::err_attribute_selectany_non_extern_data); 5672 ND.dropAttr<SelectAnyAttr>(); 5673 } 5674 } 5675 5676 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5677 // dll attributes require external linkage. Static locals may have external 5678 // linkage but still cannot be explicitly imported or exported. 5679 auto *VD = dyn_cast<VarDecl>(&ND); 5680 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5681 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5682 << &ND << Attr; 5683 ND.setInvalidDecl(); 5684 } 5685 } 5686 5687 // Virtual functions cannot be marked as 'notail'. 5688 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5689 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5690 if (MD->isVirtual()) { 5691 S.Diag(ND.getLocation(), 5692 diag::err_invalid_attribute_on_virtual_function) 5693 << Attr; 5694 ND.dropAttr<NotTailCalledAttr>(); 5695 } 5696 } 5697 5698 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5699 NamedDecl *NewDecl, 5700 bool IsSpecialization, 5701 bool IsDefinition) { 5702 if (OldDecl->isInvalidDecl()) 5703 return; 5704 5705 bool IsTemplate = false; 5706 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5707 OldDecl = OldTD->getTemplatedDecl(); 5708 IsTemplate = true; 5709 if (!IsSpecialization) 5710 IsDefinition = false; 5711 } 5712 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5713 NewDecl = NewTD->getTemplatedDecl(); 5714 IsTemplate = true; 5715 } 5716 5717 if (!OldDecl || !NewDecl) 5718 return; 5719 5720 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5721 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5722 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5723 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5724 5725 // dllimport and dllexport are inheritable attributes so we have to exclude 5726 // inherited attribute instances. 5727 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5728 (NewExportAttr && !NewExportAttr->isInherited()); 5729 5730 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5731 // the only exception being explicit specializations. 5732 // Implicitly generated declarations are also excluded for now because there 5733 // is no other way to switch these to use dllimport or dllexport. 5734 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5735 5736 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5737 // Allow with a warning for free functions and global variables. 5738 bool JustWarn = false; 5739 if (!OldDecl->isCXXClassMember()) { 5740 auto *VD = dyn_cast<VarDecl>(OldDecl); 5741 if (VD && !VD->getDescribedVarTemplate()) 5742 JustWarn = true; 5743 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5744 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5745 JustWarn = true; 5746 } 5747 5748 // We cannot change a declaration that's been used because IR has already 5749 // been emitted. Dllimported functions will still work though (modulo 5750 // address equality) as they can use the thunk. 5751 if (OldDecl->isUsed()) 5752 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5753 JustWarn = false; 5754 5755 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5756 : diag::err_attribute_dll_redeclaration; 5757 S.Diag(NewDecl->getLocation(), DiagID) 5758 << NewDecl 5759 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5760 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5761 if (!JustWarn) { 5762 NewDecl->setInvalidDecl(); 5763 return; 5764 } 5765 } 5766 5767 // A redeclaration is not allowed to drop a dllimport attribute, the only 5768 // exceptions being inline function definitions (except for function 5769 // templates), local extern declarations, qualified friend declarations or 5770 // special MSVC extension: in the last case, the declaration is treated as if 5771 // it were marked dllexport. 5772 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5773 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5774 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5775 // Ignore static data because out-of-line definitions are diagnosed 5776 // separately. 5777 IsStaticDataMember = VD->isStaticDataMember(); 5778 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5779 VarDecl::DeclarationOnly; 5780 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5781 IsInline = FD->isInlined(); 5782 IsQualifiedFriend = FD->getQualifier() && 5783 FD->getFriendObjectKind() == Decl::FOK_Declared; 5784 } 5785 5786 if (OldImportAttr && !HasNewAttr && 5787 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5788 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5789 if (IsMicrosoft && IsDefinition) { 5790 S.Diag(NewDecl->getLocation(), 5791 diag::warn_redeclaration_without_import_attribute) 5792 << NewDecl; 5793 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5794 NewDecl->dropAttr<DLLImportAttr>(); 5795 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5796 NewImportAttr->getRange(), S.Context, 5797 NewImportAttr->getSpellingListIndex())); 5798 } else { 5799 S.Diag(NewDecl->getLocation(), 5800 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5801 << NewDecl << OldImportAttr; 5802 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5803 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5804 OldDecl->dropAttr<DLLImportAttr>(); 5805 NewDecl->dropAttr<DLLImportAttr>(); 5806 } 5807 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5808 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5809 OldDecl->dropAttr<DLLImportAttr>(); 5810 NewDecl->dropAttr<DLLImportAttr>(); 5811 S.Diag(NewDecl->getLocation(), 5812 diag::warn_dllimport_dropped_from_inline_function) 5813 << NewDecl << OldImportAttr; 5814 } 5815 } 5816 5817 /// Given that we are within the definition of the given function, 5818 /// will that definition behave like C99's 'inline', where the 5819 /// definition is discarded except for optimization purposes? 5820 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5821 // Try to avoid calling GetGVALinkageForFunction. 5822 5823 // All cases of this require the 'inline' keyword. 5824 if (!FD->isInlined()) return false; 5825 5826 // This is only possible in C++ with the gnu_inline attribute. 5827 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5828 return false; 5829 5830 // Okay, go ahead and call the relatively-more-expensive function. 5831 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5832 } 5833 5834 /// Determine whether a variable is extern "C" prior to attaching 5835 /// an initializer. We can't just call isExternC() here, because that 5836 /// will also compute and cache whether the declaration is externally 5837 /// visible, which might change when we attach the initializer. 5838 /// 5839 /// This can only be used if the declaration is known to not be a 5840 /// redeclaration of an internal linkage declaration. 5841 /// 5842 /// For instance: 5843 /// 5844 /// auto x = []{}; 5845 /// 5846 /// Attaching the initializer here makes this declaration not externally 5847 /// visible, because its type has internal linkage. 5848 /// 5849 /// FIXME: This is a hack. 5850 template<typename T> 5851 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5852 if (S.getLangOpts().CPlusPlus) { 5853 // In C++, the overloadable attribute negates the effects of extern "C". 5854 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5855 return false; 5856 5857 // So do CUDA's host/device attributes. 5858 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5859 D->template hasAttr<CUDAHostAttr>())) 5860 return false; 5861 } 5862 return D->isExternC(); 5863 } 5864 5865 static bool shouldConsiderLinkage(const VarDecl *VD) { 5866 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5867 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5868 return VD->hasExternalStorage(); 5869 if (DC->isFileContext()) 5870 return true; 5871 if (DC->isRecord()) 5872 return false; 5873 llvm_unreachable("Unexpected context"); 5874 } 5875 5876 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5877 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5878 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5879 isa<OMPDeclareReductionDecl>(DC)) 5880 return true; 5881 if (DC->isRecord()) 5882 return false; 5883 llvm_unreachable("Unexpected context"); 5884 } 5885 5886 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5887 AttributeList::Kind Kind) { 5888 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5889 if (L->getKind() == Kind) 5890 return true; 5891 return false; 5892 } 5893 5894 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5895 AttributeList::Kind Kind) { 5896 // Check decl attributes on the DeclSpec. 5897 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5898 return true; 5899 5900 // Walk the declarator structure, checking decl attributes that were in a type 5901 // position to the decl itself. 5902 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5903 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5904 return true; 5905 } 5906 5907 // Finally, check attributes on the decl itself. 5908 return hasParsedAttr(S, PD.getAttributes(), Kind); 5909 } 5910 5911 /// Adjust the \c DeclContext for a function or variable that might be a 5912 /// function-local external declaration. 5913 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5914 if (!DC->isFunctionOrMethod()) 5915 return false; 5916 5917 // If this is a local extern function or variable declared within a function 5918 // template, don't add it into the enclosing namespace scope until it is 5919 // instantiated; it might have a dependent type right now. 5920 if (DC->isDependentContext()) 5921 return true; 5922 5923 // C++11 [basic.link]p7: 5924 // When a block scope declaration of an entity with linkage is not found to 5925 // refer to some other declaration, then that entity is a member of the 5926 // innermost enclosing namespace. 5927 // 5928 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5929 // semantically-enclosing namespace, not a lexically-enclosing one. 5930 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5931 DC = DC->getParent(); 5932 return true; 5933 } 5934 5935 /// \brief Returns true if given declaration has external C language linkage. 5936 static bool isDeclExternC(const Decl *D) { 5937 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5938 return FD->isExternC(); 5939 if (const auto *VD = dyn_cast<VarDecl>(D)) 5940 return VD->isExternC(); 5941 5942 llvm_unreachable("Unknown type of decl!"); 5943 } 5944 5945 NamedDecl *Sema::ActOnVariableDeclarator( 5946 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5947 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5948 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5949 QualType R = TInfo->getType(); 5950 DeclarationName Name = GetNameForDeclarator(D).getName(); 5951 5952 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5953 5954 if (D.isDecompositionDeclarator()) { 5955 AddToScope = false; 5956 // Take the name of the first declarator as our name for diagnostic 5957 // purposes. 5958 auto &Decomp = D.getDecompositionDeclarator(); 5959 if (!Decomp.bindings().empty()) { 5960 II = Decomp.bindings()[0].Name; 5961 Name = II; 5962 } 5963 } else if (!II) { 5964 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5965 << Name; 5966 return nullptr; 5967 } 5968 5969 if (getLangOpts().OpenCL) { 5970 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5971 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5972 // argument. 5973 if (R->isImageType() || R->isPipeType()) { 5974 Diag(D.getIdentifierLoc(), 5975 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5976 << R; 5977 D.setInvalidType(); 5978 return nullptr; 5979 } 5980 5981 // OpenCL v1.2 s6.9.r: 5982 // The event type cannot be used to declare a program scope variable. 5983 // OpenCL v2.0 s6.9.q: 5984 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 5985 if (NULL == S->getParent()) { 5986 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 5987 Diag(D.getIdentifierLoc(), 5988 diag::err_invalid_type_for_program_scope_var) << R; 5989 D.setInvalidType(); 5990 return nullptr; 5991 } 5992 } 5993 5994 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5995 QualType NR = R; 5996 while (NR->isPointerType()) { 5997 if (NR->isFunctionPointerType()) { 5998 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5999 D.setInvalidType(); 6000 break; 6001 } 6002 NR = NR->getPointeeType(); 6003 } 6004 6005 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6006 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6007 // half array type (unless the cl_khr_fp16 extension is enabled). 6008 if (Context.getBaseElementType(R)->isHalfType()) { 6009 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6010 D.setInvalidType(); 6011 } 6012 } 6013 6014 // OpenCL v1.2 s6.9.b p4: 6015 // The sampler type cannot be used with the __local and __global address 6016 // space qualifiers. 6017 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 6018 R.getAddressSpace() == LangAS::opencl_global)) { 6019 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6020 } 6021 6022 // OpenCL v1.2 s6.9.r: 6023 // The event type cannot be used with the __local, __constant and __global 6024 // address space qualifiers. 6025 if (R->isEventT()) { 6026 if (R.getAddressSpace()) { 6027 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6028 D.setInvalidType(); 6029 } 6030 } 6031 } 6032 6033 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6034 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6035 6036 // dllimport globals without explicit storage class are treated as extern. We 6037 // have to change the storage class this early to get the right DeclContext. 6038 if (SC == SC_None && !DC->isRecord() && 6039 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6040 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6041 SC = SC_Extern; 6042 6043 DeclContext *OriginalDC = DC; 6044 bool IsLocalExternDecl = SC == SC_Extern && 6045 adjustContextForLocalExternDecl(DC); 6046 6047 if (SCSpec == DeclSpec::SCS_mutable) { 6048 // mutable can only appear on non-static class members, so it's always 6049 // an error here 6050 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6051 D.setInvalidType(); 6052 SC = SC_None; 6053 } 6054 6055 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6056 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6057 D.getDeclSpec().getStorageClassSpecLoc())) { 6058 // In C++11, the 'register' storage class specifier is deprecated. 6059 // Suppress the warning in system macros, it's used in macros in some 6060 // popular C system headers, such as in glibc's htonl() macro. 6061 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6062 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6063 : diag::warn_deprecated_register) 6064 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6065 } 6066 6067 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6068 6069 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6070 // C99 6.9p2: The storage-class specifiers auto and register shall not 6071 // appear in the declaration specifiers in an external declaration. 6072 // Global Register+Asm is a GNU extension we support. 6073 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6074 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6075 D.setInvalidType(); 6076 } 6077 } 6078 6079 bool IsExplicitSpecialization = false; 6080 bool IsVariableTemplateSpecialization = false; 6081 bool IsPartialSpecialization = false; 6082 bool IsVariableTemplate = false; 6083 VarDecl *NewVD = nullptr; 6084 VarTemplateDecl *NewTemplate = nullptr; 6085 TemplateParameterList *TemplateParams = nullptr; 6086 if (!getLangOpts().CPlusPlus) { 6087 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6088 D.getIdentifierLoc(), II, 6089 R, TInfo, SC); 6090 6091 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6092 ParsingInitForAutoVars.insert(NewVD); 6093 6094 if (D.isInvalidType()) 6095 NewVD->setInvalidDecl(); 6096 } else { 6097 bool Invalid = false; 6098 6099 if (DC->isRecord() && !CurContext->isRecord()) { 6100 // This is an out-of-line definition of a static data member. 6101 switch (SC) { 6102 case SC_None: 6103 break; 6104 case SC_Static: 6105 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6106 diag::err_static_out_of_line) 6107 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6108 break; 6109 case SC_Auto: 6110 case SC_Register: 6111 case SC_Extern: 6112 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6113 // to names of variables declared in a block or to function parameters. 6114 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6115 // of class members 6116 6117 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6118 diag::err_storage_class_for_static_member) 6119 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6120 break; 6121 case SC_PrivateExtern: 6122 llvm_unreachable("C storage class in c++!"); 6123 } 6124 } 6125 6126 if (SC == SC_Static && CurContext->isRecord()) { 6127 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6128 if (RD->isLocalClass()) 6129 Diag(D.getIdentifierLoc(), 6130 diag::err_static_data_member_not_allowed_in_local_class) 6131 << Name << RD->getDeclName(); 6132 6133 // C++98 [class.union]p1: If a union contains a static data member, 6134 // the program is ill-formed. C++11 drops this restriction. 6135 if (RD->isUnion()) 6136 Diag(D.getIdentifierLoc(), 6137 getLangOpts().CPlusPlus11 6138 ? diag::warn_cxx98_compat_static_data_member_in_union 6139 : diag::ext_static_data_member_in_union) << Name; 6140 // We conservatively disallow static data members in anonymous structs. 6141 else if (!RD->getDeclName()) 6142 Diag(D.getIdentifierLoc(), 6143 diag::err_static_data_member_not_allowed_in_anon_struct) 6144 << Name << RD->isUnion(); 6145 } 6146 } 6147 6148 // Match up the template parameter lists with the scope specifier, then 6149 // determine whether we have a template or a template specialization. 6150 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6151 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6152 D.getCXXScopeSpec(), 6153 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6154 ? D.getName().TemplateId 6155 : nullptr, 6156 TemplateParamLists, 6157 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6158 6159 if (TemplateParams) { 6160 if (!TemplateParams->size() && 6161 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6162 // There is an extraneous 'template<>' for this variable. Complain 6163 // about it, but allow the declaration of the variable. 6164 Diag(TemplateParams->getTemplateLoc(), 6165 diag::err_template_variable_noparams) 6166 << II 6167 << SourceRange(TemplateParams->getTemplateLoc(), 6168 TemplateParams->getRAngleLoc()); 6169 TemplateParams = nullptr; 6170 } else { 6171 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6172 // This is an explicit specialization or a partial specialization. 6173 // FIXME: Check that we can declare a specialization here. 6174 IsVariableTemplateSpecialization = true; 6175 IsPartialSpecialization = TemplateParams->size() > 0; 6176 } else { // if (TemplateParams->size() > 0) 6177 // This is a template declaration. 6178 IsVariableTemplate = true; 6179 6180 // Check that we can declare a template here. 6181 if (CheckTemplateDeclScope(S, TemplateParams)) 6182 return nullptr; 6183 6184 // Only C++1y supports variable templates (N3651). 6185 Diag(D.getIdentifierLoc(), 6186 getLangOpts().CPlusPlus14 6187 ? diag::warn_cxx11_compat_variable_template 6188 : diag::ext_variable_template); 6189 } 6190 } 6191 } else { 6192 assert( 6193 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6194 "should have a 'template<>' for this decl"); 6195 } 6196 6197 if (IsVariableTemplateSpecialization) { 6198 SourceLocation TemplateKWLoc = 6199 TemplateParamLists.size() > 0 6200 ? TemplateParamLists[0]->getTemplateLoc() 6201 : SourceLocation(); 6202 DeclResult Res = ActOnVarTemplateSpecialization( 6203 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6204 IsPartialSpecialization); 6205 if (Res.isInvalid()) 6206 return nullptr; 6207 NewVD = cast<VarDecl>(Res.get()); 6208 AddToScope = false; 6209 } else if (D.isDecompositionDeclarator()) { 6210 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6211 D.getIdentifierLoc(), R, TInfo, SC, 6212 Bindings); 6213 } else 6214 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6215 D.getIdentifierLoc(), II, R, TInfo, SC); 6216 6217 // If this is supposed to be a variable template, create it as such. 6218 if (IsVariableTemplate) { 6219 NewTemplate = 6220 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6221 TemplateParams, NewVD); 6222 NewVD->setDescribedVarTemplate(NewTemplate); 6223 } 6224 6225 // If this decl has an auto type in need of deduction, make a note of the 6226 // Decl so we can diagnose uses of it in its own initializer. 6227 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6228 ParsingInitForAutoVars.insert(NewVD); 6229 6230 if (D.isInvalidType() || Invalid) { 6231 NewVD->setInvalidDecl(); 6232 if (NewTemplate) 6233 NewTemplate->setInvalidDecl(); 6234 } 6235 6236 SetNestedNameSpecifier(NewVD, D); 6237 6238 // If we have any template parameter lists that don't directly belong to 6239 // the variable (matching the scope specifier), store them. 6240 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6241 if (TemplateParamLists.size() > VDTemplateParamLists) 6242 NewVD->setTemplateParameterListsInfo( 6243 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6244 6245 if (D.getDeclSpec().isConstexprSpecified()) { 6246 NewVD->setConstexpr(true); 6247 // C++1z [dcl.spec.constexpr]p1: 6248 // A static data member declared with the constexpr specifier is 6249 // implicitly an inline variable. 6250 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6251 NewVD->setImplicitlyInline(); 6252 } 6253 6254 if (D.getDeclSpec().isConceptSpecified()) { 6255 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6256 VTD->setConcept(); 6257 6258 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6259 // be declared with the thread_local, inline, friend, or constexpr 6260 // specifiers, [...] 6261 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6262 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6263 diag::err_concept_decl_invalid_specifiers) 6264 << 0 << 0; 6265 NewVD->setInvalidDecl(true); 6266 } 6267 6268 if (D.getDeclSpec().isConstexprSpecified()) { 6269 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6270 diag::err_concept_decl_invalid_specifiers) 6271 << 0 << 3; 6272 NewVD->setInvalidDecl(true); 6273 } 6274 6275 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6276 // applied only to the definition of a function template or variable 6277 // template, declared in namespace scope. 6278 if (IsVariableTemplateSpecialization) { 6279 Diag(D.getDeclSpec().getConceptSpecLoc(), 6280 diag::err_concept_specified_specialization) 6281 << (IsPartialSpecialization ? 2 : 1); 6282 } 6283 6284 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6285 // following restrictions: 6286 // - The declared type shall have the type bool. 6287 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6288 !NewVD->isInvalidDecl()) { 6289 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6290 NewVD->setInvalidDecl(true); 6291 } 6292 } 6293 } 6294 6295 if (D.getDeclSpec().isInlineSpecified()) { 6296 if (!getLangOpts().CPlusPlus) { 6297 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6298 << 0; 6299 } else if (CurContext->isFunctionOrMethod()) { 6300 // 'inline' is not allowed on block scope variable declaration. 6301 Diag(D.getDeclSpec().getInlineSpecLoc(), 6302 diag::err_inline_declaration_block_scope) << Name 6303 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6304 } else { 6305 Diag(D.getDeclSpec().getInlineSpecLoc(), 6306 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6307 : diag::ext_inline_variable); 6308 NewVD->setInlineSpecified(); 6309 } 6310 } 6311 6312 // Set the lexical context. If the declarator has a C++ scope specifier, the 6313 // lexical context will be different from the semantic context. 6314 NewVD->setLexicalDeclContext(CurContext); 6315 if (NewTemplate) 6316 NewTemplate->setLexicalDeclContext(CurContext); 6317 6318 if (IsLocalExternDecl) { 6319 if (D.isDecompositionDeclarator()) 6320 for (auto *B : Bindings) 6321 B->setLocalExternDecl(); 6322 else 6323 NewVD->setLocalExternDecl(); 6324 } 6325 6326 bool EmitTLSUnsupportedError = false; 6327 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6328 // C++11 [dcl.stc]p4: 6329 // When thread_local is applied to a variable of block scope the 6330 // storage-class-specifier static is implied if it does not appear 6331 // explicitly. 6332 // Core issue: 'static' is not implied if the variable is declared 6333 // 'extern'. 6334 if (NewVD->hasLocalStorage() && 6335 (SCSpec != DeclSpec::SCS_unspecified || 6336 TSCS != DeclSpec::TSCS_thread_local || 6337 !DC->isFunctionOrMethod())) 6338 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6339 diag::err_thread_non_global) 6340 << DeclSpec::getSpecifierName(TSCS); 6341 else if (!Context.getTargetInfo().isTLSSupported()) { 6342 if (getLangOpts().CUDA) { 6343 // Postpone error emission until we've collected attributes required to 6344 // figure out whether it's a host or device variable and whether the 6345 // error should be ignored. 6346 EmitTLSUnsupportedError = true; 6347 // We still need to mark the variable as TLS so it shows up in AST with 6348 // proper storage class for other tools to use even if we're not going 6349 // to emit any code for it. 6350 NewVD->setTSCSpec(TSCS); 6351 } else 6352 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6353 diag::err_thread_unsupported); 6354 } else 6355 NewVD->setTSCSpec(TSCS); 6356 } 6357 6358 // C99 6.7.4p3 6359 // An inline definition of a function with external linkage shall 6360 // not contain a definition of a modifiable object with static or 6361 // thread storage duration... 6362 // We only apply this when the function is required to be defined 6363 // elsewhere, i.e. when the function is not 'extern inline'. Note 6364 // that a local variable with thread storage duration still has to 6365 // be marked 'static'. Also note that it's possible to get these 6366 // semantics in C++ using __attribute__((gnu_inline)). 6367 if (SC == SC_Static && S->getFnParent() != nullptr && 6368 !NewVD->getType().isConstQualified()) { 6369 FunctionDecl *CurFD = getCurFunctionDecl(); 6370 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6371 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6372 diag::warn_static_local_in_extern_inline); 6373 MaybeSuggestAddingStaticToDecl(CurFD); 6374 } 6375 } 6376 6377 if (D.getDeclSpec().isModulePrivateSpecified()) { 6378 if (IsVariableTemplateSpecialization) 6379 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6380 << (IsPartialSpecialization ? 1 : 0) 6381 << FixItHint::CreateRemoval( 6382 D.getDeclSpec().getModulePrivateSpecLoc()); 6383 else if (IsExplicitSpecialization) 6384 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6385 << 2 6386 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6387 else if (NewVD->hasLocalStorage()) 6388 Diag(NewVD->getLocation(), diag::err_module_private_local) 6389 << 0 << NewVD->getDeclName() 6390 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6391 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6392 else { 6393 NewVD->setModulePrivate(); 6394 if (NewTemplate) 6395 NewTemplate->setModulePrivate(); 6396 for (auto *B : Bindings) 6397 B->setModulePrivate(); 6398 } 6399 } 6400 6401 // Handle attributes prior to checking for duplicates in MergeVarDecl 6402 ProcessDeclAttributes(S, NewVD, D); 6403 6404 if (getLangOpts().CUDA) { 6405 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6406 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6407 diag::err_thread_unsupported); 6408 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6409 // storage [duration]." 6410 if (SC == SC_None && S->getFnParent() != nullptr && 6411 (NewVD->hasAttr<CUDASharedAttr>() || 6412 NewVD->hasAttr<CUDAConstantAttr>())) { 6413 NewVD->setStorageClass(SC_Static); 6414 } 6415 } 6416 6417 // Ensure that dllimport globals without explicit storage class are treated as 6418 // extern. The storage class is set above using parsed attributes. Now we can 6419 // check the VarDecl itself. 6420 assert(!NewVD->hasAttr<DLLImportAttr>() || 6421 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6422 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6423 6424 // In auto-retain/release, infer strong retension for variables of 6425 // retainable type. 6426 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6427 NewVD->setInvalidDecl(); 6428 6429 // Handle GNU asm-label extension (encoded as an attribute). 6430 if (Expr *E = (Expr*)D.getAsmLabel()) { 6431 // The parser guarantees this is a string. 6432 StringLiteral *SE = cast<StringLiteral>(E); 6433 StringRef Label = SE->getString(); 6434 if (S->getFnParent() != nullptr) { 6435 switch (SC) { 6436 case SC_None: 6437 case SC_Auto: 6438 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6439 break; 6440 case SC_Register: 6441 // Local Named register 6442 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6443 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6444 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6445 break; 6446 case SC_Static: 6447 case SC_Extern: 6448 case SC_PrivateExtern: 6449 break; 6450 } 6451 } else if (SC == SC_Register) { 6452 // Global Named register 6453 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6454 const auto &TI = Context.getTargetInfo(); 6455 bool HasSizeMismatch; 6456 6457 if (!TI.isValidGCCRegisterName(Label)) 6458 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6459 else if (!TI.validateGlobalRegisterVariable(Label, 6460 Context.getTypeSize(R), 6461 HasSizeMismatch)) 6462 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6463 else if (HasSizeMismatch) 6464 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6465 } 6466 6467 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6468 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6469 NewVD->setInvalidDecl(true); 6470 } 6471 } 6472 6473 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6474 Context, Label, 0)); 6475 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6476 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6477 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6478 if (I != ExtnameUndeclaredIdentifiers.end()) { 6479 if (isDeclExternC(NewVD)) { 6480 NewVD->addAttr(I->second); 6481 ExtnameUndeclaredIdentifiers.erase(I); 6482 } else 6483 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6484 << /*Variable*/1 << NewVD; 6485 } 6486 } 6487 6488 // Find the shadowed declaration before filtering for scope. 6489 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6490 ? getShadowedDeclaration(NewVD, Previous) 6491 : nullptr; 6492 6493 // Don't consider existing declarations that are in a different 6494 // scope and are out-of-semantic-context declarations (if the new 6495 // declaration has linkage). 6496 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6497 D.getCXXScopeSpec().isNotEmpty() || 6498 IsExplicitSpecialization || 6499 IsVariableTemplateSpecialization); 6500 6501 // Check whether the previous declaration is in the same block scope. This 6502 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6503 if (getLangOpts().CPlusPlus && 6504 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6505 NewVD->setPreviousDeclInSameBlockScope( 6506 Previous.isSingleResult() && !Previous.isShadowed() && 6507 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6508 6509 if (!getLangOpts().CPlusPlus) { 6510 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6511 } else { 6512 // If this is an explicit specialization of a static data member, check it. 6513 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6514 CheckMemberSpecialization(NewVD, Previous)) 6515 NewVD->setInvalidDecl(); 6516 6517 // Merge the decl with the existing one if appropriate. 6518 if (!Previous.empty()) { 6519 if (Previous.isSingleResult() && 6520 isa<FieldDecl>(Previous.getFoundDecl()) && 6521 D.getCXXScopeSpec().isSet()) { 6522 // The user tried to define a non-static data member 6523 // out-of-line (C++ [dcl.meaning]p1). 6524 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6525 << D.getCXXScopeSpec().getRange(); 6526 Previous.clear(); 6527 NewVD->setInvalidDecl(); 6528 } 6529 } else if (D.getCXXScopeSpec().isSet()) { 6530 // No previous declaration in the qualifying scope. 6531 Diag(D.getIdentifierLoc(), diag::err_no_member) 6532 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6533 << D.getCXXScopeSpec().getRange(); 6534 NewVD->setInvalidDecl(); 6535 } 6536 6537 if (!IsVariableTemplateSpecialization) 6538 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6539 6540 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6541 // an explicit specialization (14.8.3) or a partial specialization of a 6542 // concept definition. 6543 if (IsVariableTemplateSpecialization && 6544 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6545 Previous.isSingleResult()) { 6546 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6547 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6548 if (VarTmpl->isConcept()) { 6549 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6550 << 1 /*variable*/ 6551 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6552 : 1 /*explicitly specialized*/); 6553 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6554 NewVD->setInvalidDecl(); 6555 } 6556 } 6557 } 6558 6559 if (NewTemplate) { 6560 VarTemplateDecl *PrevVarTemplate = 6561 NewVD->getPreviousDecl() 6562 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6563 : nullptr; 6564 6565 // Check the template parameter list of this declaration, possibly 6566 // merging in the template parameter list from the previous variable 6567 // template declaration. 6568 if (CheckTemplateParameterList( 6569 TemplateParams, 6570 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6571 : nullptr, 6572 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6573 DC->isDependentContext()) 6574 ? TPC_ClassTemplateMember 6575 : TPC_VarTemplate)) 6576 NewVD->setInvalidDecl(); 6577 6578 // If we are providing an explicit specialization of a static variable 6579 // template, make a note of that. 6580 if (PrevVarTemplate && 6581 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6582 PrevVarTemplate->setMemberSpecialization(); 6583 } 6584 } 6585 6586 // Diagnose shadowed variables iff this isn't a redeclaration. 6587 if (ShadowedDecl && !D.isRedeclaration()) 6588 CheckShadow(NewVD, ShadowedDecl, Previous); 6589 6590 ProcessPragmaWeak(S, NewVD); 6591 6592 // If this is the first declaration of an extern C variable, update 6593 // the map of such variables. 6594 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6595 isIncompleteDeclExternC(*this, NewVD)) 6596 RegisterLocallyScopedExternCDecl(NewVD, S); 6597 6598 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6599 Decl *ManglingContextDecl; 6600 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6601 NewVD->getDeclContext(), ManglingContextDecl)) { 6602 Context.setManglingNumber( 6603 NewVD, MCtx->getManglingNumber( 6604 NewVD, getMSManglingNumber(getLangOpts(), S))); 6605 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6606 } 6607 } 6608 6609 // Special handling of variable named 'main'. 6610 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6611 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6612 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6613 6614 // C++ [basic.start.main]p3 6615 // A program that declares a variable main at global scope is ill-formed. 6616 if (getLangOpts().CPlusPlus) 6617 Diag(D.getLocStart(), diag::err_main_global_variable); 6618 6619 // In C, and external-linkage variable named main results in undefined 6620 // behavior. 6621 else if (NewVD->hasExternalFormalLinkage()) 6622 Diag(D.getLocStart(), diag::warn_main_redefined); 6623 } 6624 6625 if (D.isRedeclaration() && !Previous.empty()) { 6626 checkDLLAttributeRedeclaration( 6627 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6628 IsExplicitSpecialization, D.isFunctionDefinition()); 6629 } 6630 6631 if (NewTemplate) { 6632 if (NewVD->isInvalidDecl()) 6633 NewTemplate->setInvalidDecl(); 6634 ActOnDocumentableDecl(NewTemplate); 6635 return NewTemplate; 6636 } 6637 6638 return NewVD; 6639 } 6640 6641 /// Enum describing the %select options in diag::warn_decl_shadow. 6642 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6643 6644 /// Determine what kind of declaration we're shadowing. 6645 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6646 const DeclContext *OldDC) { 6647 if (isa<RecordDecl>(OldDC)) 6648 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6649 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6650 } 6651 6652 /// Return the location of the capture if the given lambda captures the given 6653 /// variable \p VD, or an invalid source location otherwise. 6654 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6655 const VarDecl *VD) { 6656 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6657 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6658 return Capture.getLocation(); 6659 } 6660 return SourceLocation(); 6661 } 6662 6663 /// \brief Return the declaration shadowed by the given variable \p D, or null 6664 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6665 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6666 const LookupResult &R) { 6667 // Return if warning is ignored. 6668 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6669 return nullptr; 6670 6671 // Don't diagnose declarations at file scope. 6672 if (D->hasGlobalStorage()) 6673 return nullptr; 6674 6675 // Only diagnose if we're shadowing an unambiguous field or variable. 6676 if (R.getResultKind() != LookupResult::Found) 6677 return nullptr; 6678 6679 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6680 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6681 ? ShadowedDecl 6682 : nullptr; 6683 } 6684 6685 /// \brief Diagnose variable or built-in function shadowing. Implements 6686 /// -Wshadow. 6687 /// 6688 /// This method is called whenever a VarDecl is added to a "useful" 6689 /// scope. 6690 /// 6691 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6692 /// \param R the lookup of the name 6693 /// 6694 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl, 6695 const LookupResult &R) { 6696 DeclContext *NewDC = D->getDeclContext(); 6697 6698 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6699 // Fields are not shadowed by variables in C++ static methods. 6700 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6701 if (MD->isStatic()) 6702 return; 6703 6704 // Fields shadowed by constructor parameters are a special case. Usually 6705 // the constructor initializes the field with the parameter. 6706 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6707 // Remember that this was shadowed so we can either warn about its 6708 // modification or its existence depending on warning settings. 6709 D = D->getCanonicalDecl(); 6710 ShadowingDecls.insert({D, FD}); 6711 return; 6712 } 6713 } 6714 6715 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6716 if (shadowedVar->isExternC()) { 6717 // For shadowing external vars, make sure that we point to the global 6718 // declaration, not a locally scoped extern declaration. 6719 for (auto I : shadowedVar->redecls()) 6720 if (I->isFileVarDecl()) { 6721 ShadowedDecl = I; 6722 break; 6723 } 6724 } 6725 6726 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6727 6728 unsigned WarningDiag = diag::warn_decl_shadow; 6729 SourceLocation CaptureLoc; 6730 if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) { 6731 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6732 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6733 if (RD->getLambdaCaptureDefault() == LCD_None) { 6734 // Try to avoid warnings for lambdas with an explicit capture list. 6735 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6736 // Warn only when the lambda captures the shadowed decl explicitly. 6737 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6738 if (CaptureLoc.isInvalid()) 6739 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6740 } else { 6741 // Remember that this was shadowed so we can avoid the warning if the 6742 // shadowed decl isn't captured and the warning settings allow it. 6743 cast<LambdaScopeInfo>(getCurFunction()) 6744 ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)}); 6745 return; 6746 } 6747 } 6748 } 6749 } 6750 6751 // Only warn about certain kinds of shadowing for class members. 6752 if (NewDC && NewDC->isRecord()) { 6753 // In particular, don't warn about shadowing non-class members. 6754 if (!OldDC->isRecord()) 6755 return; 6756 6757 // TODO: should we warn about static data members shadowing 6758 // static data members from base classes? 6759 6760 // TODO: don't diagnose for inaccessible shadowed members. 6761 // This is hard to do perfectly because we might friend the 6762 // shadowing context, but that's just a false negative. 6763 } 6764 6765 6766 DeclarationName Name = R.getLookupName(); 6767 6768 // Emit warning and note. 6769 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6770 return; 6771 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6772 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6773 if (!CaptureLoc.isInvalid()) 6774 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6775 << Name << /*explicitly*/ 1; 6776 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6777 } 6778 6779 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6780 /// when these variables are captured by the lambda. 6781 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6782 for (const auto &Shadow : LSI->ShadowingDecls) { 6783 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 6784 // Try to avoid the warning when the shadowed decl isn't captured. 6785 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 6786 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6787 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 6788 ? diag::warn_decl_shadow_uncaptured_local 6789 : diag::warn_decl_shadow) 6790 << Shadow.VD->getDeclName() 6791 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 6792 if (!CaptureLoc.isInvalid()) 6793 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6794 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 6795 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6796 } 6797 } 6798 6799 /// \brief Check -Wshadow without the advantage of a previous lookup. 6800 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6801 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6802 return; 6803 6804 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6805 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6806 LookupName(R, S); 6807 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 6808 CheckShadow(D, ShadowedDecl, R); 6809 } 6810 6811 /// Check if 'E', which is an expression that is about to be modified, refers 6812 /// to a constructor parameter that shadows a field. 6813 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6814 // Quickly ignore expressions that can't be shadowing ctor parameters. 6815 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6816 return; 6817 E = E->IgnoreParenImpCasts(); 6818 auto *DRE = dyn_cast<DeclRefExpr>(E); 6819 if (!DRE) 6820 return; 6821 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6822 auto I = ShadowingDecls.find(D); 6823 if (I == ShadowingDecls.end()) 6824 return; 6825 const NamedDecl *ShadowedDecl = I->second; 6826 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6827 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6828 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6829 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6830 6831 // Avoid issuing multiple warnings about the same decl. 6832 ShadowingDecls.erase(I); 6833 } 6834 6835 /// Check for conflict between this global or extern "C" declaration and 6836 /// previous global or extern "C" declarations. This is only used in C++. 6837 template<typename T> 6838 static bool checkGlobalOrExternCConflict( 6839 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6840 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6841 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6842 6843 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6844 // The common case: this global doesn't conflict with any extern "C" 6845 // declaration. 6846 return false; 6847 } 6848 6849 if (Prev) { 6850 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6851 // Both the old and new declarations have C language linkage. This is a 6852 // redeclaration. 6853 Previous.clear(); 6854 Previous.addDecl(Prev); 6855 return true; 6856 } 6857 6858 // This is a global, non-extern "C" declaration, and there is a previous 6859 // non-global extern "C" declaration. Diagnose if this is a variable 6860 // declaration. 6861 if (!isa<VarDecl>(ND)) 6862 return false; 6863 } else { 6864 // The declaration is extern "C". Check for any declaration in the 6865 // translation unit which might conflict. 6866 if (IsGlobal) { 6867 // We have already performed the lookup into the translation unit. 6868 IsGlobal = false; 6869 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6870 I != E; ++I) { 6871 if (isa<VarDecl>(*I)) { 6872 Prev = *I; 6873 break; 6874 } 6875 } 6876 } else { 6877 DeclContext::lookup_result R = 6878 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6879 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6880 I != E; ++I) { 6881 if (isa<VarDecl>(*I)) { 6882 Prev = *I; 6883 break; 6884 } 6885 // FIXME: If we have any other entity with this name in global scope, 6886 // the declaration is ill-formed, but that is a defect: it breaks the 6887 // 'stat' hack, for instance. Only variables can have mangled name 6888 // clashes with extern "C" declarations, so only they deserve a 6889 // diagnostic. 6890 } 6891 } 6892 6893 if (!Prev) 6894 return false; 6895 } 6896 6897 // Use the first declaration's location to ensure we point at something which 6898 // is lexically inside an extern "C" linkage-spec. 6899 assert(Prev && "should have found a previous declaration to diagnose"); 6900 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6901 Prev = FD->getFirstDecl(); 6902 else 6903 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6904 6905 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6906 << IsGlobal << ND; 6907 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6908 << IsGlobal; 6909 return false; 6910 } 6911 6912 /// Apply special rules for handling extern "C" declarations. Returns \c true 6913 /// if we have found that this is a redeclaration of some prior entity. 6914 /// 6915 /// Per C++ [dcl.link]p6: 6916 /// Two declarations [for a function or variable] with C language linkage 6917 /// with the same name that appear in different scopes refer to the same 6918 /// [entity]. An entity with C language linkage shall not be declared with 6919 /// the same name as an entity in global scope. 6920 template<typename T> 6921 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6922 LookupResult &Previous) { 6923 if (!S.getLangOpts().CPlusPlus) { 6924 // In C, when declaring a global variable, look for a corresponding 'extern' 6925 // variable declared in function scope. We don't need this in C++, because 6926 // we find local extern decls in the surrounding file-scope DeclContext. 6927 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6928 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6929 Previous.clear(); 6930 Previous.addDecl(Prev); 6931 return true; 6932 } 6933 } 6934 return false; 6935 } 6936 6937 // A declaration in the translation unit can conflict with an extern "C" 6938 // declaration. 6939 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6940 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6941 6942 // An extern "C" declaration can conflict with a declaration in the 6943 // translation unit or can be a redeclaration of an extern "C" declaration 6944 // in another scope. 6945 if (isIncompleteDeclExternC(S,ND)) 6946 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6947 6948 // Neither global nor extern "C": nothing to do. 6949 return false; 6950 } 6951 6952 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6953 // If the decl is already known invalid, don't check it. 6954 if (NewVD->isInvalidDecl()) 6955 return; 6956 6957 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6958 QualType T = TInfo->getType(); 6959 6960 // Defer checking an 'auto' type until its initializer is attached. 6961 if (T->isUndeducedType()) 6962 return; 6963 6964 if (NewVD->hasAttrs()) 6965 CheckAlignasUnderalignment(NewVD); 6966 6967 if (T->isObjCObjectType()) { 6968 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6969 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6970 T = Context.getObjCObjectPointerType(T); 6971 NewVD->setType(T); 6972 } 6973 6974 // Emit an error if an address space was applied to decl with local storage. 6975 // This includes arrays of objects with address space qualifiers, but not 6976 // automatic variables that point to other address spaces. 6977 // ISO/IEC TR 18037 S5.1.2 6978 if (!getLangOpts().OpenCL 6979 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6980 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6981 NewVD->setInvalidDecl(); 6982 return; 6983 } 6984 6985 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6986 // scope. 6987 if (getLangOpts().OpenCLVersion == 120 && 6988 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 6989 NewVD->isStaticLocal()) { 6990 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6991 NewVD->setInvalidDecl(); 6992 return; 6993 } 6994 6995 if (getLangOpts().OpenCL) { 6996 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6997 if (NewVD->hasAttr<BlocksAttr>()) { 6998 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6999 return; 7000 } 7001 7002 if (T->isBlockPointerType()) { 7003 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7004 // can't use 'extern' storage class. 7005 if (!T.isConstQualified()) { 7006 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7007 << 0 /*const*/; 7008 NewVD->setInvalidDecl(); 7009 return; 7010 } 7011 if (NewVD->hasExternalStorage()) { 7012 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7013 NewVD->setInvalidDecl(); 7014 return; 7015 } 7016 } 7017 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7018 // __constant address space. 7019 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7020 // variables inside a function can also be declared in the global 7021 // address space. 7022 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7023 NewVD->hasExternalStorage()) { 7024 if (!T->isSamplerT() && 7025 !(T.getAddressSpace() == LangAS::opencl_constant || 7026 (T.getAddressSpace() == LangAS::opencl_global && 7027 getLangOpts().OpenCLVersion == 200))) { 7028 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7029 if (getLangOpts().OpenCLVersion == 200) 7030 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7031 << Scope << "global or constant"; 7032 else 7033 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7034 << Scope << "constant"; 7035 NewVD->setInvalidDecl(); 7036 return; 7037 } 7038 } else { 7039 if (T.getAddressSpace() == LangAS::opencl_global) { 7040 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7041 << 1 /*is any function*/ << "global"; 7042 NewVD->setInvalidDecl(); 7043 return; 7044 } 7045 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7046 // in functions. 7047 if (T.getAddressSpace() == LangAS::opencl_constant || 7048 T.getAddressSpace() == LangAS::opencl_local) { 7049 FunctionDecl *FD = getCurFunctionDecl(); 7050 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7051 if (T.getAddressSpace() == LangAS::opencl_constant) 7052 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7053 << 0 /*non-kernel only*/ << "constant"; 7054 else 7055 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7056 << 0 /*non-kernel only*/ << "local"; 7057 NewVD->setInvalidDecl(); 7058 return; 7059 } 7060 } 7061 } 7062 } 7063 7064 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7065 && !NewVD->hasAttr<BlocksAttr>()) { 7066 if (getLangOpts().getGC() != LangOptions::NonGC) 7067 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7068 else { 7069 assert(!getLangOpts().ObjCAutoRefCount); 7070 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7071 } 7072 } 7073 7074 bool isVM = T->isVariablyModifiedType(); 7075 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7076 NewVD->hasAttr<BlocksAttr>()) 7077 getCurFunction()->setHasBranchProtectedScope(); 7078 7079 if ((isVM && NewVD->hasLinkage()) || 7080 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7081 bool SizeIsNegative; 7082 llvm::APSInt Oversized; 7083 TypeSourceInfo *FixedTInfo = 7084 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7085 SizeIsNegative, Oversized); 7086 if (!FixedTInfo && T->isVariableArrayType()) { 7087 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7088 // FIXME: This won't give the correct result for 7089 // int a[10][n]; 7090 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7091 7092 if (NewVD->isFileVarDecl()) 7093 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7094 << SizeRange; 7095 else if (NewVD->isStaticLocal()) 7096 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7097 << SizeRange; 7098 else 7099 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7100 << SizeRange; 7101 NewVD->setInvalidDecl(); 7102 return; 7103 } 7104 7105 if (!FixedTInfo) { 7106 if (NewVD->isFileVarDecl()) 7107 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7108 else 7109 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7110 NewVD->setInvalidDecl(); 7111 return; 7112 } 7113 7114 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7115 NewVD->setType(FixedTInfo->getType()); 7116 NewVD->setTypeSourceInfo(FixedTInfo); 7117 } 7118 7119 if (T->isVoidType()) { 7120 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7121 // of objects and functions. 7122 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7123 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7124 << T; 7125 NewVD->setInvalidDecl(); 7126 return; 7127 } 7128 } 7129 7130 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7131 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7132 NewVD->setInvalidDecl(); 7133 return; 7134 } 7135 7136 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7137 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7138 NewVD->setInvalidDecl(); 7139 return; 7140 } 7141 7142 if (NewVD->isConstexpr() && !T->isDependentType() && 7143 RequireLiteralType(NewVD->getLocation(), T, 7144 diag::err_constexpr_var_non_literal)) { 7145 NewVD->setInvalidDecl(); 7146 return; 7147 } 7148 } 7149 7150 /// \brief Perform semantic checking on a newly-created variable 7151 /// declaration. 7152 /// 7153 /// This routine performs all of the type-checking required for a 7154 /// variable declaration once it has been built. It is used both to 7155 /// check variables after they have been parsed and their declarators 7156 /// have been translated into a declaration, and to check variables 7157 /// that have been instantiated from a template. 7158 /// 7159 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7160 /// 7161 /// Returns true if the variable declaration is a redeclaration. 7162 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7163 CheckVariableDeclarationType(NewVD); 7164 7165 // If the decl is already known invalid, don't check it. 7166 if (NewVD->isInvalidDecl()) 7167 return false; 7168 7169 // If we did not find anything by this name, look for a non-visible 7170 // extern "C" declaration with the same name. 7171 if (Previous.empty() && 7172 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7173 Previous.setShadowed(); 7174 7175 if (!Previous.empty()) { 7176 MergeVarDecl(NewVD, Previous); 7177 return true; 7178 } 7179 return false; 7180 } 7181 7182 namespace { 7183 struct FindOverriddenMethod { 7184 Sema *S; 7185 CXXMethodDecl *Method; 7186 7187 /// Member lookup function that determines whether a given C++ 7188 /// method overrides a method in a base class, to be used with 7189 /// CXXRecordDecl::lookupInBases(). 7190 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7191 RecordDecl *BaseRecord = 7192 Specifier->getType()->getAs<RecordType>()->getDecl(); 7193 7194 DeclarationName Name = Method->getDeclName(); 7195 7196 // FIXME: Do we care about other names here too? 7197 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7198 // We really want to find the base class destructor here. 7199 QualType T = S->Context.getTypeDeclType(BaseRecord); 7200 CanQualType CT = S->Context.getCanonicalType(T); 7201 7202 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7203 } 7204 7205 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7206 Path.Decls = Path.Decls.slice(1)) { 7207 NamedDecl *D = Path.Decls.front(); 7208 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7209 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7210 return true; 7211 } 7212 } 7213 7214 return false; 7215 } 7216 }; 7217 7218 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7219 } // end anonymous namespace 7220 7221 /// \brief Report an error regarding overriding, along with any relevant 7222 /// overriden methods. 7223 /// 7224 /// \param DiagID the primary error to report. 7225 /// \param MD the overriding method. 7226 /// \param OEK which overrides to include as notes. 7227 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7228 OverrideErrorKind OEK = OEK_All) { 7229 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7230 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7231 E = MD->end_overridden_methods(); 7232 I != E; ++I) { 7233 // This check (& the OEK parameter) could be replaced by a predicate, but 7234 // without lambdas that would be overkill. This is still nicer than writing 7235 // out the diag loop 3 times. 7236 if ((OEK == OEK_All) || 7237 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7238 (OEK == OEK_Deleted && (*I)->isDeleted())) 7239 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7240 } 7241 } 7242 7243 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7244 /// and if so, check that it's a valid override and remember it. 7245 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7246 // Look for methods in base classes that this method might override. 7247 CXXBasePaths Paths; 7248 FindOverriddenMethod FOM; 7249 FOM.Method = MD; 7250 FOM.S = this; 7251 bool hasDeletedOverridenMethods = false; 7252 bool hasNonDeletedOverridenMethods = false; 7253 bool AddedAny = false; 7254 if (DC->lookupInBases(FOM, Paths)) { 7255 for (auto *I : Paths.found_decls()) { 7256 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7257 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7258 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7259 !CheckOverridingFunctionAttributes(MD, OldMD) && 7260 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7261 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7262 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7263 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7264 AddedAny = true; 7265 } 7266 } 7267 } 7268 } 7269 7270 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7271 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7272 } 7273 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7274 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7275 } 7276 7277 return AddedAny; 7278 } 7279 7280 namespace { 7281 // Struct for holding all of the extra arguments needed by 7282 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7283 struct ActOnFDArgs { 7284 Scope *S; 7285 Declarator &D; 7286 MultiTemplateParamsArg TemplateParamLists; 7287 bool AddToScope; 7288 }; 7289 } // end anonymous namespace 7290 7291 namespace { 7292 7293 // Callback to only accept typo corrections that have a non-zero edit distance. 7294 // Also only accept corrections that have the same parent decl. 7295 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7296 public: 7297 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7298 CXXRecordDecl *Parent) 7299 : Context(Context), OriginalFD(TypoFD), 7300 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7301 7302 bool ValidateCandidate(const TypoCorrection &candidate) override { 7303 if (candidate.getEditDistance() == 0) 7304 return false; 7305 7306 SmallVector<unsigned, 1> MismatchedParams; 7307 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7308 CDeclEnd = candidate.end(); 7309 CDecl != CDeclEnd; ++CDecl) { 7310 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7311 7312 if (FD && !FD->hasBody() && 7313 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7314 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7315 CXXRecordDecl *Parent = MD->getParent(); 7316 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7317 return true; 7318 } else if (!ExpectedParent) { 7319 return true; 7320 } 7321 } 7322 } 7323 7324 return false; 7325 } 7326 7327 private: 7328 ASTContext &Context; 7329 FunctionDecl *OriginalFD; 7330 CXXRecordDecl *ExpectedParent; 7331 }; 7332 7333 } // end anonymous namespace 7334 7335 /// \brief Generate diagnostics for an invalid function redeclaration. 7336 /// 7337 /// This routine handles generating the diagnostic messages for an invalid 7338 /// function redeclaration, including finding possible similar declarations 7339 /// or performing typo correction if there are no previous declarations with 7340 /// the same name. 7341 /// 7342 /// Returns a NamedDecl iff typo correction was performed and substituting in 7343 /// the new declaration name does not cause new errors. 7344 static NamedDecl *DiagnoseInvalidRedeclaration( 7345 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7346 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7347 DeclarationName Name = NewFD->getDeclName(); 7348 DeclContext *NewDC = NewFD->getDeclContext(); 7349 SmallVector<unsigned, 1> MismatchedParams; 7350 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7351 TypoCorrection Correction; 7352 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7353 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7354 : diag::err_member_decl_does_not_match; 7355 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7356 IsLocalFriend ? Sema::LookupLocalFriendName 7357 : Sema::LookupOrdinaryName, 7358 Sema::ForRedeclaration); 7359 7360 NewFD->setInvalidDecl(); 7361 if (IsLocalFriend) 7362 SemaRef.LookupName(Prev, S); 7363 else 7364 SemaRef.LookupQualifiedName(Prev, NewDC); 7365 assert(!Prev.isAmbiguous() && 7366 "Cannot have an ambiguity in previous-declaration lookup"); 7367 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7368 if (!Prev.empty()) { 7369 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7370 Func != FuncEnd; ++Func) { 7371 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7372 if (FD && 7373 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7374 // Add 1 to the index so that 0 can mean the mismatch didn't 7375 // involve a parameter 7376 unsigned ParamNum = 7377 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7378 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7379 } 7380 } 7381 // If the qualified name lookup yielded nothing, try typo correction 7382 } else if ((Correction = SemaRef.CorrectTypo( 7383 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7384 &ExtraArgs.D.getCXXScopeSpec(), 7385 llvm::make_unique<DifferentNameValidatorCCC>( 7386 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7387 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7388 // Set up everything for the call to ActOnFunctionDeclarator 7389 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7390 ExtraArgs.D.getIdentifierLoc()); 7391 Previous.clear(); 7392 Previous.setLookupName(Correction.getCorrection()); 7393 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7394 CDeclEnd = Correction.end(); 7395 CDecl != CDeclEnd; ++CDecl) { 7396 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7397 if (FD && !FD->hasBody() && 7398 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7399 Previous.addDecl(FD); 7400 } 7401 } 7402 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7403 7404 NamedDecl *Result; 7405 // Retry building the function declaration with the new previous 7406 // declarations, and with errors suppressed. 7407 { 7408 // Trap errors. 7409 Sema::SFINAETrap Trap(SemaRef); 7410 7411 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7412 // pieces need to verify the typo-corrected C++ declaration and hopefully 7413 // eliminate the need for the parameter pack ExtraArgs. 7414 Result = SemaRef.ActOnFunctionDeclarator( 7415 ExtraArgs.S, ExtraArgs.D, 7416 Correction.getCorrectionDecl()->getDeclContext(), 7417 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7418 ExtraArgs.AddToScope); 7419 7420 if (Trap.hasErrorOccurred()) 7421 Result = nullptr; 7422 } 7423 7424 if (Result) { 7425 // Determine which correction we picked. 7426 Decl *Canonical = Result->getCanonicalDecl(); 7427 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7428 I != E; ++I) 7429 if ((*I)->getCanonicalDecl() == Canonical) 7430 Correction.setCorrectionDecl(*I); 7431 7432 SemaRef.diagnoseTypo( 7433 Correction, 7434 SemaRef.PDiag(IsLocalFriend 7435 ? diag::err_no_matching_local_friend_suggest 7436 : diag::err_member_decl_does_not_match_suggest) 7437 << Name << NewDC << IsDefinition); 7438 return Result; 7439 } 7440 7441 // Pretend the typo correction never occurred 7442 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7443 ExtraArgs.D.getIdentifierLoc()); 7444 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7445 Previous.clear(); 7446 Previous.setLookupName(Name); 7447 } 7448 7449 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7450 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7451 7452 bool NewFDisConst = false; 7453 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7454 NewFDisConst = NewMD->isConst(); 7455 7456 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7457 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7458 NearMatch != NearMatchEnd; ++NearMatch) { 7459 FunctionDecl *FD = NearMatch->first; 7460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7461 bool FDisConst = MD && MD->isConst(); 7462 bool IsMember = MD || !IsLocalFriend; 7463 7464 // FIXME: These notes are poorly worded for the local friend case. 7465 if (unsigned Idx = NearMatch->second) { 7466 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7467 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7468 if (Loc.isInvalid()) Loc = FD->getLocation(); 7469 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7470 : diag::note_local_decl_close_param_match) 7471 << Idx << FDParam->getType() 7472 << NewFD->getParamDecl(Idx - 1)->getType(); 7473 } else if (FDisConst != NewFDisConst) { 7474 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7475 << NewFDisConst << FD->getSourceRange().getEnd(); 7476 } else 7477 SemaRef.Diag(FD->getLocation(), 7478 IsMember ? diag::note_member_def_close_match 7479 : diag::note_local_decl_close_match); 7480 } 7481 return nullptr; 7482 } 7483 7484 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7485 switch (D.getDeclSpec().getStorageClassSpec()) { 7486 default: llvm_unreachable("Unknown storage class!"); 7487 case DeclSpec::SCS_auto: 7488 case DeclSpec::SCS_register: 7489 case DeclSpec::SCS_mutable: 7490 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7491 diag::err_typecheck_sclass_func); 7492 D.setInvalidType(); 7493 break; 7494 case DeclSpec::SCS_unspecified: break; 7495 case DeclSpec::SCS_extern: 7496 if (D.getDeclSpec().isExternInLinkageSpec()) 7497 return SC_None; 7498 return SC_Extern; 7499 case DeclSpec::SCS_static: { 7500 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7501 // C99 6.7.1p5: 7502 // The declaration of an identifier for a function that has 7503 // block scope shall have no explicit storage-class specifier 7504 // other than extern 7505 // See also (C++ [dcl.stc]p4). 7506 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7507 diag::err_static_block_func); 7508 break; 7509 } else 7510 return SC_Static; 7511 } 7512 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7513 } 7514 7515 // No explicit storage class has already been returned 7516 return SC_None; 7517 } 7518 7519 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7520 DeclContext *DC, QualType &R, 7521 TypeSourceInfo *TInfo, 7522 StorageClass SC, 7523 bool &IsVirtualOkay) { 7524 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7525 DeclarationName Name = NameInfo.getName(); 7526 7527 FunctionDecl *NewFD = nullptr; 7528 bool isInline = D.getDeclSpec().isInlineSpecified(); 7529 7530 if (!SemaRef.getLangOpts().CPlusPlus) { 7531 // Determine whether the function was written with a 7532 // prototype. This true when: 7533 // - there is a prototype in the declarator, or 7534 // - the type R of the function is some kind of typedef or other reference 7535 // to a type name (which eventually refers to a function type). 7536 bool HasPrototype = 7537 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7538 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7539 7540 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7541 D.getLocStart(), NameInfo, R, 7542 TInfo, SC, isInline, 7543 HasPrototype, false); 7544 if (D.isInvalidType()) 7545 NewFD->setInvalidDecl(); 7546 7547 return NewFD; 7548 } 7549 7550 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7551 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7552 7553 // Check that the return type is not an abstract class type. 7554 // For record types, this is done by the AbstractClassUsageDiagnoser once 7555 // the class has been completely parsed. 7556 if (!DC->isRecord() && 7557 SemaRef.RequireNonAbstractType( 7558 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7559 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7560 D.setInvalidType(); 7561 7562 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7563 // This is a C++ constructor declaration. 7564 assert(DC->isRecord() && 7565 "Constructors can only be declared in a member context"); 7566 7567 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7568 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7569 D.getLocStart(), NameInfo, 7570 R, TInfo, isExplicit, isInline, 7571 /*isImplicitlyDeclared=*/false, 7572 isConstexpr); 7573 7574 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7575 // This is a C++ destructor declaration. 7576 if (DC->isRecord()) { 7577 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7578 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7579 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7580 SemaRef.Context, Record, 7581 D.getLocStart(), 7582 NameInfo, R, TInfo, isInline, 7583 /*isImplicitlyDeclared=*/false); 7584 7585 // If the class is complete, then we now create the implicit exception 7586 // specification. If the class is incomplete or dependent, we can't do 7587 // it yet. 7588 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7589 Record->getDefinition() && !Record->isBeingDefined() && 7590 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7591 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7592 } 7593 7594 IsVirtualOkay = true; 7595 return NewDD; 7596 7597 } else { 7598 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7599 D.setInvalidType(); 7600 7601 // Create a FunctionDecl to satisfy the function definition parsing 7602 // code path. 7603 return FunctionDecl::Create(SemaRef.Context, DC, 7604 D.getLocStart(), 7605 D.getIdentifierLoc(), Name, R, TInfo, 7606 SC, isInline, 7607 /*hasPrototype=*/true, isConstexpr); 7608 } 7609 7610 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7611 if (!DC->isRecord()) { 7612 SemaRef.Diag(D.getIdentifierLoc(), 7613 diag::err_conv_function_not_member); 7614 return nullptr; 7615 } 7616 7617 SemaRef.CheckConversionDeclarator(D, R, SC); 7618 IsVirtualOkay = true; 7619 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7620 D.getLocStart(), NameInfo, 7621 R, TInfo, isInline, isExplicit, 7622 isConstexpr, SourceLocation()); 7623 7624 } else if (DC->isRecord()) { 7625 // If the name of the function is the same as the name of the record, 7626 // then this must be an invalid constructor that has a return type. 7627 // (The parser checks for a return type and makes the declarator a 7628 // constructor if it has no return type). 7629 if (Name.getAsIdentifierInfo() && 7630 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7631 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7632 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7633 << SourceRange(D.getIdentifierLoc()); 7634 return nullptr; 7635 } 7636 7637 // This is a C++ method declaration. 7638 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7639 cast<CXXRecordDecl>(DC), 7640 D.getLocStart(), NameInfo, R, 7641 TInfo, SC, isInline, 7642 isConstexpr, SourceLocation()); 7643 IsVirtualOkay = !Ret->isStatic(); 7644 return Ret; 7645 } else { 7646 bool isFriend = 7647 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7648 if (!isFriend && SemaRef.CurContext->isRecord()) 7649 return nullptr; 7650 7651 // Determine whether the function was written with a 7652 // prototype. This true when: 7653 // - we're in C++ (where every function has a prototype), 7654 return FunctionDecl::Create(SemaRef.Context, DC, 7655 D.getLocStart(), 7656 NameInfo, R, TInfo, SC, isInline, 7657 true/*HasPrototype*/, isConstexpr); 7658 } 7659 } 7660 7661 enum OpenCLParamType { 7662 ValidKernelParam, 7663 PtrPtrKernelParam, 7664 PtrKernelParam, 7665 InvalidAddrSpacePtrKernelParam, 7666 InvalidKernelParam, 7667 RecordKernelParam 7668 }; 7669 7670 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7671 if (PT->isPointerType()) { 7672 QualType PointeeType = PT->getPointeeType(); 7673 if (PointeeType->isPointerType()) 7674 return PtrPtrKernelParam; 7675 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7676 PointeeType.getAddressSpace() == 0) 7677 return InvalidAddrSpacePtrKernelParam; 7678 return PtrKernelParam; 7679 } 7680 7681 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7682 // be used as builtin types. 7683 7684 if (PT->isImageType()) 7685 return PtrKernelParam; 7686 7687 if (PT->isBooleanType()) 7688 return InvalidKernelParam; 7689 7690 if (PT->isEventT()) 7691 return InvalidKernelParam; 7692 7693 // OpenCL extension spec v1.2 s9.5: 7694 // This extension adds support for half scalar and vector types as built-in 7695 // types that can be used for arithmetic operations, conversions etc. 7696 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7697 return InvalidKernelParam; 7698 7699 if (PT->isRecordType()) 7700 return RecordKernelParam; 7701 7702 return ValidKernelParam; 7703 } 7704 7705 static void checkIsValidOpenCLKernelParameter( 7706 Sema &S, 7707 Declarator &D, 7708 ParmVarDecl *Param, 7709 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7710 QualType PT = Param->getType(); 7711 7712 // Cache the valid types we encounter to avoid rechecking structs that are 7713 // used again 7714 if (ValidTypes.count(PT.getTypePtr())) 7715 return; 7716 7717 switch (getOpenCLKernelParameterType(S, PT)) { 7718 case PtrPtrKernelParam: 7719 // OpenCL v1.2 s6.9.a: 7720 // A kernel function argument cannot be declared as a 7721 // pointer to a pointer type. 7722 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7723 D.setInvalidType(); 7724 return; 7725 7726 case InvalidAddrSpacePtrKernelParam: 7727 // OpenCL v1.0 s6.5: 7728 // __kernel function arguments declared to be a pointer of a type can point 7729 // to one of the following address spaces only : __global, __local or 7730 // __constant. 7731 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7732 D.setInvalidType(); 7733 return; 7734 7735 // OpenCL v1.2 s6.9.k: 7736 // Arguments to kernel functions in a program cannot be declared with the 7737 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7738 // uintptr_t or a struct and/or union that contain fields declared to be 7739 // one of these built-in scalar types. 7740 7741 case InvalidKernelParam: 7742 // OpenCL v1.2 s6.8 n: 7743 // A kernel function argument cannot be declared 7744 // of event_t type. 7745 // Do not diagnose half type since it is diagnosed as invalid argument 7746 // type for any function elsewhere. 7747 if (!PT->isHalfType()) 7748 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7749 D.setInvalidType(); 7750 return; 7751 7752 case PtrKernelParam: 7753 case ValidKernelParam: 7754 ValidTypes.insert(PT.getTypePtr()); 7755 return; 7756 7757 case RecordKernelParam: 7758 break; 7759 } 7760 7761 // Track nested structs we will inspect 7762 SmallVector<const Decl *, 4> VisitStack; 7763 7764 // Track where we are in the nested structs. Items will migrate from 7765 // VisitStack to HistoryStack as we do the DFS for bad field. 7766 SmallVector<const FieldDecl *, 4> HistoryStack; 7767 HistoryStack.push_back(nullptr); 7768 7769 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7770 VisitStack.push_back(PD); 7771 7772 assert(VisitStack.back() && "First decl null?"); 7773 7774 do { 7775 const Decl *Next = VisitStack.pop_back_val(); 7776 if (!Next) { 7777 assert(!HistoryStack.empty()); 7778 // Found a marker, we have gone up a level 7779 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7780 ValidTypes.insert(Hist->getType().getTypePtr()); 7781 7782 continue; 7783 } 7784 7785 // Adds everything except the original parameter declaration (which is not a 7786 // field itself) to the history stack. 7787 const RecordDecl *RD; 7788 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7789 HistoryStack.push_back(Field); 7790 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7791 } else { 7792 RD = cast<RecordDecl>(Next); 7793 } 7794 7795 // Add a null marker so we know when we've gone back up a level 7796 VisitStack.push_back(nullptr); 7797 7798 for (const auto *FD : RD->fields()) { 7799 QualType QT = FD->getType(); 7800 7801 if (ValidTypes.count(QT.getTypePtr())) 7802 continue; 7803 7804 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7805 if (ParamType == ValidKernelParam) 7806 continue; 7807 7808 if (ParamType == RecordKernelParam) { 7809 VisitStack.push_back(FD); 7810 continue; 7811 } 7812 7813 // OpenCL v1.2 s6.9.p: 7814 // Arguments to kernel functions that are declared to be a struct or union 7815 // do not allow OpenCL objects to be passed as elements of the struct or 7816 // union. 7817 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7818 ParamType == InvalidAddrSpacePtrKernelParam) { 7819 S.Diag(Param->getLocation(), 7820 diag::err_record_with_pointers_kernel_param) 7821 << PT->isUnionType() 7822 << PT; 7823 } else { 7824 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7825 } 7826 7827 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7828 << PD->getDeclName(); 7829 7830 // We have an error, now let's go back up through history and show where 7831 // the offending field came from 7832 for (ArrayRef<const FieldDecl *>::const_iterator 7833 I = HistoryStack.begin() + 1, 7834 E = HistoryStack.end(); 7835 I != E; ++I) { 7836 const FieldDecl *OuterField = *I; 7837 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7838 << OuterField->getType(); 7839 } 7840 7841 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7842 << QT->isPointerType() 7843 << QT; 7844 D.setInvalidType(); 7845 return; 7846 } 7847 } while (!VisitStack.empty()); 7848 } 7849 7850 /// Find the DeclContext in which a tag is implicitly declared if we see an 7851 /// elaborated type specifier in the specified context, and lookup finds 7852 /// nothing. 7853 static DeclContext *getTagInjectionContext(DeclContext *DC) { 7854 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 7855 DC = DC->getParent(); 7856 return DC; 7857 } 7858 7859 /// Find the Scope in which a tag is implicitly declared if we see an 7860 /// elaborated type specifier in the specified context, and lookup finds 7861 /// nothing. 7862 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 7863 while (S->isClassScope() || 7864 (LangOpts.CPlusPlus && 7865 S->isFunctionPrototypeScope()) || 7866 ((S->getFlags() & Scope::DeclScope) == 0) || 7867 (S->getEntity() && S->getEntity()->isTransparentContext())) 7868 S = S->getParent(); 7869 return S; 7870 } 7871 7872 NamedDecl* 7873 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7874 TypeSourceInfo *TInfo, LookupResult &Previous, 7875 MultiTemplateParamsArg TemplateParamLists, 7876 bool &AddToScope) { 7877 QualType R = TInfo->getType(); 7878 7879 assert(R.getTypePtr()->isFunctionType()); 7880 7881 // TODO: consider using NameInfo for diagnostic. 7882 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7883 DeclarationName Name = NameInfo.getName(); 7884 StorageClass SC = getFunctionStorageClass(*this, D); 7885 7886 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7887 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7888 diag::err_invalid_thread) 7889 << DeclSpec::getSpecifierName(TSCS); 7890 7891 if (D.isFirstDeclarationOfMember()) 7892 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7893 D.getIdentifierLoc()); 7894 7895 bool isFriend = false; 7896 FunctionTemplateDecl *FunctionTemplate = nullptr; 7897 bool isExplicitSpecialization = false; 7898 bool isFunctionTemplateSpecialization = false; 7899 7900 bool isDependentClassScopeExplicitSpecialization = false; 7901 bool HasExplicitTemplateArgs = false; 7902 TemplateArgumentListInfo TemplateArgs; 7903 7904 bool isVirtualOkay = false; 7905 7906 DeclContext *OriginalDC = DC; 7907 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7908 7909 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7910 isVirtualOkay); 7911 if (!NewFD) return nullptr; 7912 7913 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7914 NewFD->setTopLevelDeclInObjCContainer(); 7915 7916 // Set the lexical context. If this is a function-scope declaration, or has a 7917 // C++ scope specifier, or is the object of a friend declaration, the lexical 7918 // context will be different from the semantic context. 7919 NewFD->setLexicalDeclContext(CurContext); 7920 7921 if (IsLocalExternDecl) 7922 NewFD->setLocalExternDecl(); 7923 7924 if (getLangOpts().CPlusPlus) { 7925 bool isInline = D.getDeclSpec().isInlineSpecified(); 7926 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7927 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7928 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7929 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7930 isFriend = D.getDeclSpec().isFriendSpecified(); 7931 if (isFriend && !isInline && D.isFunctionDefinition()) { 7932 // C++ [class.friend]p5 7933 // A function can be defined in a friend declaration of a 7934 // class . . . . Such a function is implicitly inline. 7935 NewFD->setImplicitlyInline(); 7936 } 7937 7938 // If this is a method defined in an __interface, and is not a constructor 7939 // or an overloaded operator, then set the pure flag (isVirtual will already 7940 // return true). 7941 if (const CXXRecordDecl *Parent = 7942 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7943 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7944 NewFD->setPure(true); 7945 7946 // C++ [class.union]p2 7947 // A union can have member functions, but not virtual functions. 7948 if (isVirtual && Parent->isUnion()) 7949 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7950 } 7951 7952 SetNestedNameSpecifier(NewFD, D); 7953 isExplicitSpecialization = false; 7954 isFunctionTemplateSpecialization = false; 7955 if (D.isInvalidType()) 7956 NewFD->setInvalidDecl(); 7957 7958 // Match up the template parameter lists with the scope specifier, then 7959 // determine whether we have a template or a template specialization. 7960 bool Invalid = false; 7961 if (TemplateParameterList *TemplateParams = 7962 MatchTemplateParametersToScopeSpecifier( 7963 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7964 D.getCXXScopeSpec(), 7965 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7966 ? D.getName().TemplateId 7967 : nullptr, 7968 TemplateParamLists, isFriend, isExplicitSpecialization, 7969 Invalid)) { 7970 if (TemplateParams->size() > 0) { 7971 // This is a function template 7972 7973 // Check that we can declare a template here. 7974 if (CheckTemplateDeclScope(S, TemplateParams)) 7975 NewFD->setInvalidDecl(); 7976 7977 // A destructor cannot be a template. 7978 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7979 Diag(NewFD->getLocation(), diag::err_destructor_template); 7980 NewFD->setInvalidDecl(); 7981 } 7982 7983 // If we're adding a template to a dependent context, we may need to 7984 // rebuilding some of the types used within the template parameter list, 7985 // now that we know what the current instantiation is. 7986 if (DC->isDependentContext()) { 7987 ContextRAII SavedContext(*this, DC); 7988 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7989 Invalid = true; 7990 } 7991 7992 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7993 NewFD->getLocation(), 7994 Name, TemplateParams, 7995 NewFD); 7996 FunctionTemplate->setLexicalDeclContext(CurContext); 7997 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7998 7999 // For source fidelity, store the other template param lists. 8000 if (TemplateParamLists.size() > 1) { 8001 NewFD->setTemplateParameterListsInfo(Context, 8002 TemplateParamLists.drop_back(1)); 8003 } 8004 } else { 8005 // This is a function template specialization. 8006 isFunctionTemplateSpecialization = true; 8007 // For source fidelity, store all the template param lists. 8008 if (TemplateParamLists.size() > 0) 8009 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8010 8011 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8012 if (isFriend) { 8013 // We want to remove the "template<>", found here. 8014 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8015 8016 // If we remove the template<> and the name is not a 8017 // template-id, we're actually silently creating a problem: 8018 // the friend declaration will refer to an untemplated decl, 8019 // and clearly the user wants a template specialization. So 8020 // we need to insert '<>' after the name. 8021 SourceLocation InsertLoc; 8022 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8023 InsertLoc = D.getName().getSourceRange().getEnd(); 8024 InsertLoc = getLocForEndOfToken(InsertLoc); 8025 } 8026 8027 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8028 << Name << RemoveRange 8029 << FixItHint::CreateRemoval(RemoveRange) 8030 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8031 } 8032 } 8033 } 8034 else { 8035 // All template param lists were matched against the scope specifier: 8036 // this is NOT (an explicit specialization of) a template. 8037 if (TemplateParamLists.size() > 0) 8038 // For source fidelity, store all the template param lists. 8039 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8040 } 8041 8042 if (Invalid) { 8043 NewFD->setInvalidDecl(); 8044 if (FunctionTemplate) 8045 FunctionTemplate->setInvalidDecl(); 8046 } 8047 8048 // C++ [dcl.fct.spec]p5: 8049 // The virtual specifier shall only be used in declarations of 8050 // nonstatic class member functions that appear within a 8051 // member-specification of a class declaration; see 10.3. 8052 // 8053 if (isVirtual && !NewFD->isInvalidDecl()) { 8054 if (!isVirtualOkay) { 8055 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8056 diag::err_virtual_non_function); 8057 } else if (!CurContext->isRecord()) { 8058 // 'virtual' was specified outside of the class. 8059 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8060 diag::err_virtual_out_of_class) 8061 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8062 } else if (NewFD->getDescribedFunctionTemplate()) { 8063 // C++ [temp.mem]p3: 8064 // A member function template shall not be virtual. 8065 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8066 diag::err_virtual_member_function_template) 8067 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8068 } else { 8069 // Okay: Add virtual to the method. 8070 NewFD->setVirtualAsWritten(true); 8071 } 8072 8073 if (getLangOpts().CPlusPlus14 && 8074 NewFD->getReturnType()->isUndeducedType()) 8075 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8076 } 8077 8078 if (getLangOpts().CPlusPlus14 && 8079 (NewFD->isDependentContext() || 8080 (isFriend && CurContext->isDependentContext())) && 8081 NewFD->getReturnType()->isUndeducedType()) { 8082 // If the function template is referenced directly (for instance, as a 8083 // member of the current instantiation), pretend it has a dependent type. 8084 // This is not really justified by the standard, but is the only sane 8085 // thing to do. 8086 // FIXME: For a friend function, we have not marked the function as being 8087 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8088 const FunctionProtoType *FPT = 8089 NewFD->getType()->castAs<FunctionProtoType>(); 8090 QualType Result = 8091 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8092 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8093 FPT->getExtProtoInfo())); 8094 } 8095 8096 // C++ [dcl.fct.spec]p3: 8097 // The inline specifier shall not appear on a block scope function 8098 // declaration. 8099 if (isInline && !NewFD->isInvalidDecl()) { 8100 if (CurContext->isFunctionOrMethod()) { 8101 // 'inline' is not allowed on block scope function declaration. 8102 Diag(D.getDeclSpec().getInlineSpecLoc(), 8103 diag::err_inline_declaration_block_scope) << Name 8104 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8105 } 8106 } 8107 8108 // C++ [dcl.fct.spec]p6: 8109 // The explicit specifier shall be used only in the declaration of a 8110 // constructor or conversion function within its class definition; 8111 // see 12.3.1 and 12.3.2. 8112 if (isExplicit && !NewFD->isInvalidDecl()) { 8113 if (!CurContext->isRecord()) { 8114 // 'explicit' was specified outside of the class. 8115 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8116 diag::err_explicit_out_of_class) 8117 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8118 } else if (!isa<CXXConstructorDecl>(NewFD) && 8119 !isa<CXXConversionDecl>(NewFD)) { 8120 // 'explicit' was specified on a function that wasn't a constructor 8121 // or conversion function. 8122 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8123 diag::err_explicit_non_ctor_or_conv_function) 8124 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8125 } 8126 } 8127 8128 if (isConstexpr) { 8129 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8130 // are implicitly inline. 8131 NewFD->setImplicitlyInline(); 8132 8133 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8134 // be either constructors or to return a literal type. Therefore, 8135 // destructors cannot be declared constexpr. 8136 if (isa<CXXDestructorDecl>(NewFD)) 8137 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8138 } 8139 8140 if (isConcept) { 8141 // This is a function concept. 8142 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8143 FTD->setConcept(); 8144 8145 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8146 // applied only to the definition of a function template [...] 8147 if (!D.isFunctionDefinition()) { 8148 Diag(D.getDeclSpec().getConceptSpecLoc(), 8149 diag::err_function_concept_not_defined); 8150 NewFD->setInvalidDecl(); 8151 } 8152 8153 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8154 // have no exception-specification and is treated as if it were specified 8155 // with noexcept(true) (15.4). [...] 8156 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8157 if (FPT->hasExceptionSpec()) { 8158 SourceRange Range; 8159 if (D.isFunctionDeclarator()) 8160 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8161 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8162 << FixItHint::CreateRemoval(Range); 8163 NewFD->setInvalidDecl(); 8164 } else { 8165 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8166 } 8167 8168 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8169 // following restrictions: 8170 // - The declared return type shall have the type bool. 8171 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8172 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8173 NewFD->setInvalidDecl(); 8174 } 8175 8176 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8177 // following restrictions: 8178 // - The declaration's parameter list shall be equivalent to an empty 8179 // parameter list. 8180 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8181 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8182 } 8183 8184 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8185 // implicity defined to be a constexpr declaration (implicitly inline) 8186 NewFD->setImplicitlyInline(); 8187 8188 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8189 // be declared with the thread_local, inline, friend, or constexpr 8190 // specifiers, [...] 8191 if (isInline) { 8192 Diag(D.getDeclSpec().getInlineSpecLoc(), 8193 diag::err_concept_decl_invalid_specifiers) 8194 << 1 << 1; 8195 NewFD->setInvalidDecl(true); 8196 } 8197 8198 if (isFriend) { 8199 Diag(D.getDeclSpec().getFriendSpecLoc(), 8200 diag::err_concept_decl_invalid_specifiers) 8201 << 1 << 2; 8202 NewFD->setInvalidDecl(true); 8203 } 8204 8205 if (isConstexpr) { 8206 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8207 diag::err_concept_decl_invalid_specifiers) 8208 << 1 << 3; 8209 NewFD->setInvalidDecl(true); 8210 } 8211 8212 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8213 // applied only to the definition of a function template or variable 8214 // template, declared in namespace scope. 8215 if (isFunctionTemplateSpecialization) { 8216 Diag(D.getDeclSpec().getConceptSpecLoc(), 8217 diag::err_concept_specified_specialization) << 1; 8218 NewFD->setInvalidDecl(true); 8219 return NewFD; 8220 } 8221 } 8222 8223 // If __module_private__ was specified, mark the function accordingly. 8224 if (D.getDeclSpec().isModulePrivateSpecified()) { 8225 if (isFunctionTemplateSpecialization) { 8226 SourceLocation ModulePrivateLoc 8227 = D.getDeclSpec().getModulePrivateSpecLoc(); 8228 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8229 << 0 8230 << FixItHint::CreateRemoval(ModulePrivateLoc); 8231 } else { 8232 NewFD->setModulePrivate(); 8233 if (FunctionTemplate) 8234 FunctionTemplate->setModulePrivate(); 8235 } 8236 } 8237 8238 if (isFriend) { 8239 if (FunctionTemplate) { 8240 FunctionTemplate->setObjectOfFriendDecl(); 8241 FunctionTemplate->setAccess(AS_public); 8242 } 8243 NewFD->setObjectOfFriendDecl(); 8244 NewFD->setAccess(AS_public); 8245 } 8246 8247 // If a function is defined as defaulted or deleted, mark it as such now. 8248 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8249 // definition kind to FDK_Definition. 8250 switch (D.getFunctionDefinitionKind()) { 8251 case FDK_Declaration: 8252 case FDK_Definition: 8253 break; 8254 8255 case FDK_Defaulted: 8256 NewFD->setDefaulted(); 8257 break; 8258 8259 case FDK_Deleted: 8260 NewFD->setDeletedAsWritten(); 8261 break; 8262 } 8263 8264 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8265 D.isFunctionDefinition()) { 8266 // C++ [class.mfct]p2: 8267 // A member function may be defined (8.4) in its class definition, in 8268 // which case it is an inline member function (7.1.2) 8269 NewFD->setImplicitlyInline(); 8270 } 8271 8272 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8273 !CurContext->isRecord()) { 8274 // C++ [class.static]p1: 8275 // A data or function member of a class may be declared static 8276 // in a class definition, in which case it is a static member of 8277 // the class. 8278 8279 // Complain about the 'static' specifier if it's on an out-of-line 8280 // member function definition. 8281 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8282 diag::err_static_out_of_line) 8283 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8284 } 8285 8286 // C++11 [except.spec]p15: 8287 // A deallocation function with no exception-specification is treated 8288 // as if it were specified with noexcept(true). 8289 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8290 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8291 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8292 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8293 NewFD->setType(Context.getFunctionType( 8294 FPT->getReturnType(), FPT->getParamTypes(), 8295 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8296 } 8297 8298 // Filter out previous declarations that don't match the scope. 8299 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8300 D.getCXXScopeSpec().isNotEmpty() || 8301 isExplicitSpecialization || 8302 isFunctionTemplateSpecialization); 8303 8304 // Handle GNU asm-label extension (encoded as an attribute). 8305 if (Expr *E = (Expr*) D.getAsmLabel()) { 8306 // The parser guarantees this is a string. 8307 StringLiteral *SE = cast<StringLiteral>(E); 8308 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8309 SE->getString(), 0)); 8310 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8311 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8312 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8313 if (I != ExtnameUndeclaredIdentifiers.end()) { 8314 if (isDeclExternC(NewFD)) { 8315 NewFD->addAttr(I->second); 8316 ExtnameUndeclaredIdentifiers.erase(I); 8317 } else 8318 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8319 << /*Variable*/0 << NewFD; 8320 } 8321 } 8322 8323 // Copy the parameter declarations from the declarator D to the function 8324 // declaration NewFD, if they are available. First scavenge them into Params. 8325 SmallVector<ParmVarDecl*, 16> Params; 8326 unsigned FTIIdx; 8327 if (D.isFunctionDeclarator(FTIIdx)) { 8328 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8329 8330 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8331 // function that takes no arguments, not a function that takes a 8332 // single void argument. 8333 // We let through "const void" here because Sema::GetTypeForDeclarator 8334 // already checks for that case. 8335 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8336 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8337 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8338 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8339 Param->setDeclContext(NewFD); 8340 Params.push_back(Param); 8341 8342 if (Param->isInvalidDecl()) 8343 NewFD->setInvalidDecl(); 8344 } 8345 } 8346 8347 if (!getLangOpts().CPlusPlus) { 8348 // In C, find all the tag declarations from the prototype and move them 8349 // into the function DeclContext. Remove them from the surrounding tag 8350 // injection context of the function, which is typically but not always 8351 // the TU. 8352 DeclContext *PrototypeTagContext = 8353 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8354 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8355 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8356 8357 // We don't want to reparent enumerators. Look at their parent enum 8358 // instead. 8359 if (!TD) { 8360 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8361 TD = cast<EnumDecl>(ECD->getDeclContext()); 8362 } 8363 if (!TD) 8364 continue; 8365 DeclContext *TagDC = TD->getLexicalDeclContext(); 8366 if (!TagDC->containsDecl(TD)) 8367 continue; 8368 TagDC->removeDecl(TD); 8369 TD->setDeclContext(NewFD); 8370 NewFD->addDecl(TD); 8371 8372 // Preserve the lexical DeclContext if it is not the surrounding tag 8373 // injection context of the FD. In this example, the semantic context of 8374 // E will be f and the lexical context will be S, while both the 8375 // semantic and lexical contexts of S will be f: 8376 // void f(struct S { enum E { a } f; } s); 8377 if (TagDC != PrototypeTagContext) 8378 TD->setLexicalDeclContext(TagDC); 8379 } 8380 } 8381 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8382 // When we're declaring a function with a typedef, typeof, etc as in the 8383 // following example, we'll need to synthesize (unnamed) 8384 // parameters for use in the declaration. 8385 // 8386 // @code 8387 // typedef void fn(int); 8388 // fn f; 8389 // @endcode 8390 8391 // Synthesize a parameter for each argument type. 8392 for (const auto &AI : FT->param_types()) { 8393 ParmVarDecl *Param = 8394 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8395 Param->setScopeInfo(0, Params.size()); 8396 Params.push_back(Param); 8397 } 8398 } else { 8399 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8400 "Should not need args for typedef of non-prototype fn"); 8401 } 8402 8403 // Finally, we know we have the right number of parameters, install them. 8404 NewFD->setParams(Params); 8405 8406 if (D.getDeclSpec().isNoreturnSpecified()) 8407 NewFD->addAttr( 8408 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8409 Context, 0)); 8410 8411 // Functions returning a variably modified type violate C99 6.7.5.2p2 8412 // because all functions have linkage. 8413 if (!NewFD->isInvalidDecl() && 8414 NewFD->getReturnType()->isVariablyModifiedType()) { 8415 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8416 NewFD->setInvalidDecl(); 8417 } 8418 8419 // Apply an implicit SectionAttr if #pragma code_seg is active. 8420 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8421 !NewFD->hasAttr<SectionAttr>()) { 8422 NewFD->addAttr( 8423 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8424 CodeSegStack.CurrentValue->getString(), 8425 CodeSegStack.CurrentPragmaLocation)); 8426 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8427 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8428 ASTContext::PSF_Read, 8429 NewFD)) 8430 NewFD->dropAttr<SectionAttr>(); 8431 } 8432 8433 // Handle attributes. 8434 ProcessDeclAttributes(S, NewFD, D); 8435 8436 if (getLangOpts().OpenCL) { 8437 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8438 // type declaration will generate a compilation error. 8439 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8440 if (AddressSpace == LangAS::opencl_local || 8441 AddressSpace == LangAS::opencl_global || 8442 AddressSpace == LangAS::opencl_constant) { 8443 Diag(NewFD->getLocation(), 8444 diag::err_opencl_return_value_with_address_space); 8445 NewFD->setInvalidDecl(); 8446 } 8447 } 8448 8449 if (!getLangOpts().CPlusPlus) { 8450 // Perform semantic checking on the function declaration. 8451 bool isExplicitSpecialization=false; 8452 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8453 CheckMain(NewFD, D.getDeclSpec()); 8454 8455 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8456 CheckMSVCRTEntryPoint(NewFD); 8457 8458 if (!NewFD->isInvalidDecl()) 8459 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8460 isExplicitSpecialization)); 8461 else if (!Previous.empty()) 8462 // Recover gracefully from an invalid redeclaration. 8463 D.setRedeclaration(true); 8464 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8465 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8466 "previous declaration set still overloaded"); 8467 8468 // Diagnose no-prototype function declarations with calling conventions that 8469 // don't support variadic calls. Only do this in C and do it after merging 8470 // possibly prototyped redeclarations. 8471 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8472 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8473 CallingConv CC = FT->getExtInfo().getCC(); 8474 if (!supportsVariadicCall(CC)) { 8475 // Windows system headers sometimes accidentally use stdcall without 8476 // (void) parameters, so we relax this to a warning. 8477 int DiagID = 8478 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8479 Diag(NewFD->getLocation(), DiagID) 8480 << FunctionType::getNameForCallConv(CC); 8481 } 8482 } 8483 } else { 8484 // C++11 [replacement.functions]p3: 8485 // The program's definitions shall not be specified as inline. 8486 // 8487 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8488 // 8489 // Suppress the diagnostic if the function is __attribute__((used)), since 8490 // that forces an external definition to be emitted. 8491 if (D.getDeclSpec().isInlineSpecified() && 8492 NewFD->isReplaceableGlobalAllocationFunction() && 8493 !NewFD->hasAttr<UsedAttr>()) 8494 Diag(D.getDeclSpec().getInlineSpecLoc(), 8495 diag::ext_operator_new_delete_declared_inline) 8496 << NewFD->getDeclName(); 8497 8498 // If the declarator is a template-id, translate the parser's template 8499 // argument list into our AST format. 8500 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8501 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8502 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8503 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8504 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8505 TemplateId->NumArgs); 8506 translateTemplateArguments(TemplateArgsPtr, 8507 TemplateArgs); 8508 8509 HasExplicitTemplateArgs = true; 8510 8511 if (NewFD->isInvalidDecl()) { 8512 HasExplicitTemplateArgs = false; 8513 } else if (FunctionTemplate) { 8514 // Function template with explicit template arguments. 8515 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8516 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8517 8518 HasExplicitTemplateArgs = false; 8519 } else { 8520 assert((isFunctionTemplateSpecialization || 8521 D.getDeclSpec().isFriendSpecified()) && 8522 "should have a 'template<>' for this decl"); 8523 // "friend void foo<>(int);" is an implicit specialization decl. 8524 isFunctionTemplateSpecialization = true; 8525 } 8526 } else if (isFriend && isFunctionTemplateSpecialization) { 8527 // This combination is only possible in a recovery case; the user 8528 // wrote something like: 8529 // template <> friend void foo(int); 8530 // which we're recovering from as if the user had written: 8531 // friend void foo<>(int); 8532 // Go ahead and fake up a template id. 8533 HasExplicitTemplateArgs = true; 8534 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8535 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8536 } 8537 8538 // We do not add HD attributes to specializations here because 8539 // they may have different constexpr-ness compared to their 8540 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8541 // may end up with different effective targets. Instead, a 8542 // specialization inherits its target attributes from its template 8543 // in the CheckFunctionTemplateSpecialization() call below. 8544 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8545 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8546 8547 // If it's a friend (and only if it's a friend), it's possible 8548 // that either the specialized function type or the specialized 8549 // template is dependent, and therefore matching will fail. In 8550 // this case, don't check the specialization yet. 8551 bool InstantiationDependent = false; 8552 if (isFunctionTemplateSpecialization && isFriend && 8553 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8554 TemplateSpecializationType::anyDependentTemplateArguments( 8555 TemplateArgs, 8556 InstantiationDependent))) { 8557 assert(HasExplicitTemplateArgs && 8558 "friend function specialization without template args"); 8559 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8560 Previous)) 8561 NewFD->setInvalidDecl(); 8562 } else if (isFunctionTemplateSpecialization) { 8563 if (CurContext->isDependentContext() && CurContext->isRecord() 8564 && !isFriend) { 8565 isDependentClassScopeExplicitSpecialization = true; 8566 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8567 diag::ext_function_specialization_in_class : 8568 diag::err_function_specialization_in_class) 8569 << NewFD->getDeclName(); 8570 } else if (CheckFunctionTemplateSpecialization(NewFD, 8571 (HasExplicitTemplateArgs ? &TemplateArgs 8572 : nullptr), 8573 Previous)) 8574 NewFD->setInvalidDecl(); 8575 8576 // C++ [dcl.stc]p1: 8577 // A storage-class-specifier shall not be specified in an explicit 8578 // specialization (14.7.3) 8579 FunctionTemplateSpecializationInfo *Info = 8580 NewFD->getTemplateSpecializationInfo(); 8581 if (Info && SC != SC_None) { 8582 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8583 Diag(NewFD->getLocation(), 8584 diag::err_explicit_specialization_inconsistent_storage_class) 8585 << SC 8586 << FixItHint::CreateRemoval( 8587 D.getDeclSpec().getStorageClassSpecLoc()); 8588 8589 else 8590 Diag(NewFD->getLocation(), 8591 diag::ext_explicit_specialization_storage_class) 8592 << FixItHint::CreateRemoval( 8593 D.getDeclSpec().getStorageClassSpecLoc()); 8594 } 8595 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8596 if (CheckMemberSpecialization(NewFD, Previous)) 8597 NewFD->setInvalidDecl(); 8598 } 8599 8600 // Perform semantic checking on the function declaration. 8601 if (!isDependentClassScopeExplicitSpecialization) { 8602 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8603 CheckMain(NewFD, D.getDeclSpec()); 8604 8605 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8606 CheckMSVCRTEntryPoint(NewFD); 8607 8608 if (!NewFD->isInvalidDecl()) 8609 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8610 isExplicitSpecialization)); 8611 else if (!Previous.empty()) 8612 // Recover gracefully from an invalid redeclaration. 8613 D.setRedeclaration(true); 8614 } 8615 8616 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8617 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8618 "previous declaration set still overloaded"); 8619 8620 NamedDecl *PrincipalDecl = (FunctionTemplate 8621 ? cast<NamedDecl>(FunctionTemplate) 8622 : NewFD); 8623 8624 if (isFriend && NewFD->getPreviousDecl()) { 8625 AccessSpecifier Access = AS_public; 8626 if (!NewFD->isInvalidDecl()) 8627 Access = NewFD->getPreviousDecl()->getAccess(); 8628 8629 NewFD->setAccess(Access); 8630 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8631 } 8632 8633 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8634 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8635 PrincipalDecl->setNonMemberOperator(); 8636 8637 // If we have a function template, check the template parameter 8638 // list. This will check and merge default template arguments. 8639 if (FunctionTemplate) { 8640 FunctionTemplateDecl *PrevTemplate = 8641 FunctionTemplate->getPreviousDecl(); 8642 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8643 PrevTemplate ? PrevTemplate->getTemplateParameters() 8644 : nullptr, 8645 D.getDeclSpec().isFriendSpecified() 8646 ? (D.isFunctionDefinition() 8647 ? TPC_FriendFunctionTemplateDefinition 8648 : TPC_FriendFunctionTemplate) 8649 : (D.getCXXScopeSpec().isSet() && 8650 DC && DC->isRecord() && 8651 DC->isDependentContext()) 8652 ? TPC_ClassTemplateMember 8653 : TPC_FunctionTemplate); 8654 } 8655 8656 if (NewFD->isInvalidDecl()) { 8657 // Ignore all the rest of this. 8658 } else if (!D.isRedeclaration()) { 8659 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8660 AddToScope }; 8661 // Fake up an access specifier if it's supposed to be a class member. 8662 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8663 NewFD->setAccess(AS_public); 8664 8665 // Qualified decls generally require a previous declaration. 8666 if (D.getCXXScopeSpec().isSet()) { 8667 // ...with the major exception of templated-scope or 8668 // dependent-scope friend declarations. 8669 8670 // TODO: we currently also suppress this check in dependent 8671 // contexts because (1) the parameter depth will be off when 8672 // matching friend templates and (2) we might actually be 8673 // selecting a friend based on a dependent factor. But there 8674 // are situations where these conditions don't apply and we 8675 // can actually do this check immediately. 8676 if (isFriend && 8677 (TemplateParamLists.size() || 8678 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8679 CurContext->isDependentContext())) { 8680 // ignore these 8681 } else { 8682 // The user tried to provide an out-of-line definition for a 8683 // function that is a member of a class or namespace, but there 8684 // was no such member function declared (C++ [class.mfct]p2, 8685 // C++ [namespace.memdef]p2). For example: 8686 // 8687 // class X { 8688 // void f() const; 8689 // }; 8690 // 8691 // void X::f() { } // ill-formed 8692 // 8693 // Complain about this problem, and attempt to suggest close 8694 // matches (e.g., those that differ only in cv-qualifiers and 8695 // whether the parameter types are references). 8696 8697 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8698 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8699 AddToScope = ExtraArgs.AddToScope; 8700 return Result; 8701 } 8702 } 8703 8704 // Unqualified local friend declarations are required to resolve 8705 // to something. 8706 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8707 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8708 *this, Previous, NewFD, ExtraArgs, true, S)) { 8709 AddToScope = ExtraArgs.AddToScope; 8710 return Result; 8711 } 8712 } 8713 } else if (!D.isFunctionDefinition() && 8714 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8715 !isFriend && !isFunctionTemplateSpecialization && 8716 !isExplicitSpecialization) { 8717 // An out-of-line member function declaration must also be a 8718 // definition (C++ [class.mfct]p2). 8719 // Note that this is not the case for explicit specializations of 8720 // function templates or member functions of class templates, per 8721 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8722 // extension for compatibility with old SWIG code which likes to 8723 // generate them. 8724 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8725 << D.getCXXScopeSpec().getRange(); 8726 } 8727 } 8728 8729 ProcessPragmaWeak(S, NewFD); 8730 checkAttributesAfterMerging(*this, *NewFD); 8731 8732 AddKnownFunctionAttributes(NewFD); 8733 8734 if (NewFD->hasAttr<OverloadableAttr>() && 8735 !NewFD->getType()->getAs<FunctionProtoType>()) { 8736 Diag(NewFD->getLocation(), 8737 diag::err_attribute_overloadable_no_prototype) 8738 << NewFD; 8739 8740 // Turn this into a variadic function with no parameters. 8741 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8742 FunctionProtoType::ExtProtoInfo EPI( 8743 Context.getDefaultCallingConvention(true, false)); 8744 EPI.Variadic = true; 8745 EPI.ExtInfo = FT->getExtInfo(); 8746 8747 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8748 NewFD->setType(R); 8749 } 8750 8751 // If there's a #pragma GCC visibility in scope, and this isn't a class 8752 // member, set the visibility of this function. 8753 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8754 AddPushedVisibilityAttribute(NewFD); 8755 8756 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8757 // marking the function. 8758 AddCFAuditedAttribute(NewFD); 8759 8760 // If this is a function definition, check if we have to apply optnone due to 8761 // a pragma. 8762 if(D.isFunctionDefinition()) 8763 AddRangeBasedOptnone(NewFD); 8764 8765 // If this is the first declaration of an extern C variable, update 8766 // the map of such variables. 8767 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8768 isIncompleteDeclExternC(*this, NewFD)) 8769 RegisterLocallyScopedExternCDecl(NewFD, S); 8770 8771 // Set this FunctionDecl's range up to the right paren. 8772 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8773 8774 if (D.isRedeclaration() && !Previous.empty()) { 8775 checkDLLAttributeRedeclaration( 8776 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8777 isExplicitSpecialization || isFunctionTemplateSpecialization, 8778 D.isFunctionDefinition()); 8779 } 8780 8781 if (getLangOpts().CUDA) { 8782 IdentifierInfo *II = NewFD->getIdentifier(); 8783 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8784 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8785 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8786 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8787 8788 Context.setcudaConfigureCallDecl(NewFD); 8789 } 8790 8791 // Variadic functions, other than a *declaration* of printf, are not allowed 8792 // in device-side CUDA code, unless someone passed 8793 // -fcuda-allow-variadic-functions. 8794 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8795 (NewFD->hasAttr<CUDADeviceAttr>() || 8796 NewFD->hasAttr<CUDAGlobalAttr>()) && 8797 !(II && II->isStr("printf") && NewFD->isExternC() && 8798 !D.isFunctionDefinition())) { 8799 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8800 } 8801 } 8802 8803 if (getLangOpts().CPlusPlus) { 8804 if (FunctionTemplate) { 8805 if (NewFD->isInvalidDecl()) 8806 FunctionTemplate->setInvalidDecl(); 8807 return FunctionTemplate; 8808 } 8809 } 8810 8811 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8812 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8813 if ((getLangOpts().OpenCLVersion >= 120) 8814 && (SC == SC_Static)) { 8815 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8816 D.setInvalidType(); 8817 } 8818 8819 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8820 if (!NewFD->getReturnType()->isVoidType()) { 8821 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8822 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8823 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8824 : FixItHint()); 8825 D.setInvalidType(); 8826 } 8827 8828 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8829 for (auto Param : NewFD->parameters()) 8830 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8831 } 8832 for (const ParmVarDecl *Param : NewFD->parameters()) { 8833 QualType PT = Param->getType(); 8834 8835 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8836 // types. 8837 if (getLangOpts().OpenCLVersion >= 200) { 8838 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8839 QualType ElemTy = PipeTy->getElementType(); 8840 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8841 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8842 D.setInvalidType(); 8843 } 8844 } 8845 } 8846 } 8847 8848 MarkUnusedFileScopedDecl(NewFD); 8849 8850 // Here we have an function template explicit specialization at class scope. 8851 // The actually specialization will be postponed to template instatiation 8852 // time via the ClassScopeFunctionSpecializationDecl node. 8853 if (isDependentClassScopeExplicitSpecialization) { 8854 ClassScopeFunctionSpecializationDecl *NewSpec = 8855 ClassScopeFunctionSpecializationDecl::Create( 8856 Context, CurContext, SourceLocation(), 8857 cast<CXXMethodDecl>(NewFD), 8858 HasExplicitTemplateArgs, TemplateArgs); 8859 CurContext->addDecl(NewSpec); 8860 AddToScope = false; 8861 } 8862 8863 return NewFD; 8864 } 8865 8866 /// \brief Checks if the new declaration declared in dependent context must be 8867 /// put in the same redeclaration chain as the specified declaration. 8868 /// 8869 /// \param D Declaration that is checked. 8870 /// \param PrevDecl Previous declaration found with proper lookup method for the 8871 /// same declaration name. 8872 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8873 /// belongs to. 8874 /// 8875 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8876 // Any declarations should be put into redeclaration chains except for 8877 // friend declaration in a dependent context that names a function in 8878 // namespace scope. 8879 // 8880 // This allows to compile code like: 8881 // 8882 // void func(); 8883 // template<typename T> class C1 { friend void func() { } }; 8884 // template<typename T> class C2 { friend void func() { } }; 8885 // 8886 // This code snippet is a valid code unless both templates are instantiated. 8887 return !(D->getLexicalDeclContext()->isDependentContext() && 8888 D->getDeclContext()->isFileContext() && 8889 D->getFriendObjectKind() != Decl::FOK_None); 8890 } 8891 8892 /// \brief Perform semantic checking of a new function declaration. 8893 /// 8894 /// Performs semantic analysis of the new function declaration 8895 /// NewFD. This routine performs all semantic checking that does not 8896 /// require the actual declarator involved in the declaration, and is 8897 /// used both for the declaration of functions as they are parsed 8898 /// (called via ActOnDeclarator) and for the declaration of functions 8899 /// that have been instantiated via C++ template instantiation (called 8900 /// via InstantiateDecl). 8901 /// 8902 /// \param IsExplicitSpecialization whether this new function declaration is 8903 /// an explicit specialization of the previous declaration. 8904 /// 8905 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8906 /// 8907 /// \returns true if the function declaration is a redeclaration. 8908 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8909 LookupResult &Previous, 8910 bool IsExplicitSpecialization) { 8911 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8912 "Variably modified return types are not handled here"); 8913 8914 // Determine whether the type of this function should be merged with 8915 // a previous visible declaration. This never happens for functions in C++, 8916 // and always happens in C if the previous declaration was visible. 8917 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8918 !Previous.isShadowed(); 8919 8920 bool Redeclaration = false; 8921 NamedDecl *OldDecl = nullptr; 8922 8923 // Merge or overload the declaration with an existing declaration of 8924 // the same name, if appropriate. 8925 if (!Previous.empty()) { 8926 // Determine whether NewFD is an overload of PrevDecl or 8927 // a declaration that requires merging. If it's an overload, 8928 // there's no more work to do here; we'll just add the new 8929 // function to the scope. 8930 if (!AllowOverloadingOfFunction(Previous, Context)) { 8931 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8932 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8933 Redeclaration = true; 8934 OldDecl = Candidate; 8935 } 8936 } else { 8937 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8938 /*NewIsUsingDecl*/ false)) { 8939 case Ovl_Match: 8940 Redeclaration = true; 8941 break; 8942 8943 case Ovl_NonFunction: 8944 Redeclaration = true; 8945 break; 8946 8947 case Ovl_Overload: 8948 Redeclaration = false; 8949 break; 8950 } 8951 8952 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8953 // If a function name is overloadable in C, then every function 8954 // with that name must be marked "overloadable". 8955 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8956 << Redeclaration << NewFD; 8957 NamedDecl *OverloadedDecl = nullptr; 8958 if (Redeclaration) 8959 OverloadedDecl = OldDecl; 8960 else if (!Previous.empty()) 8961 OverloadedDecl = Previous.getRepresentativeDecl(); 8962 if (OverloadedDecl) 8963 Diag(OverloadedDecl->getLocation(), 8964 diag::note_attribute_overloadable_prev_overload); 8965 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8966 } 8967 } 8968 } 8969 8970 // Check for a previous extern "C" declaration with this name. 8971 if (!Redeclaration && 8972 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8973 if (!Previous.empty()) { 8974 // This is an extern "C" declaration with the same name as a previous 8975 // declaration, and thus redeclares that entity... 8976 Redeclaration = true; 8977 OldDecl = Previous.getFoundDecl(); 8978 MergeTypeWithPrevious = false; 8979 8980 // ... except in the presence of __attribute__((overloadable)). 8981 if (OldDecl->hasAttr<OverloadableAttr>()) { 8982 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8983 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8984 << Redeclaration << NewFD; 8985 Diag(Previous.getFoundDecl()->getLocation(), 8986 diag::note_attribute_overloadable_prev_overload); 8987 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8988 } 8989 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8990 Redeclaration = false; 8991 OldDecl = nullptr; 8992 } 8993 } 8994 } 8995 } 8996 8997 // C++11 [dcl.constexpr]p8: 8998 // A constexpr specifier for a non-static member function that is not 8999 // a constructor declares that member function to be const. 9000 // 9001 // This needs to be delayed until we know whether this is an out-of-line 9002 // definition of a static member function. 9003 // 9004 // This rule is not present in C++1y, so we produce a backwards 9005 // compatibility warning whenever it happens in C++11. 9006 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9007 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9008 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9009 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9010 CXXMethodDecl *OldMD = nullptr; 9011 if (OldDecl) 9012 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9013 if (!OldMD || !OldMD->isStatic()) { 9014 const FunctionProtoType *FPT = 9015 MD->getType()->castAs<FunctionProtoType>(); 9016 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9017 EPI.TypeQuals |= Qualifiers::Const; 9018 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9019 FPT->getParamTypes(), EPI)); 9020 9021 // Warn that we did this, if we're not performing template instantiation. 9022 // In that case, we'll have warned already when the template was defined. 9023 if (ActiveTemplateInstantiations.empty()) { 9024 SourceLocation AddConstLoc; 9025 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9026 .IgnoreParens().getAs<FunctionTypeLoc>()) 9027 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9028 9029 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9030 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9031 } 9032 } 9033 } 9034 9035 if (Redeclaration) { 9036 // NewFD and OldDecl represent declarations that need to be 9037 // merged. 9038 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9039 NewFD->setInvalidDecl(); 9040 return Redeclaration; 9041 } 9042 9043 Previous.clear(); 9044 Previous.addDecl(OldDecl); 9045 9046 if (FunctionTemplateDecl *OldTemplateDecl 9047 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9048 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9049 FunctionTemplateDecl *NewTemplateDecl 9050 = NewFD->getDescribedFunctionTemplate(); 9051 assert(NewTemplateDecl && "Template/non-template mismatch"); 9052 if (CXXMethodDecl *Method 9053 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9054 Method->setAccess(OldTemplateDecl->getAccess()); 9055 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9056 } 9057 9058 // If this is an explicit specialization of a member that is a function 9059 // template, mark it as a member specialization. 9060 if (IsExplicitSpecialization && 9061 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9062 NewTemplateDecl->setMemberSpecialization(); 9063 assert(OldTemplateDecl->isMemberSpecialization()); 9064 // Explicit specializations of a member template do not inherit deleted 9065 // status from the parent member template that they are specializing. 9066 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9067 FunctionDecl *const OldTemplatedDecl = 9068 OldTemplateDecl->getTemplatedDecl(); 9069 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9070 OldTemplatedDecl->setDeletedAsWritten(false); 9071 } 9072 } 9073 9074 } else { 9075 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9076 // This needs to happen first so that 'inline' propagates. 9077 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9078 if (isa<CXXMethodDecl>(NewFD)) 9079 NewFD->setAccess(OldDecl->getAccess()); 9080 } 9081 } 9082 } 9083 9084 // Semantic checking for this function declaration (in isolation). 9085 9086 if (getLangOpts().CPlusPlus) { 9087 // C++-specific checks. 9088 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9089 CheckConstructor(Constructor); 9090 } else if (CXXDestructorDecl *Destructor = 9091 dyn_cast<CXXDestructorDecl>(NewFD)) { 9092 CXXRecordDecl *Record = Destructor->getParent(); 9093 QualType ClassType = Context.getTypeDeclType(Record); 9094 9095 // FIXME: Shouldn't we be able to perform this check even when the class 9096 // type is dependent? Both gcc and edg can handle that. 9097 if (!ClassType->isDependentType()) { 9098 DeclarationName Name 9099 = Context.DeclarationNames.getCXXDestructorName( 9100 Context.getCanonicalType(ClassType)); 9101 if (NewFD->getDeclName() != Name) { 9102 Diag(NewFD->getLocation(), diag::err_destructor_name); 9103 NewFD->setInvalidDecl(); 9104 return Redeclaration; 9105 } 9106 } 9107 } else if (CXXConversionDecl *Conversion 9108 = dyn_cast<CXXConversionDecl>(NewFD)) { 9109 ActOnConversionDeclarator(Conversion); 9110 } 9111 9112 // Find any virtual functions that this function overrides. 9113 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9114 if (!Method->isFunctionTemplateSpecialization() && 9115 !Method->getDescribedFunctionTemplate() && 9116 Method->isCanonicalDecl()) { 9117 if (AddOverriddenMethods(Method->getParent(), Method)) { 9118 // If the function was marked as "static", we have a problem. 9119 if (NewFD->getStorageClass() == SC_Static) { 9120 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9121 } 9122 } 9123 } 9124 9125 if (Method->isStatic()) 9126 checkThisInStaticMemberFunctionType(Method); 9127 } 9128 9129 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9130 if (NewFD->isOverloadedOperator() && 9131 CheckOverloadedOperatorDeclaration(NewFD)) { 9132 NewFD->setInvalidDecl(); 9133 return Redeclaration; 9134 } 9135 9136 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9137 if (NewFD->getLiteralIdentifier() && 9138 CheckLiteralOperatorDeclaration(NewFD)) { 9139 NewFD->setInvalidDecl(); 9140 return Redeclaration; 9141 } 9142 9143 // In C++, check default arguments now that we have merged decls. Unless 9144 // the lexical context is the class, because in this case this is done 9145 // during delayed parsing anyway. 9146 if (!CurContext->isRecord()) 9147 CheckCXXDefaultArguments(NewFD); 9148 9149 // If this function declares a builtin function, check the type of this 9150 // declaration against the expected type for the builtin. 9151 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9152 ASTContext::GetBuiltinTypeError Error; 9153 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9154 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9155 // If the type of the builtin differs only in its exception 9156 // specification, that's OK. 9157 // FIXME: If the types do differ in this way, it would be better to 9158 // retain the 'noexcept' form of the type. 9159 if (!T.isNull() && 9160 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9161 NewFD->getType())) 9162 // The type of this function differs from the type of the builtin, 9163 // so forget about the builtin entirely. 9164 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9165 } 9166 9167 // If this function is declared as being extern "C", then check to see if 9168 // the function returns a UDT (class, struct, or union type) that is not C 9169 // compatible, and if it does, warn the user. 9170 // But, issue any diagnostic on the first declaration only. 9171 if (Previous.empty() && NewFD->isExternC()) { 9172 QualType R = NewFD->getReturnType(); 9173 if (R->isIncompleteType() && !R->isVoidType()) 9174 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9175 << NewFD << R; 9176 else if (!R.isPODType(Context) && !R->isVoidType() && 9177 !R->isObjCObjectPointerType()) 9178 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9179 } 9180 9181 // C++1z [dcl.fct]p6: 9182 // [...] whether the function has a non-throwing exception-specification 9183 // [is] part of the function type 9184 // 9185 // This results in an ABI break between C++14 and C++17 for functions whose 9186 // declared type includes an exception-specification in a parameter or 9187 // return type. (Exception specifications on the function itself are OK in 9188 // most cases, and exception specifications are not permitted in most other 9189 // contexts where they could make it into a mangling.) 9190 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9191 auto HasNoexcept = [&](QualType T) -> bool { 9192 // Strip off declarator chunks that could be between us and a function 9193 // type. We don't need to look far, exception specifications are very 9194 // restricted prior to C++17. 9195 if (auto *RT = T->getAs<ReferenceType>()) 9196 T = RT->getPointeeType(); 9197 else if (T->isAnyPointerType()) 9198 T = T->getPointeeType(); 9199 else if (auto *MPT = T->getAs<MemberPointerType>()) 9200 T = MPT->getPointeeType(); 9201 if (auto *FPT = T->getAs<FunctionProtoType>()) 9202 if (FPT->isNothrow(Context)) 9203 return true; 9204 return false; 9205 }; 9206 9207 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9208 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9209 for (QualType T : FPT->param_types()) 9210 AnyNoexcept |= HasNoexcept(T); 9211 if (AnyNoexcept) 9212 Diag(NewFD->getLocation(), 9213 diag::warn_cxx1z_compat_exception_spec_in_signature) 9214 << NewFD; 9215 } 9216 9217 if (!Redeclaration && LangOpts.CUDA) 9218 checkCUDATargetOverload(NewFD, Previous); 9219 } 9220 return Redeclaration; 9221 } 9222 9223 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9224 // C++11 [basic.start.main]p3: 9225 // A program that [...] declares main to be inline, static or 9226 // constexpr is ill-formed. 9227 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9228 // appear in a declaration of main. 9229 // static main is not an error under C99, but we should warn about it. 9230 // We accept _Noreturn main as an extension. 9231 if (FD->getStorageClass() == SC_Static) 9232 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9233 ? diag::err_static_main : diag::warn_static_main) 9234 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9235 if (FD->isInlineSpecified()) 9236 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9237 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9238 if (DS.isNoreturnSpecified()) { 9239 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9240 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9241 Diag(NoreturnLoc, diag::ext_noreturn_main); 9242 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9243 << FixItHint::CreateRemoval(NoreturnRange); 9244 } 9245 if (FD->isConstexpr()) { 9246 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9247 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9248 FD->setConstexpr(false); 9249 } 9250 9251 if (getLangOpts().OpenCL) { 9252 Diag(FD->getLocation(), diag::err_opencl_no_main) 9253 << FD->hasAttr<OpenCLKernelAttr>(); 9254 FD->setInvalidDecl(); 9255 return; 9256 } 9257 9258 QualType T = FD->getType(); 9259 assert(T->isFunctionType() && "function decl is not of function type"); 9260 const FunctionType* FT = T->castAs<FunctionType>(); 9261 9262 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9263 // In C with GNU extensions we allow main() to have non-integer return 9264 // type, but we should warn about the extension, and we disable the 9265 // implicit-return-zero rule. 9266 9267 // GCC in C mode accepts qualified 'int'. 9268 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9269 FD->setHasImplicitReturnZero(true); 9270 else { 9271 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9272 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9273 if (RTRange.isValid()) 9274 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9275 << FixItHint::CreateReplacement(RTRange, "int"); 9276 } 9277 } else { 9278 // In C and C++, main magically returns 0 if you fall off the end; 9279 // set the flag which tells us that. 9280 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9281 9282 // All the standards say that main() should return 'int'. 9283 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9284 FD->setHasImplicitReturnZero(true); 9285 else { 9286 // Otherwise, this is just a flat-out error. 9287 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9288 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9289 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9290 : FixItHint()); 9291 FD->setInvalidDecl(true); 9292 } 9293 } 9294 9295 // Treat protoless main() as nullary. 9296 if (isa<FunctionNoProtoType>(FT)) return; 9297 9298 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9299 unsigned nparams = FTP->getNumParams(); 9300 assert(FD->getNumParams() == nparams); 9301 9302 bool HasExtraParameters = (nparams > 3); 9303 9304 if (FTP->isVariadic()) { 9305 Diag(FD->getLocation(), diag::ext_variadic_main); 9306 // FIXME: if we had information about the location of the ellipsis, we 9307 // could add a FixIt hint to remove it as a parameter. 9308 } 9309 9310 // Darwin passes an undocumented fourth argument of type char**. If 9311 // other platforms start sprouting these, the logic below will start 9312 // getting shifty. 9313 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9314 HasExtraParameters = false; 9315 9316 if (HasExtraParameters) { 9317 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9318 FD->setInvalidDecl(true); 9319 nparams = 3; 9320 } 9321 9322 // FIXME: a lot of the following diagnostics would be improved 9323 // if we had some location information about types. 9324 9325 QualType CharPP = 9326 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9327 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9328 9329 for (unsigned i = 0; i < nparams; ++i) { 9330 QualType AT = FTP->getParamType(i); 9331 9332 bool mismatch = true; 9333 9334 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9335 mismatch = false; 9336 else if (Expected[i] == CharPP) { 9337 // As an extension, the following forms are okay: 9338 // char const ** 9339 // char const * const * 9340 // char * const * 9341 9342 QualifierCollector qs; 9343 const PointerType* PT; 9344 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9345 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9346 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9347 Context.CharTy)) { 9348 qs.removeConst(); 9349 mismatch = !qs.empty(); 9350 } 9351 } 9352 9353 if (mismatch) { 9354 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9355 // TODO: suggest replacing given type with expected type 9356 FD->setInvalidDecl(true); 9357 } 9358 } 9359 9360 if (nparams == 1 && !FD->isInvalidDecl()) { 9361 Diag(FD->getLocation(), diag::warn_main_one_arg); 9362 } 9363 9364 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9365 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9366 FD->setInvalidDecl(); 9367 } 9368 } 9369 9370 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9371 QualType T = FD->getType(); 9372 assert(T->isFunctionType() && "function decl is not of function type"); 9373 const FunctionType *FT = T->castAs<FunctionType>(); 9374 9375 // Set an implicit return of 'zero' if the function can return some integral, 9376 // enumeration, pointer or nullptr type. 9377 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9378 FT->getReturnType()->isAnyPointerType() || 9379 FT->getReturnType()->isNullPtrType()) 9380 // DllMain is exempt because a return value of zero means it failed. 9381 if (FD->getName() != "DllMain") 9382 FD->setHasImplicitReturnZero(true); 9383 9384 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9385 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9386 FD->setInvalidDecl(); 9387 } 9388 } 9389 9390 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9391 // FIXME: Need strict checking. In C89, we need to check for 9392 // any assignment, increment, decrement, function-calls, or 9393 // commas outside of a sizeof. In C99, it's the same list, 9394 // except that the aforementioned are allowed in unevaluated 9395 // expressions. Everything else falls under the 9396 // "may accept other forms of constant expressions" exception. 9397 // (We never end up here for C++, so the constant expression 9398 // rules there don't matter.) 9399 const Expr *Culprit; 9400 if (Init->isConstantInitializer(Context, false, &Culprit)) 9401 return false; 9402 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9403 << Culprit->getSourceRange(); 9404 return true; 9405 } 9406 9407 namespace { 9408 // Visits an initialization expression to see if OrigDecl is evaluated in 9409 // its own initialization and throws a warning if it does. 9410 class SelfReferenceChecker 9411 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9412 Sema &S; 9413 Decl *OrigDecl; 9414 bool isRecordType; 9415 bool isPODType; 9416 bool isReferenceType; 9417 9418 bool isInitList; 9419 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9420 9421 public: 9422 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9423 9424 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9425 S(S), OrigDecl(OrigDecl) { 9426 isPODType = false; 9427 isRecordType = false; 9428 isReferenceType = false; 9429 isInitList = false; 9430 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9431 isPODType = VD->getType().isPODType(S.Context); 9432 isRecordType = VD->getType()->isRecordType(); 9433 isReferenceType = VD->getType()->isReferenceType(); 9434 } 9435 } 9436 9437 // For most expressions, just call the visitor. For initializer lists, 9438 // track the index of the field being initialized since fields are 9439 // initialized in order allowing use of previously initialized fields. 9440 void CheckExpr(Expr *E) { 9441 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9442 if (!InitList) { 9443 Visit(E); 9444 return; 9445 } 9446 9447 // Track and increment the index here. 9448 isInitList = true; 9449 InitFieldIndex.push_back(0); 9450 for (auto Child : InitList->children()) { 9451 CheckExpr(cast<Expr>(Child)); 9452 ++InitFieldIndex.back(); 9453 } 9454 InitFieldIndex.pop_back(); 9455 } 9456 9457 // Returns true if MemberExpr is checked and no futher checking is needed. 9458 // Returns false if additional checking is required. 9459 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9460 llvm::SmallVector<FieldDecl*, 4> Fields; 9461 Expr *Base = E; 9462 bool ReferenceField = false; 9463 9464 // Get the field memebers used. 9465 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9466 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9467 if (!FD) 9468 return false; 9469 Fields.push_back(FD); 9470 if (FD->getType()->isReferenceType()) 9471 ReferenceField = true; 9472 Base = ME->getBase()->IgnoreParenImpCasts(); 9473 } 9474 9475 // Keep checking only if the base Decl is the same. 9476 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9477 if (!DRE || DRE->getDecl() != OrigDecl) 9478 return false; 9479 9480 // A reference field can be bound to an unininitialized field. 9481 if (CheckReference && !ReferenceField) 9482 return true; 9483 9484 // Convert FieldDecls to their index number. 9485 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9486 for (const FieldDecl *I : llvm::reverse(Fields)) 9487 UsedFieldIndex.push_back(I->getFieldIndex()); 9488 9489 // See if a warning is needed by checking the first difference in index 9490 // numbers. If field being used has index less than the field being 9491 // initialized, then the use is safe. 9492 for (auto UsedIter = UsedFieldIndex.begin(), 9493 UsedEnd = UsedFieldIndex.end(), 9494 OrigIter = InitFieldIndex.begin(), 9495 OrigEnd = InitFieldIndex.end(); 9496 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9497 if (*UsedIter < *OrigIter) 9498 return true; 9499 if (*UsedIter > *OrigIter) 9500 break; 9501 } 9502 9503 // TODO: Add a different warning which will print the field names. 9504 HandleDeclRefExpr(DRE); 9505 return true; 9506 } 9507 9508 // For most expressions, the cast is directly above the DeclRefExpr. 9509 // For conditional operators, the cast can be outside the conditional 9510 // operator if both expressions are DeclRefExpr's. 9511 void HandleValue(Expr *E) { 9512 E = E->IgnoreParens(); 9513 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9514 HandleDeclRefExpr(DRE); 9515 return; 9516 } 9517 9518 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9519 Visit(CO->getCond()); 9520 HandleValue(CO->getTrueExpr()); 9521 HandleValue(CO->getFalseExpr()); 9522 return; 9523 } 9524 9525 if (BinaryConditionalOperator *BCO = 9526 dyn_cast<BinaryConditionalOperator>(E)) { 9527 Visit(BCO->getCond()); 9528 HandleValue(BCO->getFalseExpr()); 9529 return; 9530 } 9531 9532 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9533 HandleValue(OVE->getSourceExpr()); 9534 return; 9535 } 9536 9537 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9538 if (BO->getOpcode() == BO_Comma) { 9539 Visit(BO->getLHS()); 9540 HandleValue(BO->getRHS()); 9541 return; 9542 } 9543 } 9544 9545 if (isa<MemberExpr>(E)) { 9546 if (isInitList) { 9547 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9548 false /*CheckReference*/)) 9549 return; 9550 } 9551 9552 Expr *Base = E->IgnoreParenImpCasts(); 9553 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9554 // Check for static member variables and don't warn on them. 9555 if (!isa<FieldDecl>(ME->getMemberDecl())) 9556 return; 9557 Base = ME->getBase()->IgnoreParenImpCasts(); 9558 } 9559 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9560 HandleDeclRefExpr(DRE); 9561 return; 9562 } 9563 9564 Visit(E); 9565 } 9566 9567 // Reference types not handled in HandleValue are handled here since all 9568 // uses of references are bad, not just r-value uses. 9569 void VisitDeclRefExpr(DeclRefExpr *E) { 9570 if (isReferenceType) 9571 HandleDeclRefExpr(E); 9572 } 9573 9574 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9575 if (E->getCastKind() == CK_LValueToRValue) { 9576 HandleValue(E->getSubExpr()); 9577 return; 9578 } 9579 9580 Inherited::VisitImplicitCastExpr(E); 9581 } 9582 9583 void VisitMemberExpr(MemberExpr *E) { 9584 if (isInitList) { 9585 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9586 return; 9587 } 9588 9589 // Don't warn on arrays since they can be treated as pointers. 9590 if (E->getType()->canDecayToPointerType()) return; 9591 9592 // Warn when a non-static method call is followed by non-static member 9593 // field accesses, which is followed by a DeclRefExpr. 9594 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9595 bool Warn = (MD && !MD->isStatic()); 9596 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9597 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9598 if (!isa<FieldDecl>(ME->getMemberDecl())) 9599 Warn = false; 9600 Base = ME->getBase()->IgnoreParenImpCasts(); 9601 } 9602 9603 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9604 if (Warn) 9605 HandleDeclRefExpr(DRE); 9606 return; 9607 } 9608 9609 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9610 // Visit that expression. 9611 Visit(Base); 9612 } 9613 9614 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9615 Expr *Callee = E->getCallee(); 9616 9617 if (isa<UnresolvedLookupExpr>(Callee)) 9618 return Inherited::VisitCXXOperatorCallExpr(E); 9619 9620 Visit(Callee); 9621 for (auto Arg: E->arguments()) 9622 HandleValue(Arg->IgnoreParenImpCasts()); 9623 } 9624 9625 void VisitUnaryOperator(UnaryOperator *E) { 9626 // For POD record types, addresses of its own members are well-defined. 9627 if (E->getOpcode() == UO_AddrOf && isRecordType && 9628 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9629 if (!isPODType) 9630 HandleValue(E->getSubExpr()); 9631 return; 9632 } 9633 9634 if (E->isIncrementDecrementOp()) { 9635 HandleValue(E->getSubExpr()); 9636 return; 9637 } 9638 9639 Inherited::VisitUnaryOperator(E); 9640 } 9641 9642 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9643 9644 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9645 if (E->getConstructor()->isCopyConstructor()) { 9646 Expr *ArgExpr = E->getArg(0); 9647 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9648 if (ILE->getNumInits() == 1) 9649 ArgExpr = ILE->getInit(0); 9650 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9651 if (ICE->getCastKind() == CK_NoOp) 9652 ArgExpr = ICE->getSubExpr(); 9653 HandleValue(ArgExpr); 9654 return; 9655 } 9656 Inherited::VisitCXXConstructExpr(E); 9657 } 9658 9659 void VisitCallExpr(CallExpr *E) { 9660 // Treat std::move as a use. 9661 if (E->getNumArgs() == 1) { 9662 if (FunctionDecl *FD = E->getDirectCallee()) { 9663 if (FD->isInStdNamespace() && FD->getIdentifier() && 9664 FD->getIdentifier()->isStr("move")) { 9665 HandleValue(E->getArg(0)); 9666 return; 9667 } 9668 } 9669 } 9670 9671 Inherited::VisitCallExpr(E); 9672 } 9673 9674 void VisitBinaryOperator(BinaryOperator *E) { 9675 if (E->isCompoundAssignmentOp()) { 9676 HandleValue(E->getLHS()); 9677 Visit(E->getRHS()); 9678 return; 9679 } 9680 9681 Inherited::VisitBinaryOperator(E); 9682 } 9683 9684 // A custom visitor for BinaryConditionalOperator is needed because the 9685 // regular visitor would check the condition and true expression separately 9686 // but both point to the same place giving duplicate diagnostics. 9687 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9688 Visit(E->getCond()); 9689 Visit(E->getFalseExpr()); 9690 } 9691 9692 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9693 Decl* ReferenceDecl = DRE->getDecl(); 9694 if (OrigDecl != ReferenceDecl) return; 9695 unsigned diag; 9696 if (isReferenceType) { 9697 diag = diag::warn_uninit_self_reference_in_reference_init; 9698 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9699 diag = diag::warn_static_self_reference_in_init; 9700 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9701 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9702 DRE->getDecl()->getType()->isRecordType()) { 9703 diag = diag::warn_uninit_self_reference_in_init; 9704 } else { 9705 // Local variables will be handled by the CFG analysis. 9706 return; 9707 } 9708 9709 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9710 S.PDiag(diag) 9711 << DRE->getNameInfo().getName() 9712 << OrigDecl->getLocation() 9713 << DRE->getSourceRange()); 9714 } 9715 }; 9716 9717 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9718 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9719 bool DirectInit) { 9720 // Parameters arguments are occassionially constructed with itself, 9721 // for instance, in recursive functions. Skip them. 9722 if (isa<ParmVarDecl>(OrigDecl)) 9723 return; 9724 9725 E = E->IgnoreParens(); 9726 9727 // Skip checking T a = a where T is not a record or reference type. 9728 // Doing so is a way to silence uninitialized warnings. 9729 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9730 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9731 if (ICE->getCastKind() == CK_LValueToRValue) 9732 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9733 if (DRE->getDecl() == OrigDecl) 9734 return; 9735 9736 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9737 } 9738 } // end anonymous namespace 9739 9740 namespace { 9741 // Simple wrapper to add the name of a variable or (if no variable is 9742 // available) a DeclarationName into a diagnostic. 9743 struct VarDeclOrName { 9744 VarDecl *VDecl; 9745 DeclarationName Name; 9746 9747 friend const Sema::SemaDiagnosticBuilder & 9748 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9749 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9750 } 9751 }; 9752 } // end anonymous namespace 9753 9754 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9755 DeclarationName Name, QualType Type, 9756 TypeSourceInfo *TSI, 9757 SourceRange Range, bool DirectInit, 9758 Expr *Init) { 9759 bool IsInitCapture = !VDecl; 9760 assert((!VDecl || !VDecl->isInitCapture()) && 9761 "init captures are expected to be deduced prior to initialization"); 9762 9763 VarDeclOrName VN{VDecl, Name}; 9764 9765 DeducedType *Deduced = Type->getContainedDeducedType(); 9766 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 9767 9768 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 9769 Diag(Init->getLocStart(), diag::err_deduced_class_template_not_supported); 9770 return QualType(); 9771 } 9772 9773 ArrayRef<Expr *> DeduceInits = Init; 9774 if (DirectInit) { 9775 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9776 DeduceInits = PL->exprs(); 9777 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9778 DeduceInits = IL->inits(); 9779 } 9780 9781 // Deduction only works if we have exactly one source expression. 9782 if (DeduceInits.empty()) { 9783 // It isn't possible to write this directly, but it is possible to 9784 // end up in this situation with "auto x(some_pack...);" 9785 Diag(Init->getLocStart(), IsInitCapture 9786 ? diag::err_init_capture_no_expression 9787 : diag::err_auto_var_init_no_expression) 9788 << VN << Type << Range; 9789 return QualType(); 9790 } 9791 9792 if (DeduceInits.size() > 1) { 9793 Diag(DeduceInits[1]->getLocStart(), 9794 IsInitCapture ? diag::err_init_capture_multiple_expressions 9795 : diag::err_auto_var_init_multiple_expressions) 9796 << VN << Type << Range; 9797 return QualType(); 9798 } 9799 9800 Expr *DeduceInit = DeduceInits[0]; 9801 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9802 Diag(Init->getLocStart(), IsInitCapture 9803 ? diag::err_init_capture_paren_braces 9804 : diag::err_auto_var_init_paren_braces) 9805 << isa<InitListExpr>(Init) << VN << Type << Range; 9806 return QualType(); 9807 } 9808 9809 // Expressions default to 'id' when we're in a debugger. 9810 bool DefaultedAnyToId = false; 9811 if (getLangOpts().DebuggerCastResultToId && 9812 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9813 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9814 if (Result.isInvalid()) { 9815 return QualType(); 9816 } 9817 Init = Result.get(); 9818 DefaultedAnyToId = true; 9819 } 9820 9821 // C++ [dcl.decomp]p1: 9822 // If the assignment-expression [...] has array type A and no ref-qualifier 9823 // is present, e has type cv A 9824 if (VDecl && isa<DecompositionDecl>(VDecl) && 9825 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 9826 DeduceInit->getType()->isConstantArrayType()) 9827 return Context.getQualifiedType(DeduceInit->getType(), 9828 Type.getQualifiers()); 9829 9830 QualType DeducedType; 9831 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9832 if (!IsInitCapture) 9833 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9834 else if (isa<InitListExpr>(Init)) 9835 Diag(Range.getBegin(), 9836 diag::err_init_capture_deduction_failure_from_init_list) 9837 << VN 9838 << (DeduceInit->getType().isNull() ? TSI->getType() 9839 : DeduceInit->getType()) 9840 << DeduceInit->getSourceRange(); 9841 else 9842 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9843 << VN << TSI->getType() 9844 << (DeduceInit->getType().isNull() ? TSI->getType() 9845 : DeduceInit->getType()) 9846 << DeduceInit->getSourceRange(); 9847 } 9848 9849 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9850 // 'id' instead of a specific object type prevents most of our usual 9851 // checks. 9852 // We only want to warn outside of template instantiations, though: 9853 // inside a template, the 'id' could have come from a parameter. 9854 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9855 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9856 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9857 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 9858 } 9859 9860 return DeducedType; 9861 } 9862 9863 /// AddInitializerToDecl - Adds the initializer Init to the 9864 /// declaration dcl. If DirectInit is true, this is C++ direct 9865 /// initialization rather than copy initialization. 9866 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 9867 // If there is no declaration, there was an error parsing it. Just ignore 9868 // the initializer. 9869 if (!RealDecl || RealDecl->isInvalidDecl()) { 9870 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9871 return; 9872 } 9873 9874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9875 // Pure-specifiers are handled in ActOnPureSpecifier. 9876 Diag(Method->getLocation(), diag::err_member_function_initialization) 9877 << Method->getDeclName() << Init->getSourceRange(); 9878 Method->setInvalidDecl(); 9879 return; 9880 } 9881 9882 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9883 if (!VDecl) { 9884 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9885 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9886 RealDecl->setInvalidDecl(); 9887 return; 9888 } 9889 9890 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9891 if (VDecl->getType()->isUndeducedType()) { 9892 // Attempt typo correction early so that the type of the init expression can 9893 // be deduced based on the chosen correction if the original init contains a 9894 // TypoExpr. 9895 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9896 if (!Res.isUsable()) { 9897 RealDecl->setInvalidDecl(); 9898 return; 9899 } 9900 Init = Res.get(); 9901 9902 QualType DeducedType = deduceVarTypeFromInitializer( 9903 VDecl, VDecl->getDeclName(), VDecl->getType(), 9904 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9905 if (DeducedType.isNull()) { 9906 RealDecl->setInvalidDecl(); 9907 return; 9908 } 9909 9910 VDecl->setType(DeducedType); 9911 assert(VDecl->isLinkageValid()); 9912 9913 // In ARC, infer lifetime. 9914 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9915 VDecl->setInvalidDecl(); 9916 9917 // If this is a redeclaration, check that the type we just deduced matches 9918 // the previously declared type. 9919 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9920 // We never need to merge the type, because we cannot form an incomplete 9921 // array of auto, nor deduce such a type. 9922 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9923 } 9924 9925 // Check the deduced type is valid for a variable declaration. 9926 CheckVariableDeclarationType(VDecl); 9927 if (VDecl->isInvalidDecl()) 9928 return; 9929 } 9930 9931 // dllimport cannot be used on variable definitions. 9932 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9933 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9934 VDecl->setInvalidDecl(); 9935 return; 9936 } 9937 9938 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9939 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9940 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9941 VDecl->setInvalidDecl(); 9942 return; 9943 } 9944 9945 if (!VDecl->getType()->isDependentType()) { 9946 // A definition must end up with a complete type, which means it must be 9947 // complete with the restriction that an array type might be completed by 9948 // the initializer; note that later code assumes this restriction. 9949 QualType BaseDeclType = VDecl->getType(); 9950 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9951 BaseDeclType = Array->getElementType(); 9952 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9953 diag::err_typecheck_decl_incomplete_type)) { 9954 RealDecl->setInvalidDecl(); 9955 return; 9956 } 9957 9958 // The variable can not have an abstract class type. 9959 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9960 diag::err_abstract_type_in_decl, 9961 AbstractVariableType)) 9962 VDecl->setInvalidDecl(); 9963 } 9964 9965 // If adding the initializer will turn this declaration into a definition, 9966 // and we already have a definition for this variable, diagnose or otherwise 9967 // handle the situation. 9968 VarDecl *Def; 9969 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9970 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 9971 !VDecl->isThisDeclarationADemotedDefinition() && 9972 checkVarDeclRedefinition(Def, VDecl)) 9973 return; 9974 9975 if (getLangOpts().CPlusPlus) { 9976 // C++ [class.static.data]p4 9977 // If a static data member is of const integral or const 9978 // enumeration type, its declaration in the class definition can 9979 // specify a constant-initializer which shall be an integral 9980 // constant expression (5.19). In that case, the member can appear 9981 // in integral constant expressions. The member shall still be 9982 // defined in a namespace scope if it is used in the program and the 9983 // namespace scope definition shall not contain an initializer. 9984 // 9985 // We already performed a redefinition check above, but for static 9986 // data members we also need to check whether there was an in-class 9987 // declaration with an initializer. 9988 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9989 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9990 << VDecl->getDeclName(); 9991 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9992 diag::note_previous_initializer) 9993 << 0; 9994 return; 9995 } 9996 9997 if (VDecl->hasLocalStorage()) 9998 getCurFunction()->setHasBranchProtectedScope(); 9999 10000 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10001 VDecl->setInvalidDecl(); 10002 return; 10003 } 10004 } 10005 10006 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10007 // a kernel function cannot be initialized." 10008 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10009 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10010 VDecl->setInvalidDecl(); 10011 return; 10012 } 10013 10014 // Get the decls type and save a reference for later, since 10015 // CheckInitializerTypes may change it. 10016 QualType DclT = VDecl->getType(), SavT = DclT; 10017 10018 // Expressions default to 'id' when we're in a debugger 10019 // and we are assigning it to a variable of Objective-C pointer type. 10020 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10021 Init->getType() == Context.UnknownAnyTy) { 10022 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10023 if (Result.isInvalid()) { 10024 VDecl->setInvalidDecl(); 10025 return; 10026 } 10027 Init = Result.get(); 10028 } 10029 10030 // Perform the initialization. 10031 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10032 if (!VDecl->isInvalidDecl()) { 10033 // Handle errors like: int a({0}) 10034 if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 && 10035 !canInitializeWithParenthesizedList(VDecl->getType())) 10036 if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) { 10037 Diag(VDecl->getLocation(), diag::err_list_init_in_parens) 10038 << VDecl->getType() << CXXDirectInit->getSourceRange() 10039 << FixItHint::CreateRemoval(CXXDirectInit->getLocStart()) 10040 << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd()); 10041 Init = IList; 10042 CXXDirectInit = nullptr; 10043 } 10044 10045 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10046 InitializationKind Kind = 10047 DirectInit 10048 ? CXXDirectInit 10049 ? InitializationKind::CreateDirect(VDecl->getLocation(), 10050 Init->getLocStart(), 10051 Init->getLocEnd()) 10052 : InitializationKind::CreateDirectList(VDecl->getLocation()) 10053 : InitializationKind::CreateCopy(VDecl->getLocation(), 10054 Init->getLocStart()); 10055 10056 MultiExprArg Args = Init; 10057 if (CXXDirectInit) 10058 Args = MultiExprArg(CXXDirectInit->getExprs(), 10059 CXXDirectInit->getNumExprs()); 10060 10061 // Try to correct any TypoExprs in the initialization arguments. 10062 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10063 ExprResult Res = CorrectDelayedTyposInExpr( 10064 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10065 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10066 return Init.Failed() ? ExprError() : E; 10067 }); 10068 if (Res.isInvalid()) { 10069 VDecl->setInvalidDecl(); 10070 } else if (Res.get() != Args[Idx]) { 10071 Args[Idx] = Res.get(); 10072 } 10073 } 10074 if (VDecl->isInvalidDecl()) 10075 return; 10076 10077 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10078 /*TopLevelOfInitList=*/false, 10079 /*TreatUnavailableAsInvalid=*/false); 10080 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10081 if (Result.isInvalid()) { 10082 VDecl->setInvalidDecl(); 10083 return; 10084 } 10085 10086 Init = Result.getAs<Expr>(); 10087 } 10088 10089 // Check for self-references within variable initializers. 10090 // Variables declared within a function/method body (except for references) 10091 // are handled by a dataflow analysis. 10092 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10093 VDecl->getType()->isReferenceType()) { 10094 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10095 } 10096 10097 // If the type changed, it means we had an incomplete type that was 10098 // completed by the initializer. For example: 10099 // int ary[] = { 1, 3, 5 }; 10100 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10101 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10102 VDecl->setType(DclT); 10103 10104 if (!VDecl->isInvalidDecl()) { 10105 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10106 10107 if (VDecl->hasAttr<BlocksAttr>()) 10108 checkRetainCycles(VDecl, Init); 10109 10110 // It is safe to assign a weak reference into a strong variable. 10111 // Although this code can still have problems: 10112 // id x = self.weakProp; 10113 // id y = self.weakProp; 10114 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10115 // paths through the function. This should be revisited if 10116 // -Wrepeated-use-of-weak is made flow-sensitive. 10117 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 10118 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10119 Init->getLocStart())) 10120 getCurFunction()->markSafeWeakUse(Init); 10121 } 10122 10123 // The initialization is usually a full-expression. 10124 // 10125 // FIXME: If this is a braced initialization of an aggregate, it is not 10126 // an expression, and each individual field initializer is a separate 10127 // full-expression. For instance, in: 10128 // 10129 // struct Temp { ~Temp(); }; 10130 // struct S { S(Temp); }; 10131 // struct T { S a, b; } t = { Temp(), Temp() } 10132 // 10133 // we should destroy the first Temp before constructing the second. 10134 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10135 false, 10136 VDecl->isConstexpr()); 10137 if (Result.isInvalid()) { 10138 VDecl->setInvalidDecl(); 10139 return; 10140 } 10141 Init = Result.get(); 10142 10143 // Attach the initializer to the decl. 10144 VDecl->setInit(Init); 10145 10146 if (VDecl->isLocalVarDecl()) { 10147 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10148 // static storage duration shall be constant expressions or string literals. 10149 // C++ does not have this restriction. 10150 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 10151 const Expr *Culprit; 10152 if (VDecl->getStorageClass() == SC_Static) 10153 CheckForConstantInitializer(Init, DclT); 10154 // C89 is stricter than C99 for non-static aggregate types. 10155 // C89 6.5.7p3: All the expressions [...] in an initializer list 10156 // for an object that has aggregate or union type shall be 10157 // constant expressions. 10158 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10159 isa<InitListExpr>(Init) && 10160 !Init->isConstantInitializer(Context, false, &Culprit)) 10161 Diag(Culprit->getExprLoc(), 10162 diag::ext_aggregate_init_not_constant) 10163 << Culprit->getSourceRange(); 10164 } 10165 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10166 VDecl->getLexicalDeclContext()->isRecord()) { 10167 // This is an in-class initialization for a static data member, e.g., 10168 // 10169 // struct S { 10170 // static const int value = 17; 10171 // }; 10172 10173 // C++ [class.mem]p4: 10174 // A member-declarator can contain a constant-initializer only 10175 // if it declares a static member (9.4) of const integral or 10176 // const enumeration type, see 9.4.2. 10177 // 10178 // C++11 [class.static.data]p3: 10179 // If a non-volatile non-inline const static data member is of integral 10180 // or enumeration type, its declaration in the class definition can 10181 // specify a brace-or-equal-initializer in which every initalizer-clause 10182 // that is an assignment-expression is a constant expression. A static 10183 // data member of literal type can be declared in the class definition 10184 // with the constexpr specifier; if so, its declaration shall specify a 10185 // brace-or-equal-initializer in which every initializer-clause that is 10186 // an assignment-expression is a constant expression. 10187 10188 // Do nothing on dependent types. 10189 if (DclT->isDependentType()) { 10190 10191 // Allow any 'static constexpr' members, whether or not they are of literal 10192 // type. We separately check that every constexpr variable is of literal 10193 // type. 10194 } else if (VDecl->isConstexpr()) { 10195 10196 // Require constness. 10197 } else if (!DclT.isConstQualified()) { 10198 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10199 << Init->getSourceRange(); 10200 VDecl->setInvalidDecl(); 10201 10202 // We allow integer constant expressions in all cases. 10203 } else if (DclT->isIntegralOrEnumerationType()) { 10204 // Check whether the expression is a constant expression. 10205 SourceLocation Loc; 10206 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10207 // In C++11, a non-constexpr const static data member with an 10208 // in-class initializer cannot be volatile. 10209 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10210 else if (Init->isValueDependent()) 10211 ; // Nothing to check. 10212 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10213 ; // Ok, it's an ICE! 10214 else if (Init->isEvaluatable(Context)) { 10215 // If we can constant fold the initializer through heroics, accept it, 10216 // but report this as a use of an extension for -pedantic. 10217 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10218 << Init->getSourceRange(); 10219 } else { 10220 // Otherwise, this is some crazy unknown case. Report the issue at the 10221 // location provided by the isIntegerConstantExpr failed check. 10222 Diag(Loc, diag::err_in_class_initializer_non_constant) 10223 << Init->getSourceRange(); 10224 VDecl->setInvalidDecl(); 10225 } 10226 10227 // We allow foldable floating-point constants as an extension. 10228 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10229 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10230 // it anyway and provide a fixit to add the 'constexpr'. 10231 if (getLangOpts().CPlusPlus11) { 10232 Diag(VDecl->getLocation(), 10233 diag::ext_in_class_initializer_float_type_cxx11) 10234 << DclT << Init->getSourceRange(); 10235 Diag(VDecl->getLocStart(), 10236 diag::note_in_class_initializer_float_type_cxx11) 10237 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10238 } else { 10239 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10240 << DclT << Init->getSourceRange(); 10241 10242 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10243 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10244 << Init->getSourceRange(); 10245 VDecl->setInvalidDecl(); 10246 } 10247 } 10248 10249 // Suggest adding 'constexpr' in C++11 for literal types. 10250 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10251 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10252 << DclT << Init->getSourceRange() 10253 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10254 VDecl->setConstexpr(true); 10255 10256 } else { 10257 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10258 << DclT << Init->getSourceRange(); 10259 VDecl->setInvalidDecl(); 10260 } 10261 } else if (VDecl->isFileVarDecl()) { 10262 // In C, extern is typically used to avoid tentative definitions when 10263 // declaring variables in headers, but adding an intializer makes it a 10264 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10265 // In C++, extern is often used to give implictly static const variables 10266 // external linkage, so don't warn in that case. If selectany is present, 10267 // this might be header code intended for C and C++ inclusion, so apply the 10268 // C++ rules. 10269 if (VDecl->getStorageClass() == SC_Extern && 10270 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10271 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10272 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10273 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10274 Diag(VDecl->getLocation(), diag::warn_extern_init); 10275 10276 // C99 6.7.8p4. All file scoped initializers need to be constant. 10277 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10278 CheckForConstantInitializer(Init, DclT); 10279 } 10280 10281 // We will represent direct-initialization similarly to copy-initialization: 10282 // int x(1); -as-> int x = 1; 10283 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10284 // 10285 // Clients that want to distinguish between the two forms, can check for 10286 // direct initializer using VarDecl::getInitStyle(). 10287 // A major benefit is that clients that don't particularly care about which 10288 // exactly form was it (like the CodeGen) can handle both cases without 10289 // special case code. 10290 10291 // C++ 8.5p11: 10292 // The form of initialization (using parentheses or '=') is generally 10293 // insignificant, but does matter when the entity being initialized has a 10294 // class type. 10295 if (CXXDirectInit) { 10296 assert(DirectInit && "Call-style initializer must be direct init."); 10297 VDecl->setInitStyle(VarDecl::CallInit); 10298 } else if (DirectInit) { 10299 // This must be list-initialization. No other way is direct-initialization. 10300 VDecl->setInitStyle(VarDecl::ListInit); 10301 } 10302 10303 CheckCompleteVariableDeclaration(VDecl); 10304 } 10305 10306 /// ActOnInitializerError - Given that there was an error parsing an 10307 /// initializer for the given declaration, try to return to some form 10308 /// of sanity. 10309 void Sema::ActOnInitializerError(Decl *D) { 10310 // Our main concern here is re-establishing invariants like "a 10311 // variable's type is either dependent or complete". 10312 if (!D || D->isInvalidDecl()) return; 10313 10314 VarDecl *VD = dyn_cast<VarDecl>(D); 10315 if (!VD) return; 10316 10317 // Bindings are not usable if we can't make sense of the initializer. 10318 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10319 for (auto *BD : DD->bindings()) 10320 BD->setInvalidDecl(); 10321 10322 // Auto types are meaningless if we can't make sense of the initializer. 10323 if (ParsingInitForAutoVars.count(D)) { 10324 D->setInvalidDecl(); 10325 return; 10326 } 10327 10328 QualType Ty = VD->getType(); 10329 if (Ty->isDependentType()) return; 10330 10331 // Require a complete type. 10332 if (RequireCompleteType(VD->getLocation(), 10333 Context.getBaseElementType(Ty), 10334 diag::err_typecheck_decl_incomplete_type)) { 10335 VD->setInvalidDecl(); 10336 return; 10337 } 10338 10339 // Require a non-abstract type. 10340 if (RequireNonAbstractType(VD->getLocation(), Ty, 10341 diag::err_abstract_type_in_decl, 10342 AbstractVariableType)) { 10343 VD->setInvalidDecl(); 10344 return; 10345 } 10346 10347 // Don't bother complaining about constructors or destructors, 10348 // though. 10349 } 10350 10351 /// Checks if an object of the given type can be initialized with parenthesized 10352 /// init-list. 10353 /// 10354 /// \param TargetType Type of object being initialized. 10355 /// 10356 /// The function is used to detect wrong initializations, such as 'int({0})'. 10357 /// 10358 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) { 10359 return TargetType->isDependentType() || TargetType->isRecordType() || 10360 TargetType->getContainedAutoType(); 10361 } 10362 10363 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10364 // If there is no declaration, there was an error parsing it. Just ignore it. 10365 if (!RealDecl) 10366 return; 10367 10368 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10369 QualType Type = Var->getType(); 10370 10371 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10372 if (isa<DecompositionDecl>(RealDecl)) { 10373 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10374 Var->setInvalidDecl(); 10375 return; 10376 } 10377 10378 // C++11 [dcl.spec.auto]p3 10379 if (Type->isUndeducedType()) { 10380 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10381 << Var->getDeclName() << Type; 10382 Var->setInvalidDecl(); 10383 return; 10384 } 10385 10386 // C++11 [class.static.data]p3: A static data member can be declared with 10387 // the constexpr specifier; if so, its declaration shall specify 10388 // a brace-or-equal-initializer. 10389 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10390 // the definition of a variable [...] or the declaration of a static data 10391 // member. 10392 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10393 !Var->isThisDeclarationADemotedDefinition()) { 10394 if (Var->isStaticDataMember()) { 10395 // C++1z removes the relevant rule; the in-class declaration is always 10396 // a definition there. 10397 if (!getLangOpts().CPlusPlus1z) { 10398 Diag(Var->getLocation(), 10399 diag::err_constexpr_static_mem_var_requires_init) 10400 << Var->getDeclName(); 10401 Var->setInvalidDecl(); 10402 return; 10403 } 10404 } else { 10405 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10406 Var->setInvalidDecl(); 10407 return; 10408 } 10409 } 10410 10411 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10412 // definition having the concept specifier is called a variable concept. A 10413 // concept definition refers to [...] a variable concept and its initializer. 10414 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10415 if (VTD->isConcept()) { 10416 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10417 Var->setInvalidDecl(); 10418 return; 10419 } 10420 } 10421 10422 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10423 // be initialized. 10424 if (!Var->isInvalidDecl() && 10425 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10426 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10427 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10428 Var->setInvalidDecl(); 10429 return; 10430 } 10431 10432 switch (Var->isThisDeclarationADefinition()) { 10433 case VarDecl::Definition: 10434 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10435 break; 10436 10437 // We have an out-of-line definition of a static data member 10438 // that has an in-class initializer, so we type-check this like 10439 // a declaration. 10440 // 10441 // Fall through 10442 10443 case VarDecl::DeclarationOnly: 10444 // It's only a declaration. 10445 10446 // Block scope. C99 6.7p7: If an identifier for an object is 10447 // declared with no linkage (C99 6.2.2p6), the type for the 10448 // object shall be complete. 10449 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10450 !Var->hasLinkage() && !Var->isInvalidDecl() && 10451 RequireCompleteType(Var->getLocation(), Type, 10452 diag::err_typecheck_decl_incomplete_type)) 10453 Var->setInvalidDecl(); 10454 10455 // Make sure that the type is not abstract. 10456 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10457 RequireNonAbstractType(Var->getLocation(), Type, 10458 diag::err_abstract_type_in_decl, 10459 AbstractVariableType)) 10460 Var->setInvalidDecl(); 10461 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10462 Var->getStorageClass() == SC_PrivateExtern) { 10463 Diag(Var->getLocation(), diag::warn_private_extern); 10464 Diag(Var->getLocation(), diag::note_private_extern); 10465 } 10466 10467 return; 10468 10469 case VarDecl::TentativeDefinition: 10470 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10471 // object that has file scope without an initializer, and without a 10472 // storage-class specifier or with the storage-class specifier "static", 10473 // constitutes a tentative definition. Note: A tentative definition with 10474 // external linkage is valid (C99 6.2.2p5). 10475 if (!Var->isInvalidDecl()) { 10476 if (const IncompleteArrayType *ArrayT 10477 = Context.getAsIncompleteArrayType(Type)) { 10478 if (RequireCompleteType(Var->getLocation(), 10479 ArrayT->getElementType(), 10480 diag::err_illegal_decl_array_incomplete_type)) 10481 Var->setInvalidDecl(); 10482 } else if (Var->getStorageClass() == SC_Static) { 10483 // C99 6.9.2p3: If the declaration of an identifier for an object is 10484 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10485 // declared type shall not be an incomplete type. 10486 // NOTE: code such as the following 10487 // static struct s; 10488 // struct s { int a; }; 10489 // is accepted by gcc. Hence here we issue a warning instead of 10490 // an error and we do not invalidate the static declaration. 10491 // NOTE: to avoid multiple warnings, only check the first declaration. 10492 if (Var->isFirstDecl()) 10493 RequireCompleteType(Var->getLocation(), Type, 10494 diag::ext_typecheck_decl_incomplete_type); 10495 } 10496 } 10497 10498 // Record the tentative definition; we're done. 10499 if (!Var->isInvalidDecl()) 10500 TentativeDefinitions.push_back(Var); 10501 return; 10502 } 10503 10504 // Provide a specific diagnostic for uninitialized variable 10505 // definitions with incomplete array type. 10506 if (Type->isIncompleteArrayType()) { 10507 Diag(Var->getLocation(), 10508 diag::err_typecheck_incomplete_array_needs_initializer); 10509 Var->setInvalidDecl(); 10510 return; 10511 } 10512 10513 // Provide a specific diagnostic for uninitialized variable 10514 // definitions with reference type. 10515 if (Type->isReferenceType()) { 10516 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10517 << Var->getDeclName() 10518 << SourceRange(Var->getLocation(), Var->getLocation()); 10519 Var->setInvalidDecl(); 10520 return; 10521 } 10522 10523 // Do not attempt to type-check the default initializer for a 10524 // variable with dependent type. 10525 if (Type->isDependentType()) 10526 return; 10527 10528 if (Var->isInvalidDecl()) 10529 return; 10530 10531 if (!Var->hasAttr<AliasAttr>()) { 10532 if (RequireCompleteType(Var->getLocation(), 10533 Context.getBaseElementType(Type), 10534 diag::err_typecheck_decl_incomplete_type)) { 10535 Var->setInvalidDecl(); 10536 return; 10537 } 10538 } else { 10539 return; 10540 } 10541 10542 // The variable can not have an abstract class type. 10543 if (RequireNonAbstractType(Var->getLocation(), Type, 10544 diag::err_abstract_type_in_decl, 10545 AbstractVariableType)) { 10546 Var->setInvalidDecl(); 10547 return; 10548 } 10549 10550 // Check for jumps past the implicit initializer. C++0x 10551 // clarifies that this applies to a "variable with automatic 10552 // storage duration", not a "local variable". 10553 // C++11 [stmt.dcl]p3 10554 // A program that jumps from a point where a variable with automatic 10555 // storage duration is not in scope to a point where it is in scope is 10556 // ill-formed unless the variable has scalar type, class type with a 10557 // trivial default constructor and a trivial destructor, a cv-qualified 10558 // version of one of these types, or an array of one of the preceding 10559 // types and is declared without an initializer. 10560 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10561 if (const RecordType *Record 10562 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10563 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10564 // Mark the function for further checking even if the looser rules of 10565 // C++11 do not require such checks, so that we can diagnose 10566 // incompatibilities with C++98. 10567 if (!CXXRecord->isPOD()) 10568 getCurFunction()->setHasBranchProtectedScope(); 10569 } 10570 } 10571 10572 // C++03 [dcl.init]p9: 10573 // If no initializer is specified for an object, and the 10574 // object is of (possibly cv-qualified) non-POD class type (or 10575 // array thereof), the object shall be default-initialized; if 10576 // the object is of const-qualified type, the underlying class 10577 // type shall have a user-declared default 10578 // constructor. Otherwise, if no initializer is specified for 10579 // a non- static object, the object and its subobjects, if 10580 // any, have an indeterminate initial value); if the object 10581 // or any of its subobjects are of const-qualified type, the 10582 // program is ill-formed. 10583 // C++0x [dcl.init]p11: 10584 // If no initializer is specified for an object, the object is 10585 // default-initialized; [...]. 10586 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10587 InitializationKind Kind 10588 = InitializationKind::CreateDefault(Var->getLocation()); 10589 10590 InitializationSequence InitSeq(*this, Entity, Kind, None); 10591 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10592 if (Init.isInvalid()) 10593 Var->setInvalidDecl(); 10594 else if (Init.get()) { 10595 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10596 // This is important for template substitution. 10597 Var->setInitStyle(VarDecl::CallInit); 10598 } 10599 10600 CheckCompleteVariableDeclaration(Var); 10601 } 10602 } 10603 10604 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10605 // If there is no declaration, there was an error parsing it. Ignore it. 10606 if (!D) 10607 return; 10608 10609 VarDecl *VD = dyn_cast<VarDecl>(D); 10610 if (!VD) { 10611 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10612 D->setInvalidDecl(); 10613 return; 10614 } 10615 10616 VD->setCXXForRangeDecl(true); 10617 10618 // for-range-declaration cannot be given a storage class specifier. 10619 int Error = -1; 10620 switch (VD->getStorageClass()) { 10621 case SC_None: 10622 break; 10623 case SC_Extern: 10624 Error = 0; 10625 break; 10626 case SC_Static: 10627 Error = 1; 10628 break; 10629 case SC_PrivateExtern: 10630 Error = 2; 10631 break; 10632 case SC_Auto: 10633 Error = 3; 10634 break; 10635 case SC_Register: 10636 Error = 4; 10637 break; 10638 } 10639 if (Error != -1) { 10640 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10641 << VD->getDeclName() << Error; 10642 D->setInvalidDecl(); 10643 } 10644 } 10645 10646 StmtResult 10647 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10648 IdentifierInfo *Ident, 10649 ParsedAttributes &Attrs, 10650 SourceLocation AttrEnd) { 10651 // C++1y [stmt.iter]p1: 10652 // A range-based for statement of the form 10653 // for ( for-range-identifier : for-range-initializer ) statement 10654 // is equivalent to 10655 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10656 DeclSpec DS(Attrs.getPool().getFactory()); 10657 10658 const char *PrevSpec; 10659 unsigned DiagID; 10660 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10661 getPrintingPolicy()); 10662 10663 Declarator D(DS, Declarator::ForContext); 10664 D.SetIdentifier(Ident, IdentLoc); 10665 D.takeAttributes(Attrs, AttrEnd); 10666 10667 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10668 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10669 EmptyAttrs, IdentLoc); 10670 Decl *Var = ActOnDeclarator(S, D); 10671 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10672 FinalizeDeclaration(Var); 10673 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10674 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10675 } 10676 10677 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10678 if (var->isInvalidDecl()) return; 10679 10680 if (getLangOpts().OpenCL) { 10681 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10682 // initialiser 10683 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10684 !var->hasInit()) { 10685 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10686 << 1 /*Init*/; 10687 var->setInvalidDecl(); 10688 return; 10689 } 10690 } 10691 10692 // In Objective-C, don't allow jumps past the implicit initialization of a 10693 // local retaining variable. 10694 if (getLangOpts().ObjC1 && 10695 var->hasLocalStorage()) { 10696 switch (var->getType().getObjCLifetime()) { 10697 case Qualifiers::OCL_None: 10698 case Qualifiers::OCL_ExplicitNone: 10699 case Qualifiers::OCL_Autoreleasing: 10700 break; 10701 10702 case Qualifiers::OCL_Weak: 10703 case Qualifiers::OCL_Strong: 10704 getCurFunction()->setHasBranchProtectedScope(); 10705 break; 10706 } 10707 } 10708 10709 // Warn about externally-visible variables being defined without a 10710 // prior declaration. We only want to do this for global 10711 // declarations, but we also specifically need to avoid doing it for 10712 // class members because the linkage of an anonymous class can 10713 // change if it's later given a typedef name. 10714 if (var->isThisDeclarationADefinition() && 10715 var->getDeclContext()->getRedeclContext()->isFileContext() && 10716 var->isExternallyVisible() && var->hasLinkage() && 10717 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10718 var->getLocation())) { 10719 // Find a previous declaration that's not a definition. 10720 VarDecl *prev = var->getPreviousDecl(); 10721 while (prev && prev->isThisDeclarationADefinition()) 10722 prev = prev->getPreviousDecl(); 10723 10724 if (!prev) 10725 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10726 } 10727 10728 // Cache the result of checking for constant initialization. 10729 Optional<bool> CacheHasConstInit; 10730 const Expr *CacheCulprit; 10731 auto checkConstInit = [&]() mutable { 10732 if (!CacheHasConstInit) 10733 CacheHasConstInit = var->getInit()->isConstantInitializer( 10734 Context, var->getType()->isReferenceType(), &CacheCulprit); 10735 return *CacheHasConstInit; 10736 }; 10737 10738 if (var->getTLSKind() == VarDecl::TLS_Static) { 10739 if (var->getType().isDestructedType()) { 10740 // GNU C++98 edits for __thread, [basic.start.term]p3: 10741 // The type of an object with thread storage duration shall not 10742 // have a non-trivial destructor. 10743 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10744 if (getLangOpts().CPlusPlus11) 10745 Diag(var->getLocation(), diag::note_use_thread_local); 10746 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10747 if (!checkConstInit()) { 10748 // GNU C++98 edits for __thread, [basic.start.init]p4: 10749 // An object of thread storage duration shall not require dynamic 10750 // initialization. 10751 // FIXME: Need strict checking here. 10752 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10753 << CacheCulprit->getSourceRange(); 10754 if (getLangOpts().CPlusPlus11) 10755 Diag(var->getLocation(), diag::note_use_thread_local); 10756 } 10757 } 10758 } 10759 10760 // Apply section attributes and pragmas to global variables. 10761 bool GlobalStorage = var->hasGlobalStorage(); 10762 if (GlobalStorage && var->isThisDeclarationADefinition() && 10763 ActiveTemplateInstantiations.empty()) { 10764 PragmaStack<StringLiteral *> *Stack = nullptr; 10765 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10766 if (var->getType().isConstQualified()) 10767 Stack = &ConstSegStack; 10768 else if (!var->getInit()) { 10769 Stack = &BSSSegStack; 10770 SectionFlags |= ASTContext::PSF_Write; 10771 } else { 10772 Stack = &DataSegStack; 10773 SectionFlags |= ASTContext::PSF_Write; 10774 } 10775 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10776 var->addAttr(SectionAttr::CreateImplicit( 10777 Context, SectionAttr::Declspec_allocate, 10778 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10779 } 10780 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10781 if (UnifySection(SA->getName(), SectionFlags, var)) 10782 var->dropAttr<SectionAttr>(); 10783 10784 // Apply the init_seg attribute if this has an initializer. If the 10785 // initializer turns out to not be dynamic, we'll end up ignoring this 10786 // attribute. 10787 if (CurInitSeg && var->getInit()) 10788 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10789 CurInitSegLoc)); 10790 } 10791 10792 // All the following checks are C++ only. 10793 if (!getLangOpts().CPlusPlus) { 10794 // If this variable must be emitted, add it as an initializer for the 10795 // current module. 10796 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10797 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10798 return; 10799 } 10800 10801 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10802 CheckCompleteDecompositionDeclaration(DD); 10803 10804 QualType type = var->getType(); 10805 if (type->isDependentType()) return; 10806 10807 // __block variables might require us to capture a copy-initializer. 10808 if (var->hasAttr<BlocksAttr>()) { 10809 // It's currently invalid to ever have a __block variable with an 10810 // array type; should we diagnose that here? 10811 10812 // Regardless, we don't want to ignore array nesting when 10813 // constructing this copy. 10814 if (type->isStructureOrClassType()) { 10815 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10816 SourceLocation poi = var->getLocation(); 10817 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10818 ExprResult result 10819 = PerformMoveOrCopyInitialization( 10820 InitializedEntity::InitializeBlock(poi, type, false), 10821 var, var->getType(), varRef, /*AllowNRVO=*/true); 10822 if (!result.isInvalid()) { 10823 result = MaybeCreateExprWithCleanups(result); 10824 Expr *init = result.getAs<Expr>(); 10825 Context.setBlockVarCopyInits(var, init); 10826 } 10827 } 10828 } 10829 10830 Expr *Init = var->getInit(); 10831 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10832 QualType baseType = Context.getBaseElementType(type); 10833 10834 if (!var->getDeclContext()->isDependentContext() && 10835 Init && !Init->isValueDependent()) { 10836 10837 if (var->isConstexpr()) { 10838 SmallVector<PartialDiagnosticAt, 8> Notes; 10839 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10840 SourceLocation DiagLoc = var->getLocation(); 10841 // If the note doesn't add any useful information other than a source 10842 // location, fold it into the primary diagnostic. 10843 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10844 diag::note_invalid_subexpr_in_const_expr) { 10845 DiagLoc = Notes[0].first; 10846 Notes.clear(); 10847 } 10848 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10849 << var << Init->getSourceRange(); 10850 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10851 Diag(Notes[I].first, Notes[I].second); 10852 } 10853 } else if (var->isUsableInConstantExpressions(Context)) { 10854 // Check whether the initializer of a const variable of integral or 10855 // enumeration type is an ICE now, since we can't tell whether it was 10856 // initialized by a constant expression if we check later. 10857 var->checkInitIsICE(); 10858 } 10859 10860 // Don't emit further diagnostics about constexpr globals since they 10861 // were just diagnosed. 10862 if (!var->isConstexpr() && GlobalStorage && 10863 var->hasAttr<RequireConstantInitAttr>()) { 10864 // FIXME: Need strict checking in C++03 here. 10865 bool DiagErr = getLangOpts().CPlusPlus11 10866 ? !var->checkInitIsICE() : !checkConstInit(); 10867 if (DiagErr) { 10868 auto attr = var->getAttr<RequireConstantInitAttr>(); 10869 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10870 << Init->getSourceRange(); 10871 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10872 << attr->getRange(); 10873 } 10874 } 10875 else if (!var->isConstexpr() && IsGlobal && 10876 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10877 var->getLocation())) { 10878 // Warn about globals which don't have a constant initializer. Don't 10879 // warn about globals with a non-trivial destructor because we already 10880 // warned about them. 10881 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10882 if (!(RD && !RD->hasTrivialDestructor())) { 10883 if (!checkConstInit()) 10884 Diag(var->getLocation(), diag::warn_global_constructor) 10885 << Init->getSourceRange(); 10886 } 10887 } 10888 } 10889 10890 // Require the destructor. 10891 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10892 FinalizeVarWithDestructor(var, recordType); 10893 10894 // If this variable must be emitted, add it as an initializer for the current 10895 // module. 10896 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10897 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10898 } 10899 10900 /// \brief Determines if a variable's alignment is dependent. 10901 static bool hasDependentAlignment(VarDecl *VD) { 10902 if (VD->getType()->isDependentType()) 10903 return true; 10904 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10905 if (I->isAlignmentDependent()) 10906 return true; 10907 return false; 10908 } 10909 10910 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10911 /// any semantic actions necessary after any initializer has been attached. 10912 void 10913 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10914 // Note that we are no longer parsing the initializer for this declaration. 10915 ParsingInitForAutoVars.erase(ThisDecl); 10916 10917 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10918 if (!VD) 10919 return; 10920 10921 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10922 for (auto *BD : DD->bindings()) { 10923 FinalizeDeclaration(BD); 10924 } 10925 } 10926 10927 checkAttributesAfterMerging(*this, *VD); 10928 10929 // Perform TLS alignment check here after attributes attached to the variable 10930 // which may affect the alignment have been processed. Only perform the check 10931 // if the target has a maximum TLS alignment (zero means no constraints). 10932 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10933 // Protect the check so that it's not performed on dependent types and 10934 // dependent alignments (we can't determine the alignment in that case). 10935 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 10936 !VD->isInvalidDecl()) { 10937 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10938 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10939 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10940 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10941 << (unsigned)MaxAlignChars.getQuantity(); 10942 } 10943 } 10944 } 10945 10946 if (VD->isStaticLocal()) { 10947 if (FunctionDecl *FD = 10948 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10949 // Static locals inherit dll attributes from their function. 10950 if (Attr *A = getDLLAttr(FD)) { 10951 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10952 NewAttr->setInherited(true); 10953 VD->addAttr(NewAttr); 10954 } 10955 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10956 // function, only __shared__ variables may be declared with 10957 // static storage class. 10958 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 10959 CUDADiagIfDeviceCode(VD->getLocation(), 10960 diag::err_device_static_local_var) 10961 << CurrentCUDATarget()) 10962 VD->setInvalidDecl(); 10963 } 10964 } 10965 10966 // Perform check for initializers of device-side global variables. 10967 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10968 // 7.5). We must also apply the same checks to all __shared__ 10969 // variables whether they are local or not. CUDA also allows 10970 // constant initializers for __constant__ and __device__ variables. 10971 if (getLangOpts().CUDA) { 10972 const Expr *Init = VD->getInit(); 10973 if (Init && VD->hasGlobalStorage()) { 10974 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10975 VD->hasAttr<CUDASharedAttr>()) { 10976 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 10977 bool AllowedInit = false; 10978 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10979 AllowedInit = 10980 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10981 // We'll allow constant initializers even if it's a non-empty 10982 // constructor according to CUDA rules. This deviates from NVCC, 10983 // but allows us to handle things like constexpr constructors. 10984 if (!AllowedInit && 10985 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10986 AllowedInit = VD->getInit()->isConstantInitializer( 10987 Context, VD->getType()->isReferenceType()); 10988 10989 // Also make sure that destructor, if there is one, is empty. 10990 if (AllowedInit) 10991 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10992 AllowedInit = 10993 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10994 10995 if (!AllowedInit) { 10996 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10997 ? diag::err_shared_var_init 10998 : diag::err_dynamic_var_init) 10999 << Init->getSourceRange(); 11000 VD->setInvalidDecl(); 11001 } 11002 } else { 11003 // This is a host-side global variable. Check that the initializer is 11004 // callable from the host side. 11005 const FunctionDecl *InitFn = nullptr; 11006 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11007 InitFn = CE->getConstructor(); 11008 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11009 InitFn = CE->getDirectCallee(); 11010 } 11011 if (InitFn) { 11012 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11013 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11014 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11015 << InitFnTarget << InitFn; 11016 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11017 VD->setInvalidDecl(); 11018 } 11019 } 11020 } 11021 } 11022 } 11023 11024 // Grab the dllimport or dllexport attribute off of the VarDecl. 11025 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11026 11027 // Imported static data members cannot be defined out-of-line. 11028 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11029 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11030 VD->isThisDeclarationADefinition()) { 11031 // We allow definitions of dllimport class template static data members 11032 // with a warning. 11033 CXXRecordDecl *Context = 11034 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11035 bool IsClassTemplateMember = 11036 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11037 Context->getDescribedClassTemplate(); 11038 11039 Diag(VD->getLocation(), 11040 IsClassTemplateMember 11041 ? diag::warn_attribute_dllimport_static_field_definition 11042 : diag::err_attribute_dllimport_static_field_definition); 11043 Diag(IA->getLocation(), diag::note_attribute); 11044 if (!IsClassTemplateMember) 11045 VD->setInvalidDecl(); 11046 } 11047 } 11048 11049 // dllimport/dllexport variables cannot be thread local, their TLS index 11050 // isn't exported with the variable. 11051 if (DLLAttr && VD->getTLSKind()) { 11052 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11053 if (F && getDLLAttr(F)) { 11054 assert(VD->isStaticLocal()); 11055 // But if this is a static local in a dlimport/dllexport function, the 11056 // function will never be inlined, which means the var would never be 11057 // imported, so having it marked import/export is safe. 11058 } else { 11059 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11060 << DLLAttr; 11061 VD->setInvalidDecl(); 11062 } 11063 } 11064 11065 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11066 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11067 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11068 VD->dropAttr<UsedAttr>(); 11069 } 11070 } 11071 11072 const DeclContext *DC = VD->getDeclContext(); 11073 // If there's a #pragma GCC visibility in scope, and this isn't a class 11074 // member, set the visibility of this variable. 11075 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11076 AddPushedVisibilityAttribute(VD); 11077 11078 // FIXME: Warn on unused templates. 11079 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 11080 !isa<VarTemplatePartialSpecializationDecl>(VD)) 11081 MarkUnusedFileScopedDecl(VD); 11082 11083 // Now we have parsed the initializer and can update the table of magic 11084 // tag values. 11085 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11086 !VD->getType()->isIntegralOrEnumerationType()) 11087 return; 11088 11089 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11090 const Expr *MagicValueExpr = VD->getInit(); 11091 if (!MagicValueExpr) { 11092 continue; 11093 } 11094 llvm::APSInt MagicValueInt; 11095 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11096 Diag(I->getRange().getBegin(), 11097 diag::err_type_tag_for_datatype_not_ice) 11098 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11099 continue; 11100 } 11101 if (MagicValueInt.getActiveBits() > 64) { 11102 Diag(I->getRange().getBegin(), 11103 diag::err_type_tag_for_datatype_too_large) 11104 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11105 continue; 11106 } 11107 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11108 RegisterTypeTagForDatatype(I->getArgumentKind(), 11109 MagicValue, 11110 I->getMatchingCType(), 11111 I->getLayoutCompatible(), 11112 I->getMustBeNull()); 11113 } 11114 } 11115 11116 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11117 auto *VD = dyn_cast<VarDecl>(DD); 11118 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11119 } 11120 11121 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11122 ArrayRef<Decl *> Group) { 11123 SmallVector<Decl*, 8> Decls; 11124 11125 if (DS.isTypeSpecOwned()) 11126 Decls.push_back(DS.getRepAsDecl()); 11127 11128 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11129 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11130 bool DiagnosedMultipleDecomps = false; 11131 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11132 bool DiagnosedNonDeducedAuto = false; 11133 11134 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11135 if (Decl *D = Group[i]) { 11136 // For declarators, there are some additional syntactic-ish checks we need 11137 // to perform. 11138 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11139 if (!FirstDeclaratorInGroup) 11140 FirstDeclaratorInGroup = DD; 11141 if (!FirstDecompDeclaratorInGroup) 11142 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11143 if (!FirstNonDeducedAutoInGroup && DS.containsPlaceholderType() && 11144 !hasDeducedAuto(DD)) 11145 FirstNonDeducedAutoInGroup = DD; 11146 11147 if (FirstDeclaratorInGroup != DD) { 11148 // A decomposition declaration cannot be combined with any other 11149 // declaration in the same group. 11150 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11151 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11152 diag::err_decomp_decl_not_alone) 11153 << FirstDeclaratorInGroup->getSourceRange() 11154 << DD->getSourceRange(); 11155 DiagnosedMultipleDecomps = true; 11156 } 11157 11158 // A declarator that uses 'auto' in any way other than to declare a 11159 // variable with a deduced type cannot be combined with any other 11160 // declarator in the same group. 11161 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11162 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11163 diag::err_auto_non_deduced_not_alone) 11164 << FirstNonDeducedAutoInGroup->getType() 11165 ->hasAutoForTrailingReturnType() 11166 << FirstDeclaratorInGroup->getSourceRange() 11167 << DD->getSourceRange(); 11168 DiagnosedNonDeducedAuto = true; 11169 } 11170 } 11171 } 11172 11173 Decls.push_back(D); 11174 } 11175 } 11176 11177 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11178 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11179 handleTagNumbering(Tag, S); 11180 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11181 getLangOpts().CPlusPlus) 11182 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11183 } 11184 } 11185 11186 return BuildDeclaratorGroup(Decls); 11187 } 11188 11189 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11190 /// group, performing any necessary semantic checking. 11191 Sema::DeclGroupPtrTy 11192 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11193 // C++14 [dcl.spec.auto]p7: (DR1347) 11194 // If the type that replaces the placeholder type is not the same in each 11195 // deduction, the program is ill-formed. 11196 if (Group.size() > 1) { 11197 QualType Deduced; 11198 VarDecl *DeducedDecl = nullptr; 11199 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11200 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11201 if (!D || D->isInvalidDecl()) 11202 break; 11203 AutoType *AT = D->getType()->getContainedAutoType(); 11204 if (!AT || AT->getDeducedType().isNull()) 11205 continue; 11206 if (Deduced.isNull()) { 11207 Deduced = AT->getDeducedType(); 11208 DeducedDecl = D; 11209 } else if (!Context.hasSameType(AT->getDeducedType(), Deduced)) { 11210 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11211 diag::err_auto_different_deductions) 11212 << (unsigned)AT->getKeyword() 11213 << Deduced << DeducedDecl->getDeclName() 11214 << AT->getDeducedType() << D->getDeclName() 11215 << DeducedDecl->getInit()->getSourceRange() 11216 << D->getInit()->getSourceRange(); 11217 D->setInvalidDecl(); 11218 break; 11219 } 11220 } 11221 } 11222 11223 ActOnDocumentableDecls(Group); 11224 11225 return DeclGroupPtrTy::make( 11226 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11227 } 11228 11229 void Sema::ActOnDocumentableDecl(Decl *D) { 11230 ActOnDocumentableDecls(D); 11231 } 11232 11233 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11234 // Don't parse the comment if Doxygen diagnostics are ignored. 11235 if (Group.empty() || !Group[0]) 11236 return; 11237 11238 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11239 Group[0]->getLocation()) && 11240 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11241 Group[0]->getLocation())) 11242 return; 11243 11244 if (Group.size() >= 2) { 11245 // This is a decl group. Normally it will contain only declarations 11246 // produced from declarator list. But in case we have any definitions or 11247 // additional declaration references: 11248 // 'typedef struct S {} S;' 11249 // 'typedef struct S *S;' 11250 // 'struct S *pS;' 11251 // FinalizeDeclaratorGroup adds these as separate declarations. 11252 Decl *MaybeTagDecl = Group[0]; 11253 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11254 Group = Group.slice(1); 11255 } 11256 } 11257 11258 // See if there are any new comments that are not attached to a decl. 11259 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11260 if (!Comments.empty() && 11261 !Comments.back()->isAttached()) { 11262 // There is at least one comment that not attached to a decl. 11263 // Maybe it should be attached to one of these decls? 11264 // 11265 // Note that this way we pick up not only comments that precede the 11266 // declaration, but also comments that *follow* the declaration -- thanks to 11267 // the lookahead in the lexer: we've consumed the semicolon and looked 11268 // ahead through comments. 11269 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11270 Context.getCommentForDecl(Group[i], &PP); 11271 } 11272 } 11273 11274 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11275 /// to introduce parameters into function prototype scope. 11276 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11277 const DeclSpec &DS = D.getDeclSpec(); 11278 11279 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11280 11281 // C++03 [dcl.stc]p2 also permits 'auto'. 11282 StorageClass SC = SC_None; 11283 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11284 SC = SC_Register; 11285 } else if (getLangOpts().CPlusPlus && 11286 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11287 SC = SC_Auto; 11288 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11289 Diag(DS.getStorageClassSpecLoc(), 11290 diag::err_invalid_storage_class_in_func_decl); 11291 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11292 } 11293 11294 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11295 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11296 << DeclSpec::getSpecifierName(TSCS); 11297 if (DS.isInlineSpecified()) 11298 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11299 << getLangOpts().CPlusPlus1z; 11300 if (DS.isConstexprSpecified()) 11301 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11302 << 0; 11303 if (DS.isConceptSpecified()) 11304 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11305 11306 DiagnoseFunctionSpecifiers(DS); 11307 11308 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11309 QualType parmDeclType = TInfo->getType(); 11310 11311 if (getLangOpts().CPlusPlus) { 11312 // Check that there are no default arguments inside the type of this 11313 // parameter. 11314 CheckExtraCXXDefaultArguments(D); 11315 11316 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11317 if (D.getCXXScopeSpec().isSet()) { 11318 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11319 << D.getCXXScopeSpec().getRange(); 11320 D.getCXXScopeSpec().clear(); 11321 } 11322 } 11323 11324 // Ensure we have a valid name 11325 IdentifierInfo *II = nullptr; 11326 if (D.hasName()) { 11327 II = D.getIdentifier(); 11328 if (!II) { 11329 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11330 << GetNameForDeclarator(D).getName(); 11331 D.setInvalidType(true); 11332 } 11333 } 11334 11335 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11336 if (II) { 11337 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11338 ForRedeclaration); 11339 LookupName(R, S); 11340 if (R.isSingleResult()) { 11341 NamedDecl *PrevDecl = R.getFoundDecl(); 11342 if (PrevDecl->isTemplateParameter()) { 11343 // Maybe we will complain about the shadowed template parameter. 11344 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11345 // Just pretend that we didn't see the previous declaration. 11346 PrevDecl = nullptr; 11347 } else if (S->isDeclScope(PrevDecl)) { 11348 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11349 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11350 11351 // Recover by removing the name 11352 II = nullptr; 11353 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11354 D.setInvalidType(true); 11355 } 11356 } 11357 } 11358 11359 // Temporarily put parameter variables in the translation unit, not 11360 // the enclosing context. This prevents them from accidentally 11361 // looking like class members in C++. 11362 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11363 D.getLocStart(), 11364 D.getIdentifierLoc(), II, 11365 parmDeclType, TInfo, 11366 SC); 11367 11368 if (D.isInvalidType()) 11369 New->setInvalidDecl(); 11370 11371 assert(S->isFunctionPrototypeScope()); 11372 assert(S->getFunctionPrototypeDepth() >= 1); 11373 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11374 S->getNextFunctionPrototypeIndex()); 11375 11376 // Add the parameter declaration into this scope. 11377 S->AddDecl(New); 11378 if (II) 11379 IdResolver.AddDecl(New); 11380 11381 ProcessDeclAttributes(S, New, D); 11382 11383 if (D.getDeclSpec().isModulePrivateSpecified()) 11384 Diag(New->getLocation(), diag::err_module_private_local) 11385 << 1 << New->getDeclName() 11386 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11387 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11388 11389 if (New->hasAttr<BlocksAttr>()) { 11390 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11391 } 11392 return New; 11393 } 11394 11395 /// \brief Synthesizes a variable for a parameter arising from a 11396 /// typedef. 11397 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11398 SourceLocation Loc, 11399 QualType T) { 11400 /* FIXME: setting StartLoc == Loc. 11401 Would it be worth to modify callers so as to provide proper source 11402 location for the unnamed parameters, embedding the parameter's type? */ 11403 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11404 T, Context.getTrivialTypeSourceInfo(T, Loc), 11405 SC_None, nullptr); 11406 Param->setImplicit(); 11407 return Param; 11408 } 11409 11410 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11411 // Don't diagnose unused-parameter errors in template instantiations; we 11412 // will already have done so in the template itself. 11413 if (!ActiveTemplateInstantiations.empty()) 11414 return; 11415 11416 for (const ParmVarDecl *Parameter : Parameters) { 11417 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11418 !Parameter->hasAttr<UnusedAttr>()) { 11419 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11420 << Parameter->getDeclName(); 11421 } 11422 } 11423 } 11424 11425 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11426 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11427 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11428 return; 11429 11430 // Warn if the return value is pass-by-value and larger than the specified 11431 // threshold. 11432 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11433 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11434 if (Size > LangOpts.NumLargeByValueCopy) 11435 Diag(D->getLocation(), diag::warn_return_value_size) 11436 << D->getDeclName() << Size; 11437 } 11438 11439 // Warn if any parameter is pass-by-value and larger than the specified 11440 // threshold. 11441 for (const ParmVarDecl *Parameter : Parameters) { 11442 QualType T = Parameter->getType(); 11443 if (T->isDependentType() || !T.isPODType(Context)) 11444 continue; 11445 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11446 if (Size > LangOpts.NumLargeByValueCopy) 11447 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11448 << Parameter->getDeclName() << Size; 11449 } 11450 } 11451 11452 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11453 SourceLocation NameLoc, IdentifierInfo *Name, 11454 QualType T, TypeSourceInfo *TSInfo, 11455 StorageClass SC) { 11456 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11457 if (getLangOpts().ObjCAutoRefCount && 11458 T.getObjCLifetime() == Qualifiers::OCL_None && 11459 T->isObjCLifetimeType()) { 11460 11461 Qualifiers::ObjCLifetime lifetime; 11462 11463 // Special cases for arrays: 11464 // - if it's const, use __unsafe_unretained 11465 // - otherwise, it's an error 11466 if (T->isArrayType()) { 11467 if (!T.isConstQualified()) { 11468 DelayedDiagnostics.add( 11469 sema::DelayedDiagnostic::makeForbiddenType( 11470 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11471 } 11472 lifetime = Qualifiers::OCL_ExplicitNone; 11473 } else { 11474 lifetime = T->getObjCARCImplicitLifetime(); 11475 } 11476 T = Context.getLifetimeQualifiedType(T, lifetime); 11477 } 11478 11479 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11480 Context.getAdjustedParameterType(T), 11481 TSInfo, SC, nullptr); 11482 11483 // Parameters can not be abstract class types. 11484 // For record types, this is done by the AbstractClassUsageDiagnoser once 11485 // the class has been completely parsed. 11486 if (!CurContext->isRecord() && 11487 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11488 AbstractParamType)) 11489 New->setInvalidDecl(); 11490 11491 // Parameter declarators cannot be interface types. All ObjC objects are 11492 // passed by reference. 11493 if (T->isObjCObjectType()) { 11494 SourceLocation TypeEndLoc = 11495 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11496 Diag(NameLoc, 11497 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11498 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11499 T = Context.getObjCObjectPointerType(T); 11500 New->setType(T); 11501 } 11502 11503 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11504 // duration shall not be qualified by an address-space qualifier." 11505 // Since all parameters have automatic store duration, they can not have 11506 // an address space. 11507 if (T.getAddressSpace() != 0) { 11508 // OpenCL allows function arguments declared to be an array of a type 11509 // to be qualified with an address space. 11510 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11511 Diag(NameLoc, diag::err_arg_with_address_space); 11512 New->setInvalidDecl(); 11513 } 11514 } 11515 11516 return New; 11517 } 11518 11519 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11520 SourceLocation LocAfterDecls) { 11521 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11522 11523 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11524 // for a K&R function. 11525 if (!FTI.hasPrototype) { 11526 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11527 --i; 11528 if (FTI.Params[i].Param == nullptr) { 11529 SmallString<256> Code; 11530 llvm::raw_svector_ostream(Code) 11531 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11532 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11533 << FTI.Params[i].Ident 11534 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11535 11536 // Implicitly declare the argument as type 'int' for lack of a better 11537 // type. 11538 AttributeFactory attrs; 11539 DeclSpec DS(attrs); 11540 const char* PrevSpec; // unused 11541 unsigned DiagID; // unused 11542 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11543 DiagID, Context.getPrintingPolicy()); 11544 // Use the identifier location for the type source range. 11545 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11546 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11547 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11548 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11549 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11550 } 11551 } 11552 } 11553 } 11554 11555 Decl * 11556 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11557 MultiTemplateParamsArg TemplateParameterLists, 11558 SkipBodyInfo *SkipBody) { 11559 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11560 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11561 Scope *ParentScope = FnBodyScope->getParent(); 11562 11563 D.setFunctionDefinitionKind(FDK_Definition); 11564 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11565 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11566 } 11567 11568 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11569 Consumer.HandleInlineFunctionDefinition(D); 11570 } 11571 11572 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11573 const FunctionDecl*& PossibleZeroParamPrototype) { 11574 // Don't warn about invalid declarations. 11575 if (FD->isInvalidDecl()) 11576 return false; 11577 11578 // Or declarations that aren't global. 11579 if (!FD->isGlobal()) 11580 return false; 11581 11582 // Don't warn about C++ member functions. 11583 if (isa<CXXMethodDecl>(FD)) 11584 return false; 11585 11586 // Don't warn about 'main'. 11587 if (FD->isMain()) 11588 return false; 11589 11590 // Don't warn about inline functions. 11591 if (FD->isInlined()) 11592 return false; 11593 11594 // Don't warn about function templates. 11595 if (FD->getDescribedFunctionTemplate()) 11596 return false; 11597 11598 // Don't warn about function template specializations. 11599 if (FD->isFunctionTemplateSpecialization()) 11600 return false; 11601 11602 // Don't warn for OpenCL kernels. 11603 if (FD->hasAttr<OpenCLKernelAttr>()) 11604 return false; 11605 11606 // Don't warn on explicitly deleted functions. 11607 if (FD->isDeleted()) 11608 return false; 11609 11610 bool MissingPrototype = true; 11611 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11612 Prev; Prev = Prev->getPreviousDecl()) { 11613 // Ignore any declarations that occur in function or method 11614 // scope, because they aren't visible from the header. 11615 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11616 continue; 11617 11618 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11619 if (FD->getNumParams() == 0) 11620 PossibleZeroParamPrototype = Prev; 11621 break; 11622 } 11623 11624 return MissingPrototype; 11625 } 11626 11627 void 11628 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11629 const FunctionDecl *EffectiveDefinition, 11630 SkipBodyInfo *SkipBody) { 11631 // Don't complain if we're in GNU89 mode and the previous definition 11632 // was an extern inline function. 11633 const FunctionDecl *Definition = EffectiveDefinition; 11634 if (!Definition) 11635 if (!FD->isDefined(Definition)) 11636 return; 11637 11638 if (canRedefineFunction(Definition, getLangOpts())) 11639 return; 11640 11641 // If we don't have a visible definition of the function, and it's inline or 11642 // a template, skip the new definition. 11643 if (SkipBody && !hasVisibleDefinition(Definition) && 11644 (Definition->getFormalLinkage() == InternalLinkage || 11645 Definition->isInlined() || 11646 Definition->getDescribedFunctionTemplate() || 11647 Definition->getNumTemplateParameterLists())) { 11648 SkipBody->ShouldSkip = true; 11649 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11650 makeMergedDefinitionVisible(TD, FD->getLocation()); 11651 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11652 FD->getLocation()); 11653 return; 11654 } 11655 11656 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11657 Definition->getStorageClass() == SC_Extern) 11658 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11659 << FD->getDeclName() << getLangOpts().CPlusPlus; 11660 else 11661 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11662 11663 Diag(Definition->getLocation(), diag::note_previous_definition); 11664 FD->setInvalidDecl(); 11665 } 11666 11667 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11668 Sema &S) { 11669 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11670 11671 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11672 LSI->CallOperator = CallOperator; 11673 LSI->Lambda = LambdaClass; 11674 LSI->ReturnType = CallOperator->getReturnType(); 11675 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11676 11677 if (LCD == LCD_None) 11678 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11679 else if (LCD == LCD_ByCopy) 11680 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11681 else if (LCD == LCD_ByRef) 11682 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11683 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11684 11685 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11686 LSI->Mutable = !CallOperator->isConst(); 11687 11688 // Add the captures to the LSI so they can be noted as already 11689 // captured within tryCaptureVar. 11690 auto I = LambdaClass->field_begin(); 11691 for (const auto &C : LambdaClass->captures()) { 11692 if (C.capturesVariable()) { 11693 VarDecl *VD = C.getCapturedVar(); 11694 if (VD->isInitCapture()) 11695 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11696 QualType CaptureType = VD->getType(); 11697 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11698 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11699 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11700 /*EllipsisLoc*/C.isPackExpansion() 11701 ? C.getEllipsisLoc() : SourceLocation(), 11702 CaptureType, /*Expr*/ nullptr); 11703 11704 } else if (C.capturesThis()) { 11705 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11706 /*Expr*/ nullptr, 11707 C.getCaptureKind() == LCK_StarThis); 11708 } else { 11709 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11710 } 11711 ++I; 11712 } 11713 } 11714 11715 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11716 SkipBodyInfo *SkipBody) { 11717 // Clear the last template instantiation error context. 11718 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11719 11720 if (!D) 11721 return D; 11722 FunctionDecl *FD = nullptr; 11723 11724 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11725 FD = FunTmpl->getTemplatedDecl(); 11726 else 11727 FD = cast<FunctionDecl>(D); 11728 11729 // See if this is a redefinition. 11730 if (!FD->isLateTemplateParsed()) { 11731 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11732 11733 // If we're skipping the body, we're done. Don't enter the scope. 11734 if (SkipBody && SkipBody->ShouldSkip) 11735 return D; 11736 } 11737 11738 // Mark this function as "will have a body eventually". This lets users to 11739 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11740 // this function. 11741 FD->setWillHaveBody(); 11742 11743 // If we are instantiating a generic lambda call operator, push 11744 // a LambdaScopeInfo onto the function stack. But use the information 11745 // that's already been calculated (ActOnLambdaExpr) to prime the current 11746 // LambdaScopeInfo. 11747 // When the template operator is being specialized, the LambdaScopeInfo, 11748 // has to be properly restored so that tryCaptureVariable doesn't try 11749 // and capture any new variables. In addition when calculating potential 11750 // captures during transformation of nested lambdas, it is necessary to 11751 // have the LSI properly restored. 11752 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11753 assert(ActiveTemplateInstantiations.size() && 11754 "There should be an active template instantiation on the stack " 11755 "when instantiating a generic lambda!"); 11756 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11757 } 11758 else 11759 // Enter a new function scope 11760 PushFunctionScope(); 11761 11762 // Builtin functions cannot be defined. 11763 if (unsigned BuiltinID = FD->getBuiltinID()) { 11764 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11765 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11766 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11767 FD->setInvalidDecl(); 11768 } 11769 } 11770 11771 // The return type of a function definition must be complete 11772 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11773 QualType ResultType = FD->getReturnType(); 11774 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11775 !FD->isInvalidDecl() && 11776 RequireCompleteType(FD->getLocation(), ResultType, 11777 diag::err_func_def_incomplete_result)) 11778 FD->setInvalidDecl(); 11779 11780 if (FnBodyScope) 11781 PushDeclContext(FnBodyScope, FD); 11782 11783 // Check the validity of our function parameters 11784 CheckParmsForFunctionDef(FD->parameters(), 11785 /*CheckParameterNames=*/true); 11786 11787 // Add non-parameter declarations already in the function to the current 11788 // scope. 11789 if (FnBodyScope) { 11790 for (Decl *NPD : FD->decls()) { 11791 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 11792 if (!NonParmDecl) 11793 continue; 11794 assert(!isa<ParmVarDecl>(NonParmDecl) && 11795 "parameters should not be in newly created FD yet"); 11796 11797 // If the decl has a name, make it accessible in the current scope. 11798 if (NonParmDecl->getDeclName()) 11799 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 11800 11801 // Similarly, dive into enums and fish their constants out, making them 11802 // accessible in this scope. 11803 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 11804 for (auto *EI : ED->enumerators()) 11805 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11806 } 11807 } 11808 } 11809 11810 // Introduce our parameters into the function scope 11811 for (auto Param : FD->parameters()) { 11812 Param->setOwningFunction(FD); 11813 11814 // If this has an identifier, add it to the scope stack. 11815 if (Param->getIdentifier() && FnBodyScope) { 11816 CheckShadow(FnBodyScope, Param); 11817 11818 PushOnScopeChains(Param, FnBodyScope); 11819 } 11820 } 11821 11822 // Ensure that the function's exception specification is instantiated. 11823 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11824 ResolveExceptionSpec(D->getLocation(), FPT); 11825 11826 // dllimport cannot be applied to non-inline function definitions. 11827 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11828 !FD->isTemplateInstantiation()) { 11829 assert(!FD->hasAttr<DLLExportAttr>()); 11830 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11831 FD->setInvalidDecl(); 11832 return D; 11833 } 11834 // We want to attach documentation to original Decl (which might be 11835 // a function template). 11836 ActOnDocumentableDecl(D); 11837 if (getCurLexicalContext()->isObjCContainer() && 11838 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11839 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11840 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11841 11842 return D; 11843 } 11844 11845 /// \brief Given the set of return statements within a function body, 11846 /// compute the variables that are subject to the named return value 11847 /// optimization. 11848 /// 11849 /// Each of the variables that is subject to the named return value 11850 /// optimization will be marked as NRVO variables in the AST, and any 11851 /// return statement that has a marked NRVO variable as its NRVO candidate can 11852 /// use the named return value optimization. 11853 /// 11854 /// This function applies a very simplistic algorithm for NRVO: if every return 11855 /// statement in the scope of a variable has the same NRVO candidate, that 11856 /// candidate is an NRVO variable. 11857 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11858 ReturnStmt **Returns = Scope->Returns.data(); 11859 11860 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11861 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11862 if (!NRVOCandidate->isNRVOVariable()) 11863 Returns[I]->setNRVOCandidate(nullptr); 11864 } 11865 } 11866 } 11867 11868 bool Sema::canDelayFunctionBody(const Declarator &D) { 11869 // We can't delay parsing the body of a constexpr function template (yet). 11870 if (D.getDeclSpec().isConstexprSpecified()) 11871 return false; 11872 11873 // We can't delay parsing the body of a function template with a deduced 11874 // return type (yet). 11875 if (D.getDeclSpec().containsPlaceholderType()) { 11876 // If the placeholder introduces a non-deduced trailing return type, 11877 // we can still delay parsing it. 11878 if (D.getNumTypeObjects()) { 11879 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11880 if (Outer.Kind == DeclaratorChunk::Function && 11881 Outer.Fun.hasTrailingReturnType()) { 11882 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11883 return Ty.isNull() || !Ty->isUndeducedType(); 11884 } 11885 } 11886 return false; 11887 } 11888 11889 return true; 11890 } 11891 11892 bool Sema::canSkipFunctionBody(Decl *D) { 11893 // We cannot skip the body of a function (or function template) which is 11894 // constexpr, since we may need to evaluate its body in order to parse the 11895 // rest of the file. 11896 // We cannot skip the body of a function with an undeduced return type, 11897 // because any callers of that function need to know the type. 11898 if (const FunctionDecl *FD = D->getAsFunction()) 11899 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11900 return false; 11901 return Consumer.shouldSkipFunctionBody(D); 11902 } 11903 11904 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11905 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11906 FD->setHasSkippedBody(); 11907 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11908 MD->setHasSkippedBody(); 11909 return Decl; 11910 } 11911 11912 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11913 return ActOnFinishFunctionBody(D, BodyArg, false); 11914 } 11915 11916 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11917 bool IsInstantiation) { 11918 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11919 11920 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11921 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11922 11923 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11924 CheckCompletedCoroutineBody(FD, Body); 11925 11926 if (FD) { 11927 FD->setBody(Body); 11928 11929 if (getLangOpts().CPlusPlus14) { 11930 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11931 FD->getReturnType()->isUndeducedType()) { 11932 // If the function has a deduced result type but contains no 'return' 11933 // statements, the result type as written must be exactly 'auto', and 11934 // the deduced result type is 'void'. 11935 if (!FD->getReturnType()->getAs<AutoType>()) { 11936 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11937 << FD->getReturnType(); 11938 FD->setInvalidDecl(); 11939 } else { 11940 // Substitute 'void' for the 'auto' in the type. 11941 TypeLoc ResultType = getReturnTypeLoc(FD); 11942 Context.adjustDeducedFunctionResultType( 11943 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11944 } 11945 } 11946 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11947 // In C++11, we don't use 'auto' deduction rules for lambda call 11948 // operators because we don't support return type deduction. 11949 auto *LSI = getCurLambda(); 11950 if (LSI->HasImplicitReturnType) { 11951 deduceClosureReturnType(*LSI); 11952 11953 // C++11 [expr.prim.lambda]p4: 11954 // [...] if there are no return statements in the compound-statement 11955 // [the deduced type is] the type void 11956 QualType RetType = 11957 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11958 11959 // Update the return type to the deduced type. 11960 const FunctionProtoType *Proto = 11961 FD->getType()->getAs<FunctionProtoType>(); 11962 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11963 Proto->getExtProtoInfo())); 11964 } 11965 } 11966 11967 // The only way to be included in UndefinedButUsed is if there is an 11968 // ODR use before the definition. Avoid the expensive map lookup if this 11969 // is the first declaration. 11970 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11971 if (!FD->isExternallyVisible()) 11972 UndefinedButUsed.erase(FD); 11973 else if (FD->isInlined() && 11974 !LangOpts.GNUInline && 11975 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11976 UndefinedButUsed.erase(FD); 11977 } 11978 11979 // If the function implicitly returns zero (like 'main') or is naked, 11980 // don't complain about missing return statements. 11981 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11982 WP.disableCheckFallThrough(); 11983 11984 // MSVC permits the use of pure specifier (=0) on function definition, 11985 // defined at class scope, warn about this non-standard construct. 11986 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11987 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11988 11989 if (!FD->isInvalidDecl()) { 11990 // Don't diagnose unused parameters of defaulted or deleted functions. 11991 if (!FD->isDeleted() && !FD->isDefaulted()) 11992 DiagnoseUnusedParameters(FD->parameters()); 11993 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11994 FD->getReturnType(), FD); 11995 11996 // If this is a structor, we need a vtable. 11997 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11998 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11999 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12000 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12001 12002 // Try to apply the named return value optimization. We have to check 12003 // if we can do this here because lambdas keep return statements around 12004 // to deduce an implicit return type. 12005 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12006 !FD->isDependentContext()) 12007 computeNRVO(Body, getCurFunction()); 12008 } 12009 12010 // GNU warning -Wmissing-prototypes: 12011 // Warn if a global function is defined without a previous 12012 // prototype declaration. This warning is issued even if the 12013 // definition itself provides a prototype. The aim is to detect 12014 // global functions that fail to be declared in header files. 12015 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12016 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12017 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12018 12019 if (PossibleZeroParamPrototype) { 12020 // We found a declaration that is not a prototype, 12021 // but that could be a zero-parameter prototype 12022 if (TypeSourceInfo *TI = 12023 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12024 TypeLoc TL = TI->getTypeLoc(); 12025 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12026 Diag(PossibleZeroParamPrototype->getLocation(), 12027 diag::note_declaration_not_a_prototype) 12028 << PossibleZeroParamPrototype 12029 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12030 } 12031 } 12032 12033 // GNU warning -Wstrict-prototypes 12034 // Warn if K&R function is defined without a previous declaration. 12035 // This warning is issued only if the definition itself does not provide 12036 // a prototype. Only K&R definitions do not provide a prototype. 12037 // An empty list in a function declarator that is part of a definition 12038 // of that function specifies that the function has no parameters 12039 // (C99 6.7.5.3p14) 12040 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12041 !LangOpts.CPlusPlus) { 12042 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12043 TypeLoc TL = TI->getTypeLoc(); 12044 FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>(); 12045 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12046 } 12047 } 12048 12049 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12050 const CXXMethodDecl *KeyFunction; 12051 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12052 MD->isVirtual() && 12053 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12054 MD == KeyFunction->getCanonicalDecl()) { 12055 // Update the key-function state if necessary for this ABI. 12056 if (FD->isInlined() && 12057 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12058 Context.setNonKeyFunction(MD); 12059 12060 // If the newly-chosen key function is already defined, then we 12061 // need to mark the vtable as used retroactively. 12062 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12063 const FunctionDecl *Definition; 12064 if (KeyFunction && KeyFunction->isDefined(Definition)) 12065 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12066 } else { 12067 // We just defined they key function; mark the vtable as used. 12068 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12069 } 12070 } 12071 } 12072 12073 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12074 "Function parsing confused"); 12075 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12076 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12077 MD->setBody(Body); 12078 if (!MD->isInvalidDecl()) { 12079 DiagnoseUnusedParameters(MD->parameters()); 12080 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12081 MD->getReturnType(), MD); 12082 12083 if (Body) 12084 computeNRVO(Body, getCurFunction()); 12085 } 12086 if (getCurFunction()->ObjCShouldCallSuper) { 12087 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12088 << MD->getSelector().getAsString(); 12089 getCurFunction()->ObjCShouldCallSuper = false; 12090 } 12091 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12092 const ObjCMethodDecl *InitMethod = nullptr; 12093 bool isDesignated = 12094 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12095 assert(isDesignated && InitMethod); 12096 (void)isDesignated; 12097 12098 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12099 auto IFace = MD->getClassInterface(); 12100 if (!IFace) 12101 return false; 12102 auto SuperD = IFace->getSuperClass(); 12103 if (!SuperD) 12104 return false; 12105 return SuperD->getIdentifier() == 12106 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12107 }; 12108 // Don't issue this warning for unavailable inits or direct subclasses 12109 // of NSObject. 12110 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12111 Diag(MD->getLocation(), 12112 diag::warn_objc_designated_init_missing_super_call); 12113 Diag(InitMethod->getLocation(), 12114 diag::note_objc_designated_init_marked_here); 12115 } 12116 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12117 } 12118 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12119 // Don't issue this warning for unavaialable inits. 12120 if (!MD->isUnavailable()) 12121 Diag(MD->getLocation(), 12122 diag::warn_objc_secondary_init_missing_init_call); 12123 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12124 } 12125 } else { 12126 return nullptr; 12127 } 12128 12129 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12130 DiagnoseUnguardedAvailabilityViolations(dcl); 12131 12132 assert(!getCurFunction()->ObjCShouldCallSuper && 12133 "This should only be set for ObjC methods, which should have been " 12134 "handled in the block above."); 12135 12136 // Verify and clean out per-function state. 12137 if (Body && (!FD || !FD->isDefaulted())) { 12138 // C++ constructors that have function-try-blocks can't have return 12139 // statements in the handlers of that block. (C++ [except.handle]p14) 12140 // Verify this. 12141 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12142 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12143 12144 // Verify that gotos and switch cases don't jump into scopes illegally. 12145 if (getCurFunction()->NeedsScopeChecking() && 12146 !PP.isCodeCompletionEnabled()) 12147 DiagnoseInvalidJumps(Body); 12148 12149 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12150 if (!Destructor->getParent()->isDependentType()) 12151 CheckDestructor(Destructor); 12152 12153 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12154 Destructor->getParent()); 12155 } 12156 12157 // If any errors have occurred, clear out any temporaries that may have 12158 // been leftover. This ensures that these temporaries won't be picked up for 12159 // deletion in some later function. 12160 if (getDiagnostics().hasErrorOccurred() || 12161 getDiagnostics().getSuppressAllDiagnostics()) { 12162 DiscardCleanupsInEvaluationContext(); 12163 } 12164 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12165 !isa<FunctionTemplateDecl>(dcl)) { 12166 // Since the body is valid, issue any analysis-based warnings that are 12167 // enabled. 12168 ActivePolicy = &WP; 12169 } 12170 12171 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12172 (!CheckConstexprFunctionDecl(FD) || 12173 !CheckConstexprFunctionBody(FD, Body))) 12174 FD->setInvalidDecl(); 12175 12176 if (FD && FD->hasAttr<NakedAttr>()) { 12177 for (const Stmt *S : Body->children()) { 12178 // Allow local register variables without initializer as they don't 12179 // require prologue. 12180 bool RegisterVariables = false; 12181 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12182 for (const auto *Decl : DS->decls()) { 12183 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12184 RegisterVariables = 12185 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12186 if (!RegisterVariables) 12187 break; 12188 } 12189 } 12190 } 12191 if (RegisterVariables) 12192 continue; 12193 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12194 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12195 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12196 FD->setInvalidDecl(); 12197 break; 12198 } 12199 } 12200 } 12201 12202 assert(ExprCleanupObjects.size() == 12203 ExprEvalContexts.back().NumCleanupObjects && 12204 "Leftover temporaries in function"); 12205 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12206 assert(MaybeODRUseExprs.empty() && 12207 "Leftover expressions for odr-use checking"); 12208 } 12209 12210 if (!IsInstantiation) 12211 PopDeclContext(); 12212 12213 PopFunctionScopeInfo(ActivePolicy, dcl); 12214 // If any errors have occurred, clear out any temporaries that may have 12215 // been leftover. This ensures that these temporaries won't be picked up for 12216 // deletion in some later function. 12217 if (getDiagnostics().hasErrorOccurred()) { 12218 DiscardCleanupsInEvaluationContext(); 12219 } 12220 12221 return dcl; 12222 } 12223 12224 /// When we finish delayed parsing of an attribute, we must attach it to the 12225 /// relevant Decl. 12226 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12227 ParsedAttributes &Attrs) { 12228 // Always attach attributes to the underlying decl. 12229 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12230 D = TD->getTemplatedDecl(); 12231 ProcessDeclAttributeList(S, D, Attrs.getList()); 12232 12233 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12234 if (Method->isStatic()) 12235 checkThisInStaticMemberFunctionAttributes(Method); 12236 } 12237 12238 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12239 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12240 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12241 IdentifierInfo &II, Scope *S) { 12242 // Before we produce a declaration for an implicitly defined 12243 // function, see whether there was a locally-scoped declaration of 12244 // this name as a function or variable. If so, use that 12245 // (non-visible) declaration, and complain about it. 12246 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12247 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12248 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12249 return ExternCPrev; 12250 } 12251 12252 // Extension in C99. Legal in C90, but warn about it. 12253 unsigned diag_id; 12254 if (II.getName().startswith("__builtin_")) 12255 diag_id = diag::warn_builtin_unknown; 12256 else if (getLangOpts().C99) 12257 diag_id = diag::ext_implicit_function_decl; 12258 else 12259 diag_id = diag::warn_implicit_function_decl; 12260 Diag(Loc, diag_id) << &II; 12261 12262 // Because typo correction is expensive, only do it if the implicit 12263 // function declaration is going to be treated as an error. 12264 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12265 TypoCorrection Corrected; 12266 if (S && 12267 (Corrected = CorrectTypo( 12268 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12269 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12270 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12271 /*ErrorRecovery*/false); 12272 } 12273 12274 // Set a Declarator for the implicit definition: int foo(); 12275 const char *Dummy; 12276 AttributeFactory attrFactory; 12277 DeclSpec DS(attrFactory); 12278 unsigned DiagID; 12279 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12280 Context.getPrintingPolicy()); 12281 (void)Error; // Silence warning. 12282 assert(!Error && "Error setting up implicit decl!"); 12283 SourceLocation NoLoc; 12284 Declarator D(DS, Declarator::BlockContext); 12285 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12286 /*IsAmbiguous=*/false, 12287 /*LParenLoc=*/NoLoc, 12288 /*Params=*/nullptr, 12289 /*NumParams=*/0, 12290 /*EllipsisLoc=*/NoLoc, 12291 /*RParenLoc=*/NoLoc, 12292 /*TypeQuals=*/0, 12293 /*RefQualifierIsLvalueRef=*/true, 12294 /*RefQualifierLoc=*/NoLoc, 12295 /*ConstQualifierLoc=*/NoLoc, 12296 /*VolatileQualifierLoc=*/NoLoc, 12297 /*RestrictQualifierLoc=*/NoLoc, 12298 /*MutableLoc=*/NoLoc, 12299 EST_None, 12300 /*ESpecRange=*/SourceRange(), 12301 /*Exceptions=*/nullptr, 12302 /*ExceptionRanges=*/nullptr, 12303 /*NumExceptions=*/0, 12304 /*NoexceptExpr=*/nullptr, 12305 /*ExceptionSpecTokens=*/nullptr, 12306 /*DeclsInPrototype=*/None, 12307 Loc, Loc, D), 12308 DS.getAttributes(), 12309 SourceLocation()); 12310 D.SetIdentifier(&II, Loc); 12311 12312 // Insert this function into translation-unit scope. 12313 12314 DeclContext *PrevDC = CurContext; 12315 CurContext = Context.getTranslationUnitDecl(); 12316 12317 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12318 FD->setImplicit(); 12319 12320 CurContext = PrevDC; 12321 12322 AddKnownFunctionAttributes(FD); 12323 12324 return FD; 12325 } 12326 12327 /// \brief Adds any function attributes that we know a priori based on 12328 /// the declaration of this function. 12329 /// 12330 /// These attributes can apply both to implicitly-declared builtins 12331 /// (like __builtin___printf_chk) or to library-declared functions 12332 /// like NSLog or printf. 12333 /// 12334 /// We need to check for duplicate attributes both here and where user-written 12335 /// attributes are applied to declarations. 12336 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12337 if (FD->isInvalidDecl()) 12338 return; 12339 12340 // If this is a built-in function, map its builtin attributes to 12341 // actual attributes. 12342 if (unsigned BuiltinID = FD->getBuiltinID()) { 12343 // Handle printf-formatting attributes. 12344 unsigned FormatIdx; 12345 bool HasVAListArg; 12346 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12347 if (!FD->hasAttr<FormatAttr>()) { 12348 const char *fmt = "printf"; 12349 unsigned int NumParams = FD->getNumParams(); 12350 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12351 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12352 fmt = "NSString"; 12353 FD->addAttr(FormatAttr::CreateImplicit(Context, 12354 &Context.Idents.get(fmt), 12355 FormatIdx+1, 12356 HasVAListArg ? 0 : FormatIdx+2, 12357 FD->getLocation())); 12358 } 12359 } 12360 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12361 HasVAListArg)) { 12362 if (!FD->hasAttr<FormatAttr>()) 12363 FD->addAttr(FormatAttr::CreateImplicit(Context, 12364 &Context.Idents.get("scanf"), 12365 FormatIdx+1, 12366 HasVAListArg ? 0 : FormatIdx+2, 12367 FD->getLocation())); 12368 } 12369 12370 // Mark const if we don't care about errno and that is the only 12371 // thing preventing the function from being const. This allows 12372 // IRgen to use LLVM intrinsics for such functions. 12373 if (!getLangOpts().MathErrno && 12374 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12375 if (!FD->hasAttr<ConstAttr>()) 12376 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12377 } 12378 12379 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12380 !FD->hasAttr<ReturnsTwiceAttr>()) 12381 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12382 FD->getLocation())); 12383 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12384 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12385 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12386 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12387 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12388 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12389 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12390 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12391 // Add the appropriate attribute, depending on the CUDA compilation mode 12392 // and which target the builtin belongs to. For example, during host 12393 // compilation, aux builtins are __device__, while the rest are __host__. 12394 if (getLangOpts().CUDAIsDevice != 12395 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12396 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12397 else 12398 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12399 } 12400 } 12401 12402 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12403 // throw, add an implicit nothrow attribute to any extern "C" function we come 12404 // across. 12405 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12406 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12407 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12408 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12409 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12410 } 12411 12412 IdentifierInfo *Name = FD->getIdentifier(); 12413 if (!Name) 12414 return; 12415 if ((!getLangOpts().CPlusPlus && 12416 FD->getDeclContext()->isTranslationUnit()) || 12417 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12418 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12419 LinkageSpecDecl::lang_c)) { 12420 // Okay: this could be a libc/libm/Objective-C function we know 12421 // about. 12422 } else 12423 return; 12424 12425 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12426 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12427 // target-specific builtins, perhaps? 12428 if (!FD->hasAttr<FormatAttr>()) 12429 FD->addAttr(FormatAttr::CreateImplicit(Context, 12430 &Context.Idents.get("printf"), 2, 12431 Name->isStr("vasprintf") ? 0 : 3, 12432 FD->getLocation())); 12433 } 12434 12435 if (Name->isStr("__CFStringMakeConstantString")) { 12436 // We already have a __builtin___CFStringMakeConstantString, 12437 // but builds that use -fno-constant-cfstrings don't go through that. 12438 if (!FD->hasAttr<FormatArgAttr>()) 12439 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12440 FD->getLocation())); 12441 } 12442 } 12443 12444 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12445 TypeSourceInfo *TInfo) { 12446 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12447 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12448 12449 if (!TInfo) { 12450 assert(D.isInvalidType() && "no declarator info for valid type"); 12451 TInfo = Context.getTrivialTypeSourceInfo(T); 12452 } 12453 12454 // Scope manipulation handled by caller. 12455 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12456 D.getLocStart(), 12457 D.getIdentifierLoc(), 12458 D.getIdentifier(), 12459 TInfo); 12460 12461 // Bail out immediately if we have an invalid declaration. 12462 if (D.isInvalidType()) { 12463 NewTD->setInvalidDecl(); 12464 return NewTD; 12465 } 12466 12467 if (D.getDeclSpec().isModulePrivateSpecified()) { 12468 if (CurContext->isFunctionOrMethod()) 12469 Diag(NewTD->getLocation(), diag::err_module_private_local) 12470 << 2 << NewTD->getDeclName() 12471 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12472 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12473 else 12474 NewTD->setModulePrivate(); 12475 } 12476 12477 // C++ [dcl.typedef]p8: 12478 // If the typedef declaration defines an unnamed class (or 12479 // enum), the first typedef-name declared by the declaration 12480 // to be that class type (or enum type) is used to denote the 12481 // class type (or enum type) for linkage purposes only. 12482 // We need to check whether the type was declared in the declaration. 12483 switch (D.getDeclSpec().getTypeSpecType()) { 12484 case TST_enum: 12485 case TST_struct: 12486 case TST_interface: 12487 case TST_union: 12488 case TST_class: { 12489 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12490 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12491 break; 12492 } 12493 12494 default: 12495 break; 12496 } 12497 12498 return NewTD; 12499 } 12500 12501 /// \brief Check that this is a valid underlying type for an enum declaration. 12502 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12503 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12504 QualType T = TI->getType(); 12505 12506 if (T->isDependentType()) 12507 return false; 12508 12509 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12510 if (BT->isInteger()) 12511 return false; 12512 12513 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12514 return true; 12515 } 12516 12517 /// Check whether this is a valid redeclaration of a previous enumeration. 12518 /// \return true if the redeclaration was invalid. 12519 bool Sema::CheckEnumRedeclaration( 12520 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12521 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12522 bool IsFixed = !EnumUnderlyingTy.isNull(); 12523 12524 if (IsScoped != Prev->isScoped()) { 12525 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12526 << Prev->isScoped(); 12527 Diag(Prev->getLocation(), diag::note_previous_declaration); 12528 return true; 12529 } 12530 12531 if (IsFixed && Prev->isFixed()) { 12532 if (!EnumUnderlyingTy->isDependentType() && 12533 !Prev->getIntegerType()->isDependentType() && 12534 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12535 Prev->getIntegerType())) { 12536 // TODO: Highlight the underlying type of the redeclaration. 12537 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12538 << EnumUnderlyingTy << Prev->getIntegerType(); 12539 Diag(Prev->getLocation(), diag::note_previous_declaration) 12540 << Prev->getIntegerTypeRange(); 12541 return true; 12542 } 12543 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12544 ; 12545 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12546 ; 12547 } else if (IsFixed != Prev->isFixed()) { 12548 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12549 << Prev->isFixed(); 12550 Diag(Prev->getLocation(), diag::note_previous_declaration); 12551 return true; 12552 } 12553 12554 return false; 12555 } 12556 12557 /// \brief Get diagnostic %select index for tag kind for 12558 /// redeclaration diagnostic message. 12559 /// WARNING: Indexes apply to particular diagnostics only! 12560 /// 12561 /// \returns diagnostic %select index. 12562 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12563 switch (Tag) { 12564 case TTK_Struct: return 0; 12565 case TTK_Interface: return 1; 12566 case TTK_Class: return 2; 12567 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12568 } 12569 } 12570 12571 /// \brief Determine if tag kind is a class-key compatible with 12572 /// class for redeclaration (class, struct, or __interface). 12573 /// 12574 /// \returns true iff the tag kind is compatible. 12575 static bool isClassCompatTagKind(TagTypeKind Tag) 12576 { 12577 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12578 } 12579 12580 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12581 TagTypeKind TTK) { 12582 if (isa<TypedefDecl>(PrevDecl)) 12583 return NTK_Typedef; 12584 else if (isa<TypeAliasDecl>(PrevDecl)) 12585 return NTK_TypeAlias; 12586 else if (isa<ClassTemplateDecl>(PrevDecl)) 12587 return NTK_Template; 12588 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12589 return NTK_TypeAliasTemplate; 12590 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12591 return NTK_TemplateTemplateArgument; 12592 switch (TTK) { 12593 case TTK_Struct: 12594 case TTK_Interface: 12595 case TTK_Class: 12596 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12597 case TTK_Union: 12598 return NTK_NonUnion; 12599 case TTK_Enum: 12600 return NTK_NonEnum; 12601 } 12602 llvm_unreachable("invalid TTK"); 12603 } 12604 12605 /// \brief Determine whether a tag with a given kind is acceptable 12606 /// as a redeclaration of the given tag declaration. 12607 /// 12608 /// \returns true if the new tag kind is acceptable, false otherwise. 12609 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12610 TagTypeKind NewTag, bool isDefinition, 12611 SourceLocation NewTagLoc, 12612 const IdentifierInfo *Name) { 12613 // C++ [dcl.type.elab]p3: 12614 // The class-key or enum keyword present in the 12615 // elaborated-type-specifier shall agree in kind with the 12616 // declaration to which the name in the elaborated-type-specifier 12617 // refers. This rule also applies to the form of 12618 // elaborated-type-specifier that declares a class-name or 12619 // friend class since it can be construed as referring to the 12620 // definition of the class. Thus, in any 12621 // elaborated-type-specifier, the enum keyword shall be used to 12622 // refer to an enumeration (7.2), the union class-key shall be 12623 // used to refer to a union (clause 9), and either the class or 12624 // struct class-key shall be used to refer to a class (clause 9) 12625 // declared using the class or struct class-key. 12626 TagTypeKind OldTag = Previous->getTagKind(); 12627 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12628 if (OldTag == NewTag) 12629 return true; 12630 12631 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12632 // Warn about the struct/class tag mismatch. 12633 bool isTemplate = false; 12634 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12635 isTemplate = Record->getDescribedClassTemplate(); 12636 12637 if (!ActiveTemplateInstantiations.empty()) { 12638 // In a template instantiation, do not offer fix-its for tag mismatches 12639 // since they usually mess up the template instead of fixing the problem. 12640 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12641 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12642 << getRedeclDiagFromTagKind(OldTag); 12643 return true; 12644 } 12645 12646 if (isDefinition) { 12647 // On definitions, check previous tags and issue a fix-it for each 12648 // one that doesn't match the current tag. 12649 if (Previous->getDefinition()) { 12650 // Don't suggest fix-its for redefinitions. 12651 return true; 12652 } 12653 12654 bool previousMismatch = false; 12655 for (auto I : Previous->redecls()) { 12656 if (I->getTagKind() != NewTag) { 12657 if (!previousMismatch) { 12658 previousMismatch = true; 12659 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12660 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12661 << getRedeclDiagFromTagKind(I->getTagKind()); 12662 } 12663 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12664 << getRedeclDiagFromTagKind(NewTag) 12665 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12666 TypeWithKeyword::getTagTypeKindName(NewTag)); 12667 } 12668 } 12669 return true; 12670 } 12671 12672 // Check for a previous definition. If current tag and definition 12673 // are same type, do nothing. If no definition, but disagree with 12674 // with previous tag type, give a warning, but no fix-it. 12675 const TagDecl *Redecl = Previous->getDefinition() ? 12676 Previous->getDefinition() : Previous; 12677 if (Redecl->getTagKind() == NewTag) { 12678 return true; 12679 } 12680 12681 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12682 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12683 << getRedeclDiagFromTagKind(OldTag); 12684 Diag(Redecl->getLocation(), diag::note_previous_use); 12685 12686 // If there is a previous definition, suggest a fix-it. 12687 if (Previous->getDefinition()) { 12688 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12689 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12690 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12691 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12692 } 12693 12694 return true; 12695 } 12696 return false; 12697 } 12698 12699 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12700 /// from an outer enclosing namespace or file scope inside a friend declaration. 12701 /// This should provide the commented out code in the following snippet: 12702 /// namespace N { 12703 /// struct X; 12704 /// namespace M { 12705 /// struct Y { friend struct /*N::*/ X; }; 12706 /// } 12707 /// } 12708 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12709 SourceLocation NameLoc) { 12710 // While the decl is in a namespace, do repeated lookup of that name and see 12711 // if we get the same namespace back. If we do not, continue until 12712 // translation unit scope, at which point we have a fully qualified NNS. 12713 SmallVector<IdentifierInfo *, 4> Namespaces; 12714 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12715 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12716 // This tag should be declared in a namespace, which can only be enclosed by 12717 // other namespaces. Bail if there's an anonymous namespace in the chain. 12718 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12719 if (!Namespace || Namespace->isAnonymousNamespace()) 12720 return FixItHint(); 12721 IdentifierInfo *II = Namespace->getIdentifier(); 12722 Namespaces.push_back(II); 12723 NamedDecl *Lookup = SemaRef.LookupSingleName( 12724 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12725 if (Lookup == Namespace) 12726 break; 12727 } 12728 12729 // Once we have all the namespaces, reverse them to go outermost first, and 12730 // build an NNS. 12731 SmallString<64> Insertion; 12732 llvm::raw_svector_ostream OS(Insertion); 12733 if (DC->isTranslationUnit()) 12734 OS << "::"; 12735 std::reverse(Namespaces.begin(), Namespaces.end()); 12736 for (auto *II : Namespaces) 12737 OS << II->getName() << "::"; 12738 return FixItHint::CreateInsertion(NameLoc, Insertion); 12739 } 12740 12741 /// \brief Determine whether a tag originally declared in context \p OldDC can 12742 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12743 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12744 /// using-declaration). 12745 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12746 DeclContext *NewDC) { 12747 OldDC = OldDC->getRedeclContext(); 12748 NewDC = NewDC->getRedeclContext(); 12749 12750 if (OldDC->Equals(NewDC)) 12751 return true; 12752 12753 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12754 // encloses the other). 12755 if (S.getLangOpts().MSVCCompat && 12756 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12757 return true; 12758 12759 return false; 12760 } 12761 12762 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12763 /// former case, Name will be non-null. In the later case, Name will be null. 12764 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12765 /// reference/declaration/definition of a tag. 12766 /// 12767 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12768 /// trailing-type-specifier) other than one in an alias-declaration. 12769 /// 12770 /// \param SkipBody If non-null, will be set to indicate if the caller should 12771 /// skip the definition of this tag and treat it as if it were a declaration. 12772 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12773 SourceLocation KWLoc, CXXScopeSpec &SS, 12774 IdentifierInfo *Name, SourceLocation NameLoc, 12775 AttributeList *Attr, AccessSpecifier AS, 12776 SourceLocation ModulePrivateLoc, 12777 MultiTemplateParamsArg TemplateParameterLists, 12778 bool &OwnedDecl, bool &IsDependent, 12779 SourceLocation ScopedEnumKWLoc, 12780 bool ScopedEnumUsesClassTag, 12781 TypeResult UnderlyingType, 12782 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12783 // If this is not a definition, it must have a name. 12784 IdentifierInfo *OrigName = Name; 12785 assert((Name != nullptr || TUK == TUK_Definition) && 12786 "Nameless record must be a definition!"); 12787 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12788 12789 OwnedDecl = false; 12790 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12791 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12792 12793 // FIXME: Check explicit specializations more carefully. 12794 bool isExplicitSpecialization = false; 12795 bool Invalid = false; 12796 12797 // We only need to do this matching if we have template parameters 12798 // or a scope specifier, which also conveniently avoids this work 12799 // for non-C++ cases. 12800 if (TemplateParameterLists.size() > 0 || 12801 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12802 if (TemplateParameterList *TemplateParams = 12803 MatchTemplateParametersToScopeSpecifier( 12804 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12805 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12806 if (Kind == TTK_Enum) { 12807 Diag(KWLoc, diag::err_enum_template); 12808 return nullptr; 12809 } 12810 12811 if (TemplateParams->size() > 0) { 12812 // This is a declaration or definition of a class template (which may 12813 // be a member of another template). 12814 12815 if (Invalid) 12816 return nullptr; 12817 12818 OwnedDecl = false; 12819 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12820 SS, Name, NameLoc, Attr, 12821 TemplateParams, AS, 12822 ModulePrivateLoc, 12823 /*FriendLoc*/SourceLocation(), 12824 TemplateParameterLists.size()-1, 12825 TemplateParameterLists.data(), 12826 SkipBody); 12827 return Result.get(); 12828 } else { 12829 // The "template<>" header is extraneous. 12830 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12831 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12832 isExplicitSpecialization = true; 12833 } 12834 } 12835 } 12836 12837 // Figure out the underlying type if this a enum declaration. We need to do 12838 // this early, because it's needed to detect if this is an incompatible 12839 // redeclaration. 12840 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12841 bool EnumUnderlyingIsImplicit = false; 12842 12843 if (Kind == TTK_Enum) { 12844 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12845 // No underlying type explicitly specified, or we failed to parse the 12846 // type, default to int. 12847 EnumUnderlying = Context.IntTy.getTypePtr(); 12848 else if (UnderlyingType.get()) { 12849 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12850 // integral type; any cv-qualification is ignored. 12851 TypeSourceInfo *TI = nullptr; 12852 GetTypeFromParser(UnderlyingType.get(), &TI); 12853 EnumUnderlying = TI; 12854 12855 if (CheckEnumUnderlyingType(TI)) 12856 // Recover by falling back to int. 12857 EnumUnderlying = Context.IntTy.getTypePtr(); 12858 12859 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12860 UPPC_FixedUnderlyingType)) 12861 EnumUnderlying = Context.IntTy.getTypePtr(); 12862 12863 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12864 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12865 // Microsoft enums are always of int type. 12866 EnumUnderlying = Context.IntTy.getTypePtr(); 12867 EnumUnderlyingIsImplicit = true; 12868 } 12869 } 12870 } 12871 12872 DeclContext *SearchDC = CurContext; 12873 DeclContext *DC = CurContext; 12874 bool isStdBadAlloc = false; 12875 bool isStdAlignValT = false; 12876 12877 RedeclarationKind Redecl = ForRedeclaration; 12878 if (TUK == TUK_Friend || TUK == TUK_Reference) 12879 Redecl = NotForRedeclaration; 12880 12881 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12882 if (Name && SS.isNotEmpty()) { 12883 // We have a nested-name tag ('struct foo::bar'). 12884 12885 // Check for invalid 'foo::'. 12886 if (SS.isInvalid()) { 12887 Name = nullptr; 12888 goto CreateNewDecl; 12889 } 12890 12891 // If this is a friend or a reference to a class in a dependent 12892 // context, don't try to make a decl for it. 12893 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12894 DC = computeDeclContext(SS, false); 12895 if (!DC) { 12896 IsDependent = true; 12897 return nullptr; 12898 } 12899 } else { 12900 DC = computeDeclContext(SS, true); 12901 if (!DC) { 12902 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12903 << SS.getRange(); 12904 return nullptr; 12905 } 12906 } 12907 12908 if (RequireCompleteDeclContext(SS, DC)) 12909 return nullptr; 12910 12911 SearchDC = DC; 12912 // Look-up name inside 'foo::'. 12913 LookupQualifiedName(Previous, DC); 12914 12915 if (Previous.isAmbiguous()) 12916 return nullptr; 12917 12918 if (Previous.empty()) { 12919 // Name lookup did not find anything. However, if the 12920 // nested-name-specifier refers to the current instantiation, 12921 // and that current instantiation has any dependent base 12922 // classes, we might find something at instantiation time: treat 12923 // this as a dependent elaborated-type-specifier. 12924 // But this only makes any sense for reference-like lookups. 12925 if (Previous.wasNotFoundInCurrentInstantiation() && 12926 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12927 IsDependent = true; 12928 return nullptr; 12929 } 12930 12931 // A tag 'foo::bar' must already exist. 12932 Diag(NameLoc, diag::err_not_tag_in_scope) 12933 << Kind << Name << DC << SS.getRange(); 12934 Name = nullptr; 12935 Invalid = true; 12936 goto CreateNewDecl; 12937 } 12938 } else if (Name) { 12939 // C++14 [class.mem]p14: 12940 // If T is the name of a class, then each of the following shall have a 12941 // name different from T: 12942 // -- every member of class T that is itself a type 12943 if (TUK != TUK_Reference && TUK != TUK_Friend && 12944 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12945 return nullptr; 12946 12947 // If this is a named struct, check to see if there was a previous forward 12948 // declaration or definition. 12949 // FIXME: We're looking into outer scopes here, even when we 12950 // shouldn't be. Doing so can result in ambiguities that we 12951 // shouldn't be diagnosing. 12952 LookupName(Previous, S); 12953 12954 // When declaring or defining a tag, ignore ambiguities introduced 12955 // by types using'ed into this scope. 12956 if (Previous.isAmbiguous() && 12957 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12958 LookupResult::Filter F = Previous.makeFilter(); 12959 while (F.hasNext()) { 12960 NamedDecl *ND = F.next(); 12961 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12962 SearchDC->getRedeclContext())) 12963 F.erase(); 12964 } 12965 F.done(); 12966 } 12967 12968 // C++11 [namespace.memdef]p3: 12969 // If the name in a friend declaration is neither qualified nor 12970 // a template-id and the declaration is a function or an 12971 // elaborated-type-specifier, the lookup to determine whether 12972 // the entity has been previously declared shall not consider 12973 // any scopes outside the innermost enclosing namespace. 12974 // 12975 // MSVC doesn't implement the above rule for types, so a friend tag 12976 // declaration may be a redeclaration of a type declared in an enclosing 12977 // scope. They do implement this rule for friend functions. 12978 // 12979 // Does it matter that this should be by scope instead of by 12980 // semantic context? 12981 if (!Previous.empty() && TUK == TUK_Friend) { 12982 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12983 LookupResult::Filter F = Previous.makeFilter(); 12984 bool FriendSawTagOutsideEnclosingNamespace = false; 12985 while (F.hasNext()) { 12986 NamedDecl *ND = F.next(); 12987 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12988 if (DC->isFileContext() && 12989 !EnclosingNS->Encloses(ND->getDeclContext())) { 12990 if (getLangOpts().MSVCCompat) 12991 FriendSawTagOutsideEnclosingNamespace = true; 12992 else 12993 F.erase(); 12994 } 12995 } 12996 F.done(); 12997 12998 // Diagnose this MSVC extension in the easy case where lookup would have 12999 // unambiguously found something outside the enclosing namespace. 13000 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13001 NamedDecl *ND = Previous.getFoundDecl(); 13002 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13003 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13004 } 13005 } 13006 13007 // Note: there used to be some attempt at recovery here. 13008 if (Previous.isAmbiguous()) 13009 return nullptr; 13010 13011 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13012 // FIXME: This makes sure that we ignore the contexts associated 13013 // with C structs, unions, and enums when looking for a matching 13014 // tag declaration or definition. See the similar lookup tweak 13015 // in Sema::LookupName; is there a better way to deal with this? 13016 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13017 SearchDC = SearchDC->getParent(); 13018 } 13019 } 13020 13021 if (Previous.isSingleResult() && 13022 Previous.getFoundDecl()->isTemplateParameter()) { 13023 // Maybe we will complain about the shadowed template parameter. 13024 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13025 // Just pretend that we didn't see the previous declaration. 13026 Previous.clear(); 13027 } 13028 13029 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13030 DC->Equals(getStdNamespace())) { 13031 if (Name->isStr("bad_alloc")) { 13032 // This is a declaration of or a reference to "std::bad_alloc". 13033 isStdBadAlloc = true; 13034 13035 // If std::bad_alloc has been implicitly declared (but made invisible to 13036 // name lookup), fill in this implicit declaration as the previous 13037 // declaration, so that the declarations get chained appropriately. 13038 if (Previous.empty() && StdBadAlloc) 13039 Previous.addDecl(getStdBadAlloc()); 13040 } else if (Name->isStr("align_val_t")) { 13041 isStdAlignValT = true; 13042 if (Previous.empty() && StdAlignValT) 13043 Previous.addDecl(getStdAlignValT()); 13044 } 13045 } 13046 13047 // If we didn't find a previous declaration, and this is a reference 13048 // (or friend reference), move to the correct scope. In C++, we 13049 // also need to do a redeclaration lookup there, just in case 13050 // there's a shadow friend decl. 13051 if (Name && Previous.empty() && 13052 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13053 if (Invalid) goto CreateNewDecl; 13054 assert(SS.isEmpty()); 13055 13056 if (TUK == TUK_Reference) { 13057 // C++ [basic.scope.pdecl]p5: 13058 // -- for an elaborated-type-specifier of the form 13059 // 13060 // class-key identifier 13061 // 13062 // if the elaborated-type-specifier is used in the 13063 // decl-specifier-seq or parameter-declaration-clause of a 13064 // function defined in namespace scope, the identifier is 13065 // declared as a class-name in the namespace that contains 13066 // the declaration; otherwise, except as a friend 13067 // declaration, the identifier is declared in the smallest 13068 // non-class, non-function-prototype scope that contains the 13069 // declaration. 13070 // 13071 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13072 // C structs and unions. 13073 // 13074 // It is an error in C++ to declare (rather than define) an enum 13075 // type, including via an elaborated type specifier. We'll 13076 // diagnose that later; for now, declare the enum in the same 13077 // scope as we would have picked for any other tag type. 13078 // 13079 // GNU C also supports this behavior as part of its incomplete 13080 // enum types extension, while GNU C++ does not. 13081 // 13082 // Find the context where we'll be declaring the tag. 13083 // FIXME: We would like to maintain the current DeclContext as the 13084 // lexical context, 13085 SearchDC = getTagInjectionContext(SearchDC); 13086 13087 // Find the scope where we'll be declaring the tag. 13088 S = getTagInjectionScope(S, getLangOpts()); 13089 } else { 13090 assert(TUK == TUK_Friend); 13091 // C++ [namespace.memdef]p3: 13092 // If a friend declaration in a non-local class first declares a 13093 // class or function, the friend class or function is a member of 13094 // the innermost enclosing namespace. 13095 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13096 } 13097 13098 // In C++, we need to do a redeclaration lookup to properly 13099 // diagnose some problems. 13100 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13101 // hidden declaration so that we don't get ambiguity errors when using a 13102 // type declared by an elaborated-type-specifier. In C that is not correct 13103 // and we should instead merge compatible types found by lookup. 13104 if (getLangOpts().CPlusPlus) { 13105 Previous.setRedeclarationKind(ForRedeclaration); 13106 LookupQualifiedName(Previous, SearchDC); 13107 } else { 13108 Previous.setRedeclarationKind(ForRedeclaration); 13109 LookupName(Previous, S); 13110 } 13111 } 13112 13113 // If we have a known previous declaration to use, then use it. 13114 if (Previous.empty() && SkipBody && SkipBody->Previous) 13115 Previous.addDecl(SkipBody->Previous); 13116 13117 if (!Previous.empty()) { 13118 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13119 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13120 13121 // It's okay to have a tag decl in the same scope as a typedef 13122 // which hides a tag decl in the same scope. Finding this 13123 // insanity with a redeclaration lookup can only actually happen 13124 // in C++. 13125 // 13126 // This is also okay for elaborated-type-specifiers, which is 13127 // technically forbidden by the current standard but which is 13128 // okay according to the likely resolution of an open issue; 13129 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13130 if (getLangOpts().CPlusPlus) { 13131 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13132 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13133 TagDecl *Tag = TT->getDecl(); 13134 if (Tag->getDeclName() == Name && 13135 Tag->getDeclContext()->getRedeclContext() 13136 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13137 PrevDecl = Tag; 13138 Previous.clear(); 13139 Previous.addDecl(Tag); 13140 Previous.resolveKind(); 13141 } 13142 } 13143 } 13144 } 13145 13146 // If this is a redeclaration of a using shadow declaration, it must 13147 // declare a tag in the same context. In MSVC mode, we allow a 13148 // redefinition if either context is within the other. 13149 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13150 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13151 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13152 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 13153 !(OldTag && isAcceptableTagRedeclContext( 13154 *this, OldTag->getDeclContext(), SearchDC))) { 13155 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13156 Diag(Shadow->getTargetDecl()->getLocation(), 13157 diag::note_using_decl_target); 13158 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13159 << 0; 13160 // Recover by ignoring the old declaration. 13161 Previous.clear(); 13162 goto CreateNewDecl; 13163 } 13164 } 13165 13166 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13167 // If this is a use of a previous tag, or if the tag is already declared 13168 // in the same scope (so that the definition/declaration completes or 13169 // rementions the tag), reuse the decl. 13170 if (TUK == TUK_Reference || TUK == TUK_Friend || 13171 isDeclInScope(DirectPrevDecl, SearchDC, S, 13172 SS.isNotEmpty() || isExplicitSpecialization)) { 13173 // Make sure that this wasn't declared as an enum and now used as a 13174 // struct or something similar. 13175 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13176 TUK == TUK_Definition, KWLoc, 13177 Name)) { 13178 bool SafeToContinue 13179 = (PrevTagDecl->getTagKind() != TTK_Enum && 13180 Kind != TTK_Enum); 13181 if (SafeToContinue) 13182 Diag(KWLoc, diag::err_use_with_wrong_tag) 13183 << Name 13184 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13185 PrevTagDecl->getKindName()); 13186 else 13187 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13188 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13189 13190 if (SafeToContinue) 13191 Kind = PrevTagDecl->getTagKind(); 13192 else { 13193 // Recover by making this an anonymous redefinition. 13194 Name = nullptr; 13195 Previous.clear(); 13196 Invalid = true; 13197 } 13198 } 13199 13200 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13201 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13202 13203 // If this is an elaborated-type-specifier for a scoped enumeration, 13204 // the 'class' keyword is not necessary and not permitted. 13205 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13206 if (ScopedEnum) 13207 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13208 << PrevEnum->isScoped() 13209 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13210 return PrevTagDecl; 13211 } 13212 13213 QualType EnumUnderlyingTy; 13214 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13215 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13216 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13217 EnumUnderlyingTy = QualType(T, 0); 13218 13219 // All conflicts with previous declarations are recovered by 13220 // returning the previous declaration, unless this is a definition, 13221 // in which case we want the caller to bail out. 13222 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13223 ScopedEnum, EnumUnderlyingTy, 13224 EnumUnderlyingIsImplicit, PrevEnum)) 13225 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13226 } 13227 13228 // C++11 [class.mem]p1: 13229 // A member shall not be declared twice in the member-specification, 13230 // except that a nested class or member class template can be declared 13231 // and then later defined. 13232 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13233 S->isDeclScope(PrevDecl)) { 13234 Diag(NameLoc, diag::ext_member_redeclared); 13235 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13236 } 13237 13238 if (!Invalid) { 13239 // If this is a use, just return the declaration we found, unless 13240 // we have attributes. 13241 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13242 if (Attr) { 13243 // FIXME: Diagnose these attributes. For now, we create a new 13244 // declaration to hold them. 13245 } else if (TUK == TUK_Reference && 13246 (PrevTagDecl->getFriendObjectKind() == 13247 Decl::FOK_Undeclared || 13248 PP.getModuleContainingLocation( 13249 PrevDecl->getLocation()) != 13250 PP.getModuleContainingLocation(KWLoc)) && 13251 SS.isEmpty()) { 13252 // This declaration is a reference to an existing entity, but 13253 // has different visibility from that entity: it either makes 13254 // a friend visible or it makes a type visible in a new module. 13255 // In either case, create a new declaration. We only do this if 13256 // the declaration would have meant the same thing if no prior 13257 // declaration were found, that is, if it was found in the same 13258 // scope where we would have injected a declaration. 13259 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13260 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13261 return PrevTagDecl; 13262 // This is in the injected scope, create a new declaration in 13263 // that scope. 13264 S = getTagInjectionScope(S, getLangOpts()); 13265 } else { 13266 return PrevTagDecl; 13267 } 13268 } 13269 13270 // Diagnose attempts to redefine a tag. 13271 if (TUK == TUK_Definition) { 13272 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13273 // If we're defining a specialization and the previous definition 13274 // is from an implicit instantiation, don't emit an error 13275 // here; we'll catch this in the general case below. 13276 bool IsExplicitSpecializationAfterInstantiation = false; 13277 if (isExplicitSpecialization) { 13278 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13279 IsExplicitSpecializationAfterInstantiation = 13280 RD->getTemplateSpecializationKind() != 13281 TSK_ExplicitSpecialization; 13282 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13283 IsExplicitSpecializationAfterInstantiation = 13284 ED->getTemplateSpecializationKind() != 13285 TSK_ExplicitSpecialization; 13286 } 13287 13288 NamedDecl *Hidden = nullptr; 13289 if (SkipBody && getLangOpts().CPlusPlus && 13290 !hasVisibleDefinition(Def, &Hidden)) { 13291 // There is a definition of this tag, but it is not visible. We 13292 // explicitly make use of C++'s one definition rule here, and 13293 // assume that this definition is identical to the hidden one 13294 // we already have. Make the existing definition visible and 13295 // use it in place of this one. 13296 SkipBody->ShouldSkip = true; 13297 makeMergedDefinitionVisible(Hidden, KWLoc); 13298 return Def; 13299 } else if (!IsExplicitSpecializationAfterInstantiation) { 13300 // A redeclaration in function prototype scope in C isn't 13301 // visible elsewhere, so merely issue a warning. 13302 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13303 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13304 else 13305 Diag(NameLoc, diag::err_redefinition) << Name; 13306 Diag(Def->getLocation(), diag::note_previous_definition); 13307 // If this is a redefinition, recover by making this 13308 // struct be anonymous, which will make any later 13309 // references get the previous definition. 13310 Name = nullptr; 13311 Previous.clear(); 13312 Invalid = true; 13313 } 13314 } else { 13315 // If the type is currently being defined, complain 13316 // about a nested redefinition. 13317 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13318 if (TD->isBeingDefined()) { 13319 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13320 Diag(PrevTagDecl->getLocation(), 13321 diag::note_previous_definition); 13322 Name = nullptr; 13323 Previous.clear(); 13324 Invalid = true; 13325 } 13326 } 13327 13328 // Okay, this is definition of a previously declared or referenced 13329 // tag. We're going to create a new Decl for it. 13330 } 13331 13332 // Okay, we're going to make a redeclaration. If this is some kind 13333 // of reference, make sure we build the redeclaration in the same DC 13334 // as the original, and ignore the current access specifier. 13335 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13336 SearchDC = PrevTagDecl->getDeclContext(); 13337 AS = AS_none; 13338 } 13339 } 13340 // If we get here we have (another) forward declaration or we 13341 // have a definition. Just create a new decl. 13342 13343 } else { 13344 // If we get here, this is a definition of a new tag type in a nested 13345 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13346 // new decl/type. We set PrevDecl to NULL so that the entities 13347 // have distinct types. 13348 Previous.clear(); 13349 } 13350 // If we get here, we're going to create a new Decl. If PrevDecl 13351 // is non-NULL, it's a definition of the tag declared by 13352 // PrevDecl. If it's NULL, we have a new definition. 13353 13354 // Otherwise, PrevDecl is not a tag, but was found with tag 13355 // lookup. This is only actually possible in C++, where a few 13356 // things like templates still live in the tag namespace. 13357 } else { 13358 // Use a better diagnostic if an elaborated-type-specifier 13359 // found the wrong kind of type on the first 13360 // (non-redeclaration) lookup. 13361 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13362 !Previous.isForRedeclaration()) { 13363 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13364 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13365 << Kind; 13366 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13367 Invalid = true; 13368 13369 // Otherwise, only diagnose if the declaration is in scope. 13370 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13371 SS.isNotEmpty() || isExplicitSpecialization)) { 13372 // do nothing 13373 13374 // Diagnose implicit declarations introduced by elaborated types. 13375 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13376 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13377 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13378 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13379 Invalid = true; 13380 13381 // Otherwise it's a declaration. Call out a particularly common 13382 // case here. 13383 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13384 unsigned Kind = 0; 13385 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13386 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13387 << Name << Kind << TND->getUnderlyingType(); 13388 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13389 Invalid = true; 13390 13391 // Otherwise, diagnose. 13392 } else { 13393 // The tag name clashes with something else in the target scope, 13394 // issue an error and recover by making this tag be anonymous. 13395 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13396 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13397 Name = nullptr; 13398 Invalid = true; 13399 } 13400 13401 // The existing declaration isn't relevant to us; we're in a 13402 // new scope, so clear out the previous declaration. 13403 Previous.clear(); 13404 } 13405 } 13406 13407 CreateNewDecl: 13408 13409 TagDecl *PrevDecl = nullptr; 13410 if (Previous.isSingleResult()) 13411 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13412 13413 // If there is an identifier, use the location of the identifier as the 13414 // location of the decl, otherwise use the location of the struct/union 13415 // keyword. 13416 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13417 13418 // Otherwise, create a new declaration. If there is a previous 13419 // declaration of the same entity, the two will be linked via 13420 // PrevDecl. 13421 TagDecl *New; 13422 13423 bool IsForwardReference = false; 13424 if (Kind == TTK_Enum) { 13425 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13426 // enum X { A, B, C } D; D should chain to X. 13427 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13428 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13429 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13430 13431 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13432 StdAlignValT = cast<EnumDecl>(New); 13433 13434 // If this is an undefined enum, warn. 13435 if (TUK != TUK_Definition && !Invalid) { 13436 TagDecl *Def; 13437 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13438 cast<EnumDecl>(New)->isFixed()) { 13439 // C++0x: 7.2p2: opaque-enum-declaration. 13440 // Conflicts are diagnosed above. Do nothing. 13441 } 13442 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13443 Diag(Loc, diag::ext_forward_ref_enum_def) 13444 << New; 13445 Diag(Def->getLocation(), diag::note_previous_definition); 13446 } else { 13447 unsigned DiagID = diag::ext_forward_ref_enum; 13448 if (getLangOpts().MSVCCompat) 13449 DiagID = diag::ext_ms_forward_ref_enum; 13450 else if (getLangOpts().CPlusPlus) 13451 DiagID = diag::err_forward_ref_enum; 13452 Diag(Loc, DiagID); 13453 13454 // If this is a forward-declared reference to an enumeration, make a 13455 // note of it; we won't actually be introducing the declaration into 13456 // the declaration context. 13457 if (TUK == TUK_Reference) 13458 IsForwardReference = true; 13459 } 13460 } 13461 13462 if (EnumUnderlying) { 13463 EnumDecl *ED = cast<EnumDecl>(New); 13464 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13465 ED->setIntegerTypeSourceInfo(TI); 13466 else 13467 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13468 ED->setPromotionType(ED->getIntegerType()); 13469 } 13470 } else { 13471 // struct/union/class 13472 13473 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13474 // struct X { int A; } D; D should chain to X. 13475 if (getLangOpts().CPlusPlus) { 13476 // FIXME: Look for a way to use RecordDecl for simple structs. 13477 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13478 cast_or_null<CXXRecordDecl>(PrevDecl)); 13479 13480 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13481 StdBadAlloc = cast<CXXRecordDecl>(New); 13482 } else 13483 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13484 cast_or_null<RecordDecl>(PrevDecl)); 13485 } 13486 13487 // C++11 [dcl.type]p3: 13488 // A type-specifier-seq shall not define a class or enumeration [...]. 13489 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13490 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13491 << Context.getTagDeclType(New); 13492 Invalid = true; 13493 } 13494 13495 // Maybe add qualifier info. 13496 if (SS.isNotEmpty()) { 13497 if (SS.isSet()) { 13498 // If this is either a declaration or a definition, check the 13499 // nested-name-specifier against the current context. We don't do this 13500 // for explicit specializations, because they have similar checking 13501 // (with more specific diagnostics) in the call to 13502 // CheckMemberSpecialization, below. 13503 if (!isExplicitSpecialization && 13504 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13505 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13506 Invalid = true; 13507 13508 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13509 if (TemplateParameterLists.size() > 0) { 13510 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13511 } 13512 } 13513 else 13514 Invalid = true; 13515 } 13516 13517 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13518 // Add alignment attributes if necessary; these attributes are checked when 13519 // the ASTContext lays out the structure. 13520 // 13521 // It is important for implementing the correct semantics that this 13522 // happen here (in act on tag decl). The #pragma pack stack is 13523 // maintained as a result of parser callbacks which can occur at 13524 // many points during the parsing of a struct declaration (because 13525 // the #pragma tokens are effectively skipped over during the 13526 // parsing of the struct). 13527 if (TUK == TUK_Definition) { 13528 AddAlignmentAttributesForRecord(RD); 13529 AddMsStructLayoutForRecord(RD); 13530 } 13531 } 13532 13533 if (ModulePrivateLoc.isValid()) { 13534 if (isExplicitSpecialization) 13535 Diag(New->getLocation(), diag::err_module_private_specialization) 13536 << 2 13537 << FixItHint::CreateRemoval(ModulePrivateLoc); 13538 // __module_private__ does not apply to local classes. However, we only 13539 // diagnose this as an error when the declaration specifiers are 13540 // freestanding. Here, we just ignore the __module_private__. 13541 else if (!SearchDC->isFunctionOrMethod()) 13542 New->setModulePrivate(); 13543 } 13544 13545 // If this is a specialization of a member class (of a class template), 13546 // check the specialization. 13547 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13548 Invalid = true; 13549 13550 // If we're declaring or defining a tag in function prototype scope in C, 13551 // note that this type can only be used within the function and add it to 13552 // the list of decls to inject into the function definition scope. 13553 if ((Name || Kind == TTK_Enum) && 13554 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13555 if (getLangOpts().CPlusPlus) { 13556 // C++ [dcl.fct]p6: 13557 // Types shall not be defined in return or parameter types. 13558 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13559 Diag(Loc, diag::err_type_defined_in_param_type) 13560 << Name; 13561 Invalid = true; 13562 } 13563 } else if (!PrevDecl) { 13564 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13565 } 13566 } 13567 13568 if (Invalid) 13569 New->setInvalidDecl(); 13570 13571 if (Attr) 13572 ProcessDeclAttributeList(S, New, Attr); 13573 13574 // Set the lexical context. If the tag has a C++ scope specifier, the 13575 // lexical context will be different from the semantic context. 13576 New->setLexicalDeclContext(CurContext); 13577 13578 // Mark this as a friend decl if applicable. 13579 // In Microsoft mode, a friend declaration also acts as a forward 13580 // declaration so we always pass true to setObjectOfFriendDecl to make 13581 // the tag name visible. 13582 if (TUK == TUK_Friend) 13583 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13584 13585 // Set the access specifier. 13586 if (!Invalid && SearchDC->isRecord()) 13587 SetMemberAccessSpecifier(New, PrevDecl, AS); 13588 13589 if (TUK == TUK_Definition) 13590 New->startDefinition(); 13591 13592 // If this has an identifier, add it to the scope stack. 13593 if (TUK == TUK_Friend) { 13594 // We might be replacing an existing declaration in the lookup tables; 13595 // if so, borrow its access specifier. 13596 if (PrevDecl) 13597 New->setAccess(PrevDecl->getAccess()); 13598 13599 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13600 DC->makeDeclVisibleInContext(New); 13601 if (Name) // can be null along some error paths 13602 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13603 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13604 } else if (Name) { 13605 S = getNonFieldDeclScope(S); 13606 PushOnScopeChains(New, S, !IsForwardReference); 13607 if (IsForwardReference) 13608 SearchDC->makeDeclVisibleInContext(New); 13609 } else { 13610 CurContext->addDecl(New); 13611 } 13612 13613 // If this is the C FILE type, notify the AST context. 13614 if (IdentifierInfo *II = New->getIdentifier()) 13615 if (!New->isInvalidDecl() && 13616 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13617 II->isStr("FILE")) 13618 Context.setFILEDecl(New); 13619 13620 if (PrevDecl) 13621 mergeDeclAttributes(New, PrevDecl); 13622 13623 // If there's a #pragma GCC visibility in scope, set the visibility of this 13624 // record. 13625 AddPushedVisibilityAttribute(New); 13626 13627 OwnedDecl = true; 13628 // In C++, don't return an invalid declaration. We can't recover well from 13629 // the cases where we make the type anonymous. 13630 if (Invalid && getLangOpts().CPlusPlus) { 13631 if (New->isBeingDefined()) 13632 if (auto RD = dyn_cast<RecordDecl>(New)) 13633 RD->completeDefinition(); 13634 return nullptr; 13635 } else { 13636 return New; 13637 } 13638 } 13639 13640 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13641 AdjustDeclIfTemplate(TagD); 13642 TagDecl *Tag = cast<TagDecl>(TagD); 13643 13644 // Enter the tag context. 13645 PushDeclContext(S, Tag); 13646 13647 ActOnDocumentableDecl(TagD); 13648 13649 // If there's a #pragma GCC visibility in scope, set the visibility of this 13650 // record. 13651 AddPushedVisibilityAttribute(Tag); 13652 } 13653 13654 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13655 assert(isa<ObjCContainerDecl>(IDecl) && 13656 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13657 DeclContext *OCD = cast<DeclContext>(IDecl); 13658 assert(getContainingDC(OCD) == CurContext && 13659 "The next DeclContext should be lexically contained in the current one."); 13660 CurContext = OCD; 13661 return IDecl; 13662 } 13663 13664 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13665 SourceLocation FinalLoc, 13666 bool IsFinalSpelledSealed, 13667 SourceLocation LBraceLoc) { 13668 AdjustDeclIfTemplate(TagD); 13669 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13670 13671 FieldCollector->StartClass(); 13672 13673 if (!Record->getIdentifier()) 13674 return; 13675 13676 if (FinalLoc.isValid()) 13677 Record->addAttr(new (Context) 13678 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13679 13680 // C++ [class]p2: 13681 // [...] The class-name is also inserted into the scope of the 13682 // class itself; this is known as the injected-class-name. For 13683 // purposes of access checking, the injected-class-name is treated 13684 // as if it were a public member name. 13685 CXXRecordDecl *InjectedClassName 13686 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13687 Record->getLocStart(), Record->getLocation(), 13688 Record->getIdentifier(), 13689 /*PrevDecl=*/nullptr, 13690 /*DelayTypeCreation=*/true); 13691 Context.getTypeDeclType(InjectedClassName, Record); 13692 InjectedClassName->setImplicit(); 13693 InjectedClassName->setAccess(AS_public); 13694 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13695 InjectedClassName->setDescribedClassTemplate(Template); 13696 PushOnScopeChains(InjectedClassName, S); 13697 assert(InjectedClassName->isInjectedClassName() && 13698 "Broken injected-class-name"); 13699 } 13700 13701 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13702 SourceRange BraceRange) { 13703 AdjustDeclIfTemplate(TagD); 13704 TagDecl *Tag = cast<TagDecl>(TagD); 13705 Tag->setBraceRange(BraceRange); 13706 13707 // Make sure we "complete" the definition even it is invalid. 13708 if (Tag->isBeingDefined()) { 13709 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13710 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13711 RD->completeDefinition(); 13712 } 13713 13714 if (isa<CXXRecordDecl>(Tag)) 13715 FieldCollector->FinishClass(); 13716 13717 // Exit this scope of this tag's definition. 13718 PopDeclContext(); 13719 13720 if (getCurLexicalContext()->isObjCContainer() && 13721 Tag->getDeclContext()->isFileContext()) 13722 Tag->setTopLevelDeclInObjCContainer(); 13723 13724 // Notify the consumer that we've defined a tag. 13725 if (!Tag->isInvalidDecl()) 13726 Consumer.HandleTagDeclDefinition(Tag); 13727 } 13728 13729 void Sema::ActOnObjCContainerFinishDefinition() { 13730 // Exit this scope of this interface definition. 13731 PopDeclContext(); 13732 } 13733 13734 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13735 assert(DC == CurContext && "Mismatch of container contexts"); 13736 OriginalLexicalContext = DC; 13737 ActOnObjCContainerFinishDefinition(); 13738 } 13739 13740 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13741 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13742 OriginalLexicalContext = nullptr; 13743 } 13744 13745 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13746 AdjustDeclIfTemplate(TagD); 13747 TagDecl *Tag = cast<TagDecl>(TagD); 13748 Tag->setInvalidDecl(); 13749 13750 // Make sure we "complete" the definition even it is invalid. 13751 if (Tag->isBeingDefined()) { 13752 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13753 RD->completeDefinition(); 13754 } 13755 13756 // We're undoing ActOnTagStartDefinition here, not 13757 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13758 // the FieldCollector. 13759 13760 PopDeclContext(); 13761 } 13762 13763 // Note that FieldName may be null for anonymous bitfields. 13764 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13765 IdentifierInfo *FieldName, 13766 QualType FieldTy, bool IsMsStruct, 13767 Expr *BitWidth, bool *ZeroWidth) { 13768 // Default to true; that shouldn't confuse checks for emptiness 13769 if (ZeroWidth) 13770 *ZeroWidth = true; 13771 13772 // C99 6.7.2.1p4 - verify the field type. 13773 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13774 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13775 // Handle incomplete types with specific error. 13776 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13777 return ExprError(); 13778 if (FieldName) 13779 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13780 << FieldName << FieldTy << BitWidth->getSourceRange(); 13781 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13782 << FieldTy << BitWidth->getSourceRange(); 13783 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13784 UPPC_BitFieldWidth)) 13785 return ExprError(); 13786 13787 // If the bit-width is type- or value-dependent, don't try to check 13788 // it now. 13789 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13790 return BitWidth; 13791 13792 llvm::APSInt Value; 13793 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13794 if (ICE.isInvalid()) 13795 return ICE; 13796 BitWidth = ICE.get(); 13797 13798 if (Value != 0 && ZeroWidth) 13799 *ZeroWidth = false; 13800 13801 // Zero-width bitfield is ok for anonymous field. 13802 if (Value == 0 && FieldName) 13803 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13804 13805 if (Value.isSigned() && Value.isNegative()) { 13806 if (FieldName) 13807 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13808 << FieldName << Value.toString(10); 13809 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13810 << Value.toString(10); 13811 } 13812 13813 if (!FieldTy->isDependentType()) { 13814 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13815 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13816 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13817 13818 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13819 // ABI. 13820 bool CStdConstraintViolation = 13821 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13822 bool MSBitfieldViolation = 13823 Value.ugt(TypeStorageSize) && 13824 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13825 if (CStdConstraintViolation || MSBitfieldViolation) { 13826 unsigned DiagWidth = 13827 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13828 if (FieldName) 13829 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13830 << FieldName << (unsigned)Value.getZExtValue() 13831 << !CStdConstraintViolation << DiagWidth; 13832 13833 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13834 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13835 << DiagWidth; 13836 } 13837 13838 // Warn on types where the user might conceivably expect to get all 13839 // specified bits as value bits: that's all integral types other than 13840 // 'bool'. 13841 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13842 if (FieldName) 13843 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13844 << FieldName << (unsigned)Value.getZExtValue() 13845 << (unsigned)TypeWidth; 13846 else 13847 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13848 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13849 } 13850 } 13851 13852 return BitWidth; 13853 } 13854 13855 /// ActOnField - Each field of a C struct/union is passed into this in order 13856 /// to create a FieldDecl object for it. 13857 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13858 Declarator &D, Expr *BitfieldWidth) { 13859 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13860 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13861 /*InitStyle=*/ICIS_NoInit, AS_public); 13862 return Res; 13863 } 13864 13865 /// HandleField - Analyze a field of a C struct or a C++ data member. 13866 /// 13867 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13868 SourceLocation DeclStart, 13869 Declarator &D, Expr *BitWidth, 13870 InClassInitStyle InitStyle, 13871 AccessSpecifier AS) { 13872 if (D.isDecompositionDeclarator()) { 13873 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13874 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13875 << Decomp.getSourceRange(); 13876 return nullptr; 13877 } 13878 13879 IdentifierInfo *II = D.getIdentifier(); 13880 SourceLocation Loc = DeclStart; 13881 if (II) Loc = D.getIdentifierLoc(); 13882 13883 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13884 QualType T = TInfo->getType(); 13885 if (getLangOpts().CPlusPlus) { 13886 CheckExtraCXXDefaultArguments(D); 13887 13888 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13889 UPPC_DataMemberType)) { 13890 D.setInvalidType(); 13891 T = Context.IntTy; 13892 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13893 } 13894 } 13895 13896 // TR 18037 does not allow fields to be declared with address spaces. 13897 if (T.getQualifiers().hasAddressSpace()) { 13898 Diag(Loc, diag::err_field_with_address_space); 13899 D.setInvalidType(); 13900 } 13901 13902 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13903 // used as structure or union field: image, sampler, event or block types. 13904 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13905 T->isSamplerT() || T->isBlockPointerType())) { 13906 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13907 D.setInvalidType(); 13908 } 13909 13910 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13911 13912 if (D.getDeclSpec().isInlineSpecified()) 13913 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13914 << getLangOpts().CPlusPlus1z; 13915 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13916 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13917 diag::err_invalid_thread) 13918 << DeclSpec::getSpecifierName(TSCS); 13919 13920 // Check to see if this name was declared as a member previously 13921 NamedDecl *PrevDecl = nullptr; 13922 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13923 LookupName(Previous, S); 13924 switch (Previous.getResultKind()) { 13925 case LookupResult::Found: 13926 case LookupResult::FoundUnresolvedValue: 13927 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13928 break; 13929 13930 case LookupResult::FoundOverloaded: 13931 PrevDecl = Previous.getRepresentativeDecl(); 13932 break; 13933 13934 case LookupResult::NotFound: 13935 case LookupResult::NotFoundInCurrentInstantiation: 13936 case LookupResult::Ambiguous: 13937 break; 13938 } 13939 Previous.suppressDiagnostics(); 13940 13941 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13942 // Maybe we will complain about the shadowed template parameter. 13943 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13944 // Just pretend that we didn't see the previous declaration. 13945 PrevDecl = nullptr; 13946 } 13947 13948 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13949 PrevDecl = nullptr; 13950 13951 bool Mutable 13952 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13953 SourceLocation TSSL = D.getLocStart(); 13954 FieldDecl *NewFD 13955 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13956 TSSL, AS, PrevDecl, &D); 13957 13958 if (NewFD->isInvalidDecl()) 13959 Record->setInvalidDecl(); 13960 13961 if (D.getDeclSpec().isModulePrivateSpecified()) 13962 NewFD->setModulePrivate(); 13963 13964 if (NewFD->isInvalidDecl() && PrevDecl) { 13965 // Don't introduce NewFD into scope; there's already something 13966 // with the same name in the same scope. 13967 } else if (II) { 13968 PushOnScopeChains(NewFD, S); 13969 } else 13970 Record->addDecl(NewFD); 13971 13972 return NewFD; 13973 } 13974 13975 /// \brief Build a new FieldDecl and check its well-formedness. 13976 /// 13977 /// This routine builds a new FieldDecl given the fields name, type, 13978 /// record, etc. \p PrevDecl should refer to any previous declaration 13979 /// with the same name and in the same scope as the field to be 13980 /// created. 13981 /// 13982 /// \returns a new FieldDecl. 13983 /// 13984 /// \todo The Declarator argument is a hack. It will be removed once 13985 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13986 TypeSourceInfo *TInfo, 13987 RecordDecl *Record, SourceLocation Loc, 13988 bool Mutable, Expr *BitWidth, 13989 InClassInitStyle InitStyle, 13990 SourceLocation TSSL, 13991 AccessSpecifier AS, NamedDecl *PrevDecl, 13992 Declarator *D) { 13993 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13994 bool InvalidDecl = false; 13995 if (D) InvalidDecl = D->isInvalidType(); 13996 13997 // If we receive a broken type, recover by assuming 'int' and 13998 // marking this declaration as invalid. 13999 if (T.isNull()) { 14000 InvalidDecl = true; 14001 T = Context.IntTy; 14002 } 14003 14004 QualType EltTy = Context.getBaseElementType(T); 14005 if (!EltTy->isDependentType()) { 14006 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14007 // Fields of incomplete type force their record to be invalid. 14008 Record->setInvalidDecl(); 14009 InvalidDecl = true; 14010 } else { 14011 NamedDecl *Def; 14012 EltTy->isIncompleteType(&Def); 14013 if (Def && Def->isInvalidDecl()) { 14014 Record->setInvalidDecl(); 14015 InvalidDecl = true; 14016 } 14017 } 14018 } 14019 14020 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14021 if (BitWidth && getLangOpts().OpenCL) { 14022 Diag(Loc, diag::err_opencl_bitfields); 14023 InvalidDecl = true; 14024 } 14025 14026 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14027 // than a variably modified type. 14028 if (!InvalidDecl && T->isVariablyModifiedType()) { 14029 bool SizeIsNegative; 14030 llvm::APSInt Oversized; 14031 14032 TypeSourceInfo *FixedTInfo = 14033 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14034 SizeIsNegative, 14035 Oversized); 14036 if (FixedTInfo) { 14037 Diag(Loc, diag::warn_illegal_constant_array_size); 14038 TInfo = FixedTInfo; 14039 T = FixedTInfo->getType(); 14040 } else { 14041 if (SizeIsNegative) 14042 Diag(Loc, diag::err_typecheck_negative_array_size); 14043 else if (Oversized.getBoolValue()) 14044 Diag(Loc, diag::err_array_too_large) 14045 << Oversized.toString(10); 14046 else 14047 Diag(Loc, diag::err_typecheck_field_variable_size); 14048 InvalidDecl = true; 14049 } 14050 } 14051 14052 // Fields can not have abstract class types 14053 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14054 diag::err_abstract_type_in_decl, 14055 AbstractFieldType)) 14056 InvalidDecl = true; 14057 14058 bool ZeroWidth = false; 14059 if (InvalidDecl) 14060 BitWidth = nullptr; 14061 // If this is declared as a bit-field, check the bit-field. 14062 if (BitWidth) { 14063 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14064 &ZeroWidth).get(); 14065 if (!BitWidth) { 14066 InvalidDecl = true; 14067 BitWidth = nullptr; 14068 ZeroWidth = false; 14069 } 14070 } 14071 14072 // Check that 'mutable' is consistent with the type of the declaration. 14073 if (!InvalidDecl && Mutable) { 14074 unsigned DiagID = 0; 14075 if (T->isReferenceType()) 14076 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14077 : diag::err_mutable_reference; 14078 else if (T.isConstQualified()) 14079 DiagID = diag::err_mutable_const; 14080 14081 if (DiagID) { 14082 SourceLocation ErrLoc = Loc; 14083 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14084 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14085 Diag(ErrLoc, DiagID); 14086 if (DiagID != diag::ext_mutable_reference) { 14087 Mutable = false; 14088 InvalidDecl = true; 14089 } 14090 } 14091 } 14092 14093 // C++11 [class.union]p8 (DR1460): 14094 // At most one variant member of a union may have a 14095 // brace-or-equal-initializer. 14096 if (InitStyle != ICIS_NoInit) 14097 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14098 14099 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14100 BitWidth, Mutable, InitStyle); 14101 if (InvalidDecl) 14102 NewFD->setInvalidDecl(); 14103 14104 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14105 Diag(Loc, diag::err_duplicate_member) << II; 14106 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14107 NewFD->setInvalidDecl(); 14108 } 14109 14110 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14111 if (Record->isUnion()) { 14112 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14113 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14114 if (RDecl->getDefinition()) { 14115 // C++ [class.union]p1: An object of a class with a non-trivial 14116 // constructor, a non-trivial copy constructor, a non-trivial 14117 // destructor, or a non-trivial copy assignment operator 14118 // cannot be a member of a union, nor can an array of such 14119 // objects. 14120 if (CheckNontrivialField(NewFD)) 14121 NewFD->setInvalidDecl(); 14122 } 14123 } 14124 14125 // C++ [class.union]p1: If a union contains a member of reference type, 14126 // the program is ill-formed, except when compiling with MSVC extensions 14127 // enabled. 14128 if (EltTy->isReferenceType()) { 14129 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14130 diag::ext_union_member_of_reference_type : 14131 diag::err_union_member_of_reference_type) 14132 << NewFD->getDeclName() << EltTy; 14133 if (!getLangOpts().MicrosoftExt) 14134 NewFD->setInvalidDecl(); 14135 } 14136 } 14137 } 14138 14139 // FIXME: We need to pass in the attributes given an AST 14140 // representation, not a parser representation. 14141 if (D) { 14142 // FIXME: The current scope is almost... but not entirely... correct here. 14143 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14144 14145 if (NewFD->hasAttrs()) 14146 CheckAlignasUnderalignment(NewFD); 14147 } 14148 14149 // In auto-retain/release, infer strong retension for fields of 14150 // retainable type. 14151 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14152 NewFD->setInvalidDecl(); 14153 14154 if (T.isObjCGCWeak()) 14155 Diag(Loc, diag::warn_attribute_weak_on_field); 14156 14157 NewFD->setAccess(AS); 14158 return NewFD; 14159 } 14160 14161 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14162 assert(FD); 14163 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14164 14165 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14166 return false; 14167 14168 QualType EltTy = Context.getBaseElementType(FD->getType()); 14169 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14170 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14171 if (RDecl->getDefinition()) { 14172 // We check for copy constructors before constructors 14173 // because otherwise we'll never get complaints about 14174 // copy constructors. 14175 14176 CXXSpecialMember member = CXXInvalid; 14177 // We're required to check for any non-trivial constructors. Since the 14178 // implicit default constructor is suppressed if there are any 14179 // user-declared constructors, we just need to check that there is a 14180 // trivial default constructor and a trivial copy constructor. (We don't 14181 // worry about move constructors here, since this is a C++98 check.) 14182 if (RDecl->hasNonTrivialCopyConstructor()) 14183 member = CXXCopyConstructor; 14184 else if (!RDecl->hasTrivialDefaultConstructor()) 14185 member = CXXDefaultConstructor; 14186 else if (RDecl->hasNonTrivialCopyAssignment()) 14187 member = CXXCopyAssignment; 14188 else if (RDecl->hasNonTrivialDestructor()) 14189 member = CXXDestructor; 14190 14191 if (member != CXXInvalid) { 14192 if (!getLangOpts().CPlusPlus11 && 14193 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14194 // Objective-C++ ARC: it is an error to have a non-trivial field of 14195 // a union. However, system headers in Objective-C programs 14196 // occasionally have Objective-C lifetime objects within unions, 14197 // and rather than cause the program to fail, we make those 14198 // members unavailable. 14199 SourceLocation Loc = FD->getLocation(); 14200 if (getSourceManager().isInSystemHeader(Loc)) { 14201 if (!FD->hasAttr<UnavailableAttr>()) 14202 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14203 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14204 return false; 14205 } 14206 } 14207 14208 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14209 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14210 diag::err_illegal_union_or_anon_struct_member) 14211 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14212 DiagnoseNontrivial(RDecl, member); 14213 return !getLangOpts().CPlusPlus11; 14214 } 14215 } 14216 } 14217 14218 return false; 14219 } 14220 14221 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14222 /// AST enum value. 14223 static ObjCIvarDecl::AccessControl 14224 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14225 switch (ivarVisibility) { 14226 default: llvm_unreachable("Unknown visitibility kind"); 14227 case tok::objc_private: return ObjCIvarDecl::Private; 14228 case tok::objc_public: return ObjCIvarDecl::Public; 14229 case tok::objc_protected: return ObjCIvarDecl::Protected; 14230 case tok::objc_package: return ObjCIvarDecl::Package; 14231 } 14232 } 14233 14234 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14235 /// in order to create an IvarDecl object for it. 14236 Decl *Sema::ActOnIvar(Scope *S, 14237 SourceLocation DeclStart, 14238 Declarator &D, Expr *BitfieldWidth, 14239 tok::ObjCKeywordKind Visibility) { 14240 14241 IdentifierInfo *II = D.getIdentifier(); 14242 Expr *BitWidth = (Expr*)BitfieldWidth; 14243 SourceLocation Loc = DeclStart; 14244 if (II) Loc = D.getIdentifierLoc(); 14245 14246 // FIXME: Unnamed fields can be handled in various different ways, for 14247 // example, unnamed unions inject all members into the struct namespace! 14248 14249 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14250 QualType T = TInfo->getType(); 14251 14252 if (BitWidth) { 14253 // 6.7.2.1p3, 6.7.2.1p4 14254 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14255 if (!BitWidth) 14256 D.setInvalidType(); 14257 } else { 14258 // Not a bitfield. 14259 14260 // validate II. 14261 14262 } 14263 if (T->isReferenceType()) { 14264 Diag(Loc, diag::err_ivar_reference_type); 14265 D.setInvalidType(); 14266 } 14267 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14268 // than a variably modified type. 14269 else if (T->isVariablyModifiedType()) { 14270 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14271 D.setInvalidType(); 14272 } 14273 14274 // Get the visibility (access control) for this ivar. 14275 ObjCIvarDecl::AccessControl ac = 14276 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14277 : ObjCIvarDecl::None; 14278 // Must set ivar's DeclContext to its enclosing interface. 14279 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14280 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14281 return nullptr; 14282 ObjCContainerDecl *EnclosingContext; 14283 if (ObjCImplementationDecl *IMPDecl = 14284 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14285 if (LangOpts.ObjCRuntime.isFragile()) { 14286 // Case of ivar declared in an implementation. Context is that of its class. 14287 EnclosingContext = IMPDecl->getClassInterface(); 14288 assert(EnclosingContext && "Implementation has no class interface!"); 14289 } 14290 else 14291 EnclosingContext = EnclosingDecl; 14292 } else { 14293 if (ObjCCategoryDecl *CDecl = 14294 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14295 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14296 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14297 return nullptr; 14298 } 14299 } 14300 EnclosingContext = EnclosingDecl; 14301 } 14302 14303 // Construct the decl. 14304 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14305 DeclStart, Loc, II, T, 14306 TInfo, ac, (Expr *)BitfieldWidth); 14307 14308 if (II) { 14309 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14310 ForRedeclaration); 14311 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14312 && !isa<TagDecl>(PrevDecl)) { 14313 Diag(Loc, diag::err_duplicate_member) << II; 14314 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14315 NewID->setInvalidDecl(); 14316 } 14317 } 14318 14319 // Process attributes attached to the ivar. 14320 ProcessDeclAttributes(S, NewID, D); 14321 14322 if (D.isInvalidType()) 14323 NewID->setInvalidDecl(); 14324 14325 // In ARC, infer 'retaining' for ivars of retainable type. 14326 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14327 NewID->setInvalidDecl(); 14328 14329 if (D.getDeclSpec().isModulePrivateSpecified()) 14330 NewID->setModulePrivate(); 14331 14332 if (II) { 14333 // FIXME: When interfaces are DeclContexts, we'll need to add 14334 // these to the interface. 14335 S->AddDecl(NewID); 14336 IdResolver.AddDecl(NewID); 14337 } 14338 14339 if (LangOpts.ObjCRuntime.isNonFragile() && 14340 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14341 Diag(Loc, diag::warn_ivars_in_interface); 14342 14343 return NewID; 14344 } 14345 14346 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14347 /// class and class extensions. For every class \@interface and class 14348 /// extension \@interface, if the last ivar is a bitfield of any type, 14349 /// then add an implicit `char :0` ivar to the end of that interface. 14350 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14351 SmallVectorImpl<Decl *> &AllIvarDecls) { 14352 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14353 return; 14354 14355 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14356 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14357 14358 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14359 return; 14360 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14361 if (!ID) { 14362 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14363 if (!CD->IsClassExtension()) 14364 return; 14365 } 14366 // No need to add this to end of @implementation. 14367 else 14368 return; 14369 } 14370 // All conditions are met. Add a new bitfield to the tail end of ivars. 14371 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14372 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14373 14374 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14375 DeclLoc, DeclLoc, nullptr, 14376 Context.CharTy, 14377 Context.getTrivialTypeSourceInfo(Context.CharTy, 14378 DeclLoc), 14379 ObjCIvarDecl::Private, BW, 14380 true); 14381 AllIvarDecls.push_back(Ivar); 14382 } 14383 14384 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14385 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14386 SourceLocation RBrac, AttributeList *Attr) { 14387 assert(EnclosingDecl && "missing record or interface decl"); 14388 14389 // If this is an Objective-C @implementation or category and we have 14390 // new fields here we should reset the layout of the interface since 14391 // it will now change. 14392 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14393 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14394 switch (DC->getKind()) { 14395 default: break; 14396 case Decl::ObjCCategory: 14397 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14398 break; 14399 case Decl::ObjCImplementation: 14400 Context. 14401 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14402 break; 14403 } 14404 } 14405 14406 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14407 14408 // Start counting up the number of named members; make sure to include 14409 // members of anonymous structs and unions in the total. 14410 unsigned NumNamedMembers = 0; 14411 if (Record) { 14412 for (const auto *I : Record->decls()) { 14413 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14414 if (IFD->getDeclName()) 14415 ++NumNamedMembers; 14416 } 14417 } 14418 14419 // Verify that all the fields are okay. 14420 SmallVector<FieldDecl*, 32> RecFields; 14421 14422 bool ARCErrReported = false; 14423 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14424 i != end; ++i) { 14425 FieldDecl *FD = cast<FieldDecl>(*i); 14426 14427 // Get the type for the field. 14428 const Type *FDTy = FD->getType().getTypePtr(); 14429 14430 if (!FD->isAnonymousStructOrUnion()) { 14431 // Remember all fields written by the user. 14432 RecFields.push_back(FD); 14433 } 14434 14435 // If the field is already invalid for some reason, don't emit more 14436 // diagnostics about it. 14437 if (FD->isInvalidDecl()) { 14438 EnclosingDecl->setInvalidDecl(); 14439 continue; 14440 } 14441 14442 // C99 6.7.2.1p2: 14443 // A structure or union shall not contain a member with 14444 // incomplete or function type (hence, a structure shall not 14445 // contain an instance of itself, but may contain a pointer to 14446 // an instance of itself), except that the last member of a 14447 // structure with more than one named member may have incomplete 14448 // array type; such a structure (and any union containing, 14449 // possibly recursively, a member that is such a structure) 14450 // shall not be a member of a structure or an element of an 14451 // array. 14452 if (FDTy->isFunctionType()) { 14453 // Field declared as a function. 14454 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14455 << FD->getDeclName(); 14456 FD->setInvalidDecl(); 14457 EnclosingDecl->setInvalidDecl(); 14458 continue; 14459 } else if (FDTy->isIncompleteArrayType() && Record && 14460 ((i + 1 == Fields.end() && !Record->isUnion()) || 14461 ((getLangOpts().MicrosoftExt || 14462 getLangOpts().CPlusPlus) && 14463 (i + 1 == Fields.end() || Record->isUnion())))) { 14464 // Flexible array member. 14465 // Microsoft and g++ is more permissive regarding flexible array. 14466 // It will accept flexible array in union and also 14467 // as the sole element of a struct/class. 14468 unsigned DiagID = 0; 14469 if (Record->isUnion()) 14470 DiagID = getLangOpts().MicrosoftExt 14471 ? diag::ext_flexible_array_union_ms 14472 : getLangOpts().CPlusPlus 14473 ? diag::ext_flexible_array_union_gnu 14474 : diag::err_flexible_array_union; 14475 else if (NumNamedMembers < 1) 14476 DiagID = getLangOpts().MicrosoftExt 14477 ? diag::ext_flexible_array_empty_aggregate_ms 14478 : getLangOpts().CPlusPlus 14479 ? diag::ext_flexible_array_empty_aggregate_gnu 14480 : diag::err_flexible_array_empty_aggregate; 14481 14482 if (DiagID) 14483 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14484 << Record->getTagKind(); 14485 // While the layout of types that contain virtual bases is not specified 14486 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14487 // virtual bases after the derived members. This would make a flexible 14488 // array member declared at the end of an object not adjacent to the end 14489 // of the type. 14490 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14491 if (RD->getNumVBases() != 0) 14492 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14493 << FD->getDeclName() << Record->getTagKind(); 14494 if (!getLangOpts().C99) 14495 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14496 << FD->getDeclName() << Record->getTagKind(); 14497 14498 // If the element type has a non-trivial destructor, we would not 14499 // implicitly destroy the elements, so disallow it for now. 14500 // 14501 // FIXME: GCC allows this. We should probably either implicitly delete 14502 // the destructor of the containing class, or just allow this. 14503 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14504 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14505 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14506 << FD->getDeclName() << FD->getType(); 14507 FD->setInvalidDecl(); 14508 EnclosingDecl->setInvalidDecl(); 14509 continue; 14510 } 14511 // Okay, we have a legal flexible array member at the end of the struct. 14512 Record->setHasFlexibleArrayMember(true); 14513 } else if (!FDTy->isDependentType() && 14514 RequireCompleteType(FD->getLocation(), FD->getType(), 14515 diag::err_field_incomplete)) { 14516 // Incomplete type 14517 FD->setInvalidDecl(); 14518 EnclosingDecl->setInvalidDecl(); 14519 continue; 14520 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14521 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14522 // A type which contains a flexible array member is considered to be a 14523 // flexible array member. 14524 Record->setHasFlexibleArrayMember(true); 14525 if (!Record->isUnion()) { 14526 // If this is a struct/class and this is not the last element, reject 14527 // it. Note that GCC supports variable sized arrays in the middle of 14528 // structures. 14529 if (i + 1 != Fields.end()) 14530 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14531 << FD->getDeclName() << FD->getType(); 14532 else { 14533 // We support flexible arrays at the end of structs in 14534 // other structs as an extension. 14535 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14536 << FD->getDeclName(); 14537 } 14538 } 14539 } 14540 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14541 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14542 diag::err_abstract_type_in_decl, 14543 AbstractIvarType)) { 14544 // Ivars can not have abstract class types 14545 FD->setInvalidDecl(); 14546 } 14547 if (Record && FDTTy->getDecl()->hasObjectMember()) 14548 Record->setHasObjectMember(true); 14549 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14550 Record->setHasVolatileMember(true); 14551 } else if (FDTy->isObjCObjectType()) { 14552 /// A field cannot be an Objective-c object 14553 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14554 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14555 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14556 FD->setType(T); 14557 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14558 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14559 // It's an error in ARC if a field has lifetime. 14560 // We don't want to report this in a system header, though, 14561 // so we just make the field unavailable. 14562 // FIXME: that's really not sufficient; we need to make the type 14563 // itself invalid to, say, initialize or copy. 14564 QualType T = FD->getType(); 14565 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14566 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14567 SourceLocation loc = FD->getLocation(); 14568 if (getSourceManager().isInSystemHeader(loc)) { 14569 if (!FD->hasAttr<UnavailableAttr>()) { 14570 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14571 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14572 } 14573 } else { 14574 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14575 << T->isBlockPointerType() << Record->getTagKind(); 14576 } 14577 ARCErrReported = true; 14578 } 14579 } else if (getLangOpts().ObjC1 && 14580 getLangOpts().getGC() != LangOptions::NonGC && 14581 Record && !Record->hasObjectMember()) { 14582 if (FD->getType()->isObjCObjectPointerType() || 14583 FD->getType().isObjCGCStrong()) 14584 Record->setHasObjectMember(true); 14585 else if (Context.getAsArrayType(FD->getType())) { 14586 QualType BaseType = Context.getBaseElementType(FD->getType()); 14587 if (BaseType->isRecordType() && 14588 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14589 Record->setHasObjectMember(true); 14590 else if (BaseType->isObjCObjectPointerType() || 14591 BaseType.isObjCGCStrong()) 14592 Record->setHasObjectMember(true); 14593 } 14594 } 14595 if (Record && FD->getType().isVolatileQualified()) 14596 Record->setHasVolatileMember(true); 14597 // Keep track of the number of named members. 14598 if (FD->getIdentifier()) 14599 ++NumNamedMembers; 14600 } 14601 14602 // Okay, we successfully defined 'Record'. 14603 if (Record) { 14604 bool Completed = false; 14605 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14606 if (!CXXRecord->isInvalidDecl()) { 14607 // Set access bits correctly on the directly-declared conversions. 14608 for (CXXRecordDecl::conversion_iterator 14609 I = CXXRecord->conversion_begin(), 14610 E = CXXRecord->conversion_end(); I != E; ++I) 14611 I.setAccess((*I)->getAccess()); 14612 } 14613 14614 if (!CXXRecord->isDependentType()) { 14615 if (CXXRecord->hasUserDeclaredDestructor()) { 14616 // Adjust user-defined destructor exception spec. 14617 if (getLangOpts().CPlusPlus11) 14618 AdjustDestructorExceptionSpec(CXXRecord, 14619 CXXRecord->getDestructor()); 14620 } 14621 14622 if (!CXXRecord->isInvalidDecl()) { 14623 // Add any implicitly-declared members to this class. 14624 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14625 14626 // If we have virtual base classes, we may end up finding multiple 14627 // final overriders for a given virtual function. Check for this 14628 // problem now. 14629 if (CXXRecord->getNumVBases()) { 14630 CXXFinalOverriderMap FinalOverriders; 14631 CXXRecord->getFinalOverriders(FinalOverriders); 14632 14633 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14634 MEnd = FinalOverriders.end(); 14635 M != MEnd; ++M) { 14636 for (OverridingMethods::iterator SO = M->second.begin(), 14637 SOEnd = M->second.end(); 14638 SO != SOEnd; ++SO) { 14639 assert(SO->second.size() > 0 && 14640 "Virtual function without overridding functions?"); 14641 if (SO->second.size() == 1) 14642 continue; 14643 14644 // C++ [class.virtual]p2: 14645 // In a derived class, if a virtual member function of a base 14646 // class subobject has more than one final overrider the 14647 // program is ill-formed. 14648 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14649 << (const NamedDecl *)M->first << Record; 14650 Diag(M->first->getLocation(), 14651 diag::note_overridden_virtual_function); 14652 for (OverridingMethods::overriding_iterator 14653 OM = SO->second.begin(), 14654 OMEnd = SO->second.end(); 14655 OM != OMEnd; ++OM) 14656 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14657 << (const NamedDecl *)M->first << OM->Method->getParent(); 14658 14659 Record->setInvalidDecl(); 14660 } 14661 } 14662 CXXRecord->completeDefinition(&FinalOverriders); 14663 Completed = true; 14664 } 14665 } 14666 } 14667 } 14668 14669 if (!Completed) 14670 Record->completeDefinition(); 14671 14672 // We may have deferred checking for a deleted destructor. Check now. 14673 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14674 auto *Dtor = CXXRecord->getDestructor(); 14675 if (Dtor && Dtor->isImplicit() && 14676 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14677 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14678 } 14679 14680 if (Record->hasAttrs()) { 14681 CheckAlignasUnderalignment(Record); 14682 14683 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14684 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14685 IA->getRange(), IA->getBestCase(), 14686 IA->getSemanticSpelling()); 14687 } 14688 14689 // Check if the structure/union declaration is a type that can have zero 14690 // size in C. For C this is a language extension, for C++ it may cause 14691 // compatibility problems. 14692 bool CheckForZeroSize; 14693 if (!getLangOpts().CPlusPlus) { 14694 CheckForZeroSize = true; 14695 } else { 14696 // For C++ filter out types that cannot be referenced in C code. 14697 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14698 CheckForZeroSize = 14699 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14700 !CXXRecord->isDependentType() && 14701 CXXRecord->isCLike(); 14702 } 14703 if (CheckForZeroSize) { 14704 bool ZeroSize = true; 14705 bool IsEmpty = true; 14706 unsigned NonBitFields = 0; 14707 for (RecordDecl::field_iterator I = Record->field_begin(), 14708 E = Record->field_end(); 14709 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14710 IsEmpty = false; 14711 if (I->isUnnamedBitfield()) { 14712 if (I->getBitWidthValue(Context) > 0) 14713 ZeroSize = false; 14714 } else { 14715 ++NonBitFields; 14716 QualType FieldType = I->getType(); 14717 if (FieldType->isIncompleteType() || 14718 !Context.getTypeSizeInChars(FieldType).isZero()) 14719 ZeroSize = false; 14720 } 14721 } 14722 14723 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14724 // allowed in C++, but warn if its declaration is inside 14725 // extern "C" block. 14726 if (ZeroSize) { 14727 Diag(RecLoc, getLangOpts().CPlusPlus ? 14728 diag::warn_zero_size_struct_union_in_extern_c : 14729 diag::warn_zero_size_struct_union_compat) 14730 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14731 } 14732 14733 // Structs without named members are extension in C (C99 6.7.2.1p7), 14734 // but are accepted by GCC. 14735 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14736 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14737 diag::ext_no_named_members_in_struct_union) 14738 << Record->isUnion(); 14739 } 14740 } 14741 } else { 14742 ObjCIvarDecl **ClsFields = 14743 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14744 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14745 ID->setEndOfDefinitionLoc(RBrac); 14746 // Add ivar's to class's DeclContext. 14747 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14748 ClsFields[i]->setLexicalDeclContext(ID); 14749 ID->addDecl(ClsFields[i]); 14750 } 14751 // Must enforce the rule that ivars in the base classes may not be 14752 // duplicates. 14753 if (ID->getSuperClass()) 14754 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14755 } else if (ObjCImplementationDecl *IMPDecl = 14756 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14757 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14758 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14759 // Ivar declared in @implementation never belongs to the implementation. 14760 // Only it is in implementation's lexical context. 14761 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14762 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14763 IMPDecl->setIvarLBraceLoc(LBrac); 14764 IMPDecl->setIvarRBraceLoc(RBrac); 14765 } else if (ObjCCategoryDecl *CDecl = 14766 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14767 // case of ivars in class extension; all other cases have been 14768 // reported as errors elsewhere. 14769 // FIXME. Class extension does not have a LocEnd field. 14770 // CDecl->setLocEnd(RBrac); 14771 // Add ivar's to class extension's DeclContext. 14772 // Diagnose redeclaration of private ivars. 14773 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14774 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14775 if (IDecl) { 14776 if (const ObjCIvarDecl *ClsIvar = 14777 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14778 Diag(ClsFields[i]->getLocation(), 14779 diag::err_duplicate_ivar_declaration); 14780 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14781 continue; 14782 } 14783 for (const auto *Ext : IDecl->known_extensions()) { 14784 if (const ObjCIvarDecl *ClsExtIvar 14785 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14786 Diag(ClsFields[i]->getLocation(), 14787 diag::err_duplicate_ivar_declaration); 14788 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14789 continue; 14790 } 14791 } 14792 } 14793 ClsFields[i]->setLexicalDeclContext(CDecl); 14794 CDecl->addDecl(ClsFields[i]); 14795 } 14796 CDecl->setIvarLBraceLoc(LBrac); 14797 CDecl->setIvarRBraceLoc(RBrac); 14798 } 14799 } 14800 14801 if (Attr) 14802 ProcessDeclAttributeList(S, Record, Attr); 14803 } 14804 14805 /// \brief Determine whether the given integral value is representable within 14806 /// the given type T. 14807 static bool isRepresentableIntegerValue(ASTContext &Context, 14808 llvm::APSInt &Value, 14809 QualType T) { 14810 assert(T->isIntegralType(Context) && "Integral type required!"); 14811 unsigned BitWidth = Context.getIntWidth(T); 14812 14813 if (Value.isUnsigned() || Value.isNonNegative()) { 14814 if (T->isSignedIntegerOrEnumerationType()) 14815 --BitWidth; 14816 return Value.getActiveBits() <= BitWidth; 14817 } 14818 return Value.getMinSignedBits() <= BitWidth; 14819 } 14820 14821 // \brief Given an integral type, return the next larger integral type 14822 // (or a NULL type of no such type exists). 14823 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14824 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14825 // enum checking below. 14826 assert(T->isIntegralType(Context) && "Integral type required!"); 14827 const unsigned NumTypes = 4; 14828 QualType SignedIntegralTypes[NumTypes] = { 14829 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14830 }; 14831 QualType UnsignedIntegralTypes[NumTypes] = { 14832 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14833 Context.UnsignedLongLongTy 14834 }; 14835 14836 unsigned BitWidth = Context.getTypeSize(T); 14837 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14838 : UnsignedIntegralTypes; 14839 for (unsigned I = 0; I != NumTypes; ++I) 14840 if (Context.getTypeSize(Types[I]) > BitWidth) 14841 return Types[I]; 14842 14843 return QualType(); 14844 } 14845 14846 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14847 EnumConstantDecl *LastEnumConst, 14848 SourceLocation IdLoc, 14849 IdentifierInfo *Id, 14850 Expr *Val) { 14851 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14852 llvm::APSInt EnumVal(IntWidth); 14853 QualType EltTy; 14854 14855 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14856 Val = nullptr; 14857 14858 if (Val) 14859 Val = DefaultLvalueConversion(Val).get(); 14860 14861 if (Val) { 14862 if (Enum->isDependentType() || Val->isTypeDependent()) 14863 EltTy = Context.DependentTy; 14864 else { 14865 SourceLocation ExpLoc; 14866 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14867 !getLangOpts().MSVCCompat) { 14868 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14869 // constant-expression in the enumerator-definition shall be a converted 14870 // constant expression of the underlying type. 14871 EltTy = Enum->getIntegerType(); 14872 ExprResult Converted = 14873 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14874 CCEK_Enumerator); 14875 if (Converted.isInvalid()) 14876 Val = nullptr; 14877 else 14878 Val = Converted.get(); 14879 } else if (!Val->isValueDependent() && 14880 !(Val = VerifyIntegerConstantExpression(Val, 14881 &EnumVal).get())) { 14882 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14883 } else { 14884 if (Enum->isFixed()) { 14885 EltTy = Enum->getIntegerType(); 14886 14887 // In Obj-C and Microsoft mode, require the enumeration value to be 14888 // representable in the underlying type of the enumeration. In C++11, 14889 // we perform a non-narrowing conversion as part of converted constant 14890 // expression checking. 14891 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14892 if (getLangOpts().MSVCCompat) { 14893 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14894 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14895 } else 14896 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14897 } else 14898 Val = ImpCastExprToType(Val, EltTy, 14899 EltTy->isBooleanType() ? 14900 CK_IntegralToBoolean : CK_IntegralCast) 14901 .get(); 14902 } else if (getLangOpts().CPlusPlus) { 14903 // C++11 [dcl.enum]p5: 14904 // If the underlying type is not fixed, the type of each enumerator 14905 // is the type of its initializing value: 14906 // - If an initializer is specified for an enumerator, the 14907 // initializing value has the same type as the expression. 14908 EltTy = Val->getType(); 14909 } else { 14910 // C99 6.7.2.2p2: 14911 // The expression that defines the value of an enumeration constant 14912 // shall be an integer constant expression that has a value 14913 // representable as an int. 14914 14915 // Complain if the value is not representable in an int. 14916 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14917 Diag(IdLoc, diag::ext_enum_value_not_int) 14918 << EnumVal.toString(10) << Val->getSourceRange() 14919 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14920 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14921 // Force the type of the expression to 'int'. 14922 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14923 } 14924 EltTy = Val->getType(); 14925 } 14926 } 14927 } 14928 } 14929 14930 if (!Val) { 14931 if (Enum->isDependentType()) 14932 EltTy = Context.DependentTy; 14933 else if (!LastEnumConst) { 14934 // C++0x [dcl.enum]p5: 14935 // If the underlying type is not fixed, the type of each enumerator 14936 // is the type of its initializing value: 14937 // - If no initializer is specified for the first enumerator, the 14938 // initializing value has an unspecified integral type. 14939 // 14940 // GCC uses 'int' for its unspecified integral type, as does 14941 // C99 6.7.2.2p3. 14942 if (Enum->isFixed()) { 14943 EltTy = Enum->getIntegerType(); 14944 } 14945 else { 14946 EltTy = Context.IntTy; 14947 } 14948 } else { 14949 // Assign the last value + 1. 14950 EnumVal = LastEnumConst->getInitVal(); 14951 ++EnumVal; 14952 EltTy = LastEnumConst->getType(); 14953 14954 // Check for overflow on increment. 14955 if (EnumVal < LastEnumConst->getInitVal()) { 14956 // C++0x [dcl.enum]p5: 14957 // If the underlying type is not fixed, the type of each enumerator 14958 // is the type of its initializing value: 14959 // 14960 // - Otherwise the type of the initializing value is the same as 14961 // the type of the initializing value of the preceding enumerator 14962 // unless the incremented value is not representable in that type, 14963 // in which case the type is an unspecified integral type 14964 // sufficient to contain the incremented value. If no such type 14965 // exists, the program is ill-formed. 14966 QualType T = getNextLargerIntegralType(Context, EltTy); 14967 if (T.isNull() || Enum->isFixed()) { 14968 // There is no integral type larger enough to represent this 14969 // value. Complain, then allow the value to wrap around. 14970 EnumVal = LastEnumConst->getInitVal(); 14971 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14972 ++EnumVal; 14973 if (Enum->isFixed()) 14974 // When the underlying type is fixed, this is ill-formed. 14975 Diag(IdLoc, diag::err_enumerator_wrapped) 14976 << EnumVal.toString(10) 14977 << EltTy; 14978 else 14979 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14980 << EnumVal.toString(10); 14981 } else { 14982 EltTy = T; 14983 } 14984 14985 // Retrieve the last enumerator's value, extent that type to the 14986 // type that is supposed to be large enough to represent the incremented 14987 // value, then increment. 14988 EnumVal = LastEnumConst->getInitVal(); 14989 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14990 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14991 ++EnumVal; 14992 14993 // If we're not in C++, diagnose the overflow of enumerator values, 14994 // which in C99 means that the enumerator value is not representable in 14995 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14996 // permits enumerator values that are representable in some larger 14997 // integral type. 14998 if (!getLangOpts().CPlusPlus && !T.isNull()) 14999 Diag(IdLoc, diag::warn_enum_value_overflow); 15000 } else if (!getLangOpts().CPlusPlus && 15001 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15002 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15003 Diag(IdLoc, diag::ext_enum_value_not_int) 15004 << EnumVal.toString(10) << 1; 15005 } 15006 } 15007 } 15008 15009 if (!EltTy->isDependentType()) { 15010 // Make the enumerator value match the signedness and size of the 15011 // enumerator's type. 15012 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15013 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15014 } 15015 15016 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15017 Val, EnumVal); 15018 } 15019 15020 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15021 SourceLocation IILoc) { 15022 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15023 !getLangOpts().CPlusPlus) 15024 return SkipBodyInfo(); 15025 15026 // We have an anonymous enum definition. Look up the first enumerator to 15027 // determine if we should merge the definition with an existing one and 15028 // skip the body. 15029 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15030 ForRedeclaration); 15031 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15032 if (!PrevECD) 15033 return SkipBodyInfo(); 15034 15035 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15036 NamedDecl *Hidden; 15037 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15038 SkipBodyInfo Skip; 15039 Skip.Previous = Hidden; 15040 return Skip; 15041 } 15042 15043 return SkipBodyInfo(); 15044 } 15045 15046 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15047 SourceLocation IdLoc, IdentifierInfo *Id, 15048 AttributeList *Attr, 15049 SourceLocation EqualLoc, Expr *Val) { 15050 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15051 EnumConstantDecl *LastEnumConst = 15052 cast_or_null<EnumConstantDecl>(lastEnumConst); 15053 15054 // The scope passed in may not be a decl scope. Zip up the scope tree until 15055 // we find one that is. 15056 S = getNonFieldDeclScope(S); 15057 15058 // Verify that there isn't already something declared with this name in this 15059 // scope. 15060 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15061 ForRedeclaration); 15062 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15063 // Maybe we will complain about the shadowed template parameter. 15064 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15065 // Just pretend that we didn't see the previous declaration. 15066 PrevDecl = nullptr; 15067 } 15068 15069 // C++ [class.mem]p15: 15070 // If T is the name of a class, then each of the following shall have a name 15071 // different from T: 15072 // - every enumerator of every member of class T that is an unscoped 15073 // enumerated type 15074 if (!TheEnumDecl->isScoped()) 15075 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15076 DeclarationNameInfo(Id, IdLoc)); 15077 15078 EnumConstantDecl *New = 15079 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15080 if (!New) 15081 return nullptr; 15082 15083 if (PrevDecl) { 15084 // When in C++, we may get a TagDecl with the same name; in this case the 15085 // enum constant will 'hide' the tag. 15086 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15087 "Received TagDecl when not in C++!"); 15088 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15089 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15090 if (isa<EnumConstantDecl>(PrevDecl)) 15091 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15092 else 15093 Diag(IdLoc, diag::err_redefinition) << Id; 15094 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15095 return nullptr; 15096 } 15097 } 15098 15099 // Process attributes. 15100 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15101 15102 // Register this decl in the current scope stack. 15103 New->setAccess(TheEnumDecl->getAccess()); 15104 PushOnScopeChains(New, S); 15105 15106 ActOnDocumentableDecl(New); 15107 15108 return New; 15109 } 15110 15111 // Returns true when the enum initial expression does not trigger the 15112 // duplicate enum warning. A few common cases are exempted as follows: 15113 // Element2 = Element1 15114 // Element2 = Element1 + 1 15115 // Element2 = Element1 - 1 15116 // Where Element2 and Element1 are from the same enum. 15117 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15118 Expr *InitExpr = ECD->getInitExpr(); 15119 if (!InitExpr) 15120 return true; 15121 InitExpr = InitExpr->IgnoreImpCasts(); 15122 15123 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15124 if (!BO->isAdditiveOp()) 15125 return true; 15126 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15127 if (!IL) 15128 return true; 15129 if (IL->getValue() != 1) 15130 return true; 15131 15132 InitExpr = BO->getLHS(); 15133 } 15134 15135 // This checks if the elements are from the same enum. 15136 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15137 if (!DRE) 15138 return true; 15139 15140 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15141 if (!EnumConstant) 15142 return true; 15143 15144 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15145 Enum) 15146 return true; 15147 15148 return false; 15149 } 15150 15151 namespace { 15152 struct DupKey { 15153 int64_t val; 15154 bool isTombstoneOrEmptyKey; 15155 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15156 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15157 }; 15158 15159 static DupKey GetDupKey(const llvm::APSInt& Val) { 15160 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15161 false); 15162 } 15163 15164 struct DenseMapInfoDupKey { 15165 static DupKey getEmptyKey() { return DupKey(0, true); } 15166 static DupKey getTombstoneKey() { return DupKey(1, true); } 15167 static unsigned getHashValue(const DupKey Key) { 15168 return (unsigned)(Key.val * 37); 15169 } 15170 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15171 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15172 LHS.val == RHS.val; 15173 } 15174 }; 15175 } // end anonymous namespace 15176 15177 // Emits a warning when an element is implicitly set a value that 15178 // a previous element has already been set to. 15179 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15180 EnumDecl *Enum, 15181 QualType EnumType) { 15182 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15183 return; 15184 // Avoid anonymous enums 15185 if (!Enum->getIdentifier()) 15186 return; 15187 15188 // Only check for small enums. 15189 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15190 return; 15191 15192 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15193 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15194 15195 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15196 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15197 ValueToVectorMap; 15198 15199 DuplicatesVector DupVector; 15200 ValueToVectorMap EnumMap; 15201 15202 // Populate the EnumMap with all values represented by enum constants without 15203 // an initialier. 15204 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15205 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15206 15207 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15208 // this constant. Skip this enum since it may be ill-formed. 15209 if (!ECD) { 15210 return; 15211 } 15212 15213 if (ECD->getInitExpr()) 15214 continue; 15215 15216 DupKey Key = GetDupKey(ECD->getInitVal()); 15217 DeclOrVector &Entry = EnumMap[Key]; 15218 15219 // First time encountering this value. 15220 if (Entry.isNull()) 15221 Entry = ECD; 15222 } 15223 15224 // Create vectors for any values that has duplicates. 15225 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15226 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15227 if (!ValidDuplicateEnum(ECD, Enum)) 15228 continue; 15229 15230 DupKey Key = GetDupKey(ECD->getInitVal()); 15231 15232 DeclOrVector& Entry = EnumMap[Key]; 15233 if (Entry.isNull()) 15234 continue; 15235 15236 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15237 // Ensure constants are different. 15238 if (D == ECD) 15239 continue; 15240 15241 // Create new vector and push values onto it. 15242 ECDVector *Vec = new ECDVector(); 15243 Vec->push_back(D); 15244 Vec->push_back(ECD); 15245 15246 // Update entry to point to the duplicates vector. 15247 Entry = Vec; 15248 15249 // Store the vector somewhere we can consult later for quick emission of 15250 // diagnostics. 15251 DupVector.push_back(Vec); 15252 continue; 15253 } 15254 15255 ECDVector *Vec = Entry.get<ECDVector*>(); 15256 // Make sure constants are not added more than once. 15257 if (*Vec->begin() == ECD) 15258 continue; 15259 15260 Vec->push_back(ECD); 15261 } 15262 15263 // Emit diagnostics. 15264 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15265 DupVectorEnd = DupVector.end(); 15266 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15267 ECDVector *Vec = *DupVectorIter; 15268 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15269 15270 // Emit warning for one enum constant. 15271 ECDVector::iterator I = Vec->begin(); 15272 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15273 << (*I)->getName() << (*I)->getInitVal().toString(10) 15274 << (*I)->getSourceRange(); 15275 ++I; 15276 15277 // Emit one note for each of the remaining enum constants with 15278 // the same value. 15279 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15280 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15281 << (*I)->getName() << (*I)->getInitVal().toString(10) 15282 << (*I)->getSourceRange(); 15283 delete Vec; 15284 } 15285 } 15286 15287 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15288 bool AllowMask) const { 15289 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 15290 assert(ED->isCompleteDefinition() && "expected enum definition"); 15291 15292 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15293 llvm::APInt &FlagBits = R.first->second; 15294 15295 if (R.second) { 15296 for (auto *E : ED->enumerators()) { 15297 const auto &EVal = E->getInitVal(); 15298 // Only single-bit enumerators introduce new flag values. 15299 if (EVal.isPowerOf2()) 15300 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15301 } 15302 } 15303 15304 // A value is in a flag enum if either its bits are a subset of the enum's 15305 // flag bits (the first condition) or we are allowing masks and the same is 15306 // true of its complement (the second condition). When masks are allowed, we 15307 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15308 // 15309 // While it's true that any value could be used as a mask, the assumption is 15310 // that a mask will have all of the insignificant bits set. Anything else is 15311 // likely a logic error. 15312 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15313 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15314 } 15315 15316 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15317 Decl *EnumDeclX, 15318 ArrayRef<Decl *> Elements, 15319 Scope *S, AttributeList *Attr) { 15320 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15321 QualType EnumType = Context.getTypeDeclType(Enum); 15322 15323 if (Attr) 15324 ProcessDeclAttributeList(S, Enum, Attr); 15325 15326 if (Enum->isDependentType()) { 15327 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15328 EnumConstantDecl *ECD = 15329 cast_or_null<EnumConstantDecl>(Elements[i]); 15330 if (!ECD) continue; 15331 15332 ECD->setType(EnumType); 15333 } 15334 15335 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15336 return; 15337 } 15338 15339 // TODO: If the result value doesn't fit in an int, it must be a long or long 15340 // long value. ISO C does not support this, but GCC does as an extension, 15341 // emit a warning. 15342 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15343 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15344 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15345 15346 // Verify that all the values are okay, compute the size of the values, and 15347 // reverse the list. 15348 unsigned NumNegativeBits = 0; 15349 unsigned NumPositiveBits = 0; 15350 15351 // Keep track of whether all elements have type int. 15352 bool AllElementsInt = true; 15353 15354 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15355 EnumConstantDecl *ECD = 15356 cast_or_null<EnumConstantDecl>(Elements[i]); 15357 if (!ECD) continue; // Already issued a diagnostic. 15358 15359 const llvm::APSInt &InitVal = ECD->getInitVal(); 15360 15361 // Keep track of the size of positive and negative values. 15362 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15363 NumPositiveBits = std::max(NumPositiveBits, 15364 (unsigned)InitVal.getActiveBits()); 15365 else 15366 NumNegativeBits = std::max(NumNegativeBits, 15367 (unsigned)InitVal.getMinSignedBits()); 15368 15369 // Keep track of whether every enum element has type int (very commmon). 15370 if (AllElementsInt) 15371 AllElementsInt = ECD->getType() == Context.IntTy; 15372 } 15373 15374 // Figure out the type that should be used for this enum. 15375 QualType BestType; 15376 unsigned BestWidth; 15377 15378 // C++0x N3000 [conv.prom]p3: 15379 // An rvalue of an unscoped enumeration type whose underlying 15380 // type is not fixed can be converted to an rvalue of the first 15381 // of the following types that can represent all the values of 15382 // the enumeration: int, unsigned int, long int, unsigned long 15383 // int, long long int, or unsigned long long int. 15384 // C99 6.4.4.3p2: 15385 // An identifier declared as an enumeration constant has type int. 15386 // The C99 rule is modified by a gcc extension 15387 QualType BestPromotionType; 15388 15389 bool Packed = Enum->hasAttr<PackedAttr>(); 15390 // -fshort-enums is the equivalent to specifying the packed attribute on all 15391 // enum definitions. 15392 if (LangOpts.ShortEnums) 15393 Packed = true; 15394 15395 if (Enum->isFixed()) { 15396 BestType = Enum->getIntegerType(); 15397 if (BestType->isPromotableIntegerType()) 15398 BestPromotionType = Context.getPromotedIntegerType(BestType); 15399 else 15400 BestPromotionType = BestType; 15401 15402 BestWidth = Context.getIntWidth(BestType); 15403 } 15404 else if (NumNegativeBits) { 15405 // If there is a negative value, figure out the smallest integer type (of 15406 // int/long/longlong) that fits. 15407 // If it's packed, check also if it fits a char or a short. 15408 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15409 BestType = Context.SignedCharTy; 15410 BestWidth = CharWidth; 15411 } else if (Packed && NumNegativeBits <= ShortWidth && 15412 NumPositiveBits < ShortWidth) { 15413 BestType = Context.ShortTy; 15414 BestWidth = ShortWidth; 15415 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15416 BestType = Context.IntTy; 15417 BestWidth = IntWidth; 15418 } else { 15419 BestWidth = Context.getTargetInfo().getLongWidth(); 15420 15421 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15422 BestType = Context.LongTy; 15423 } else { 15424 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15425 15426 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15427 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15428 BestType = Context.LongLongTy; 15429 } 15430 } 15431 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15432 } else { 15433 // If there is no negative value, figure out the smallest type that fits 15434 // all of the enumerator values. 15435 // If it's packed, check also if it fits a char or a short. 15436 if (Packed && NumPositiveBits <= CharWidth) { 15437 BestType = Context.UnsignedCharTy; 15438 BestPromotionType = Context.IntTy; 15439 BestWidth = CharWidth; 15440 } else if (Packed && NumPositiveBits <= ShortWidth) { 15441 BestType = Context.UnsignedShortTy; 15442 BestPromotionType = Context.IntTy; 15443 BestWidth = ShortWidth; 15444 } else if (NumPositiveBits <= IntWidth) { 15445 BestType = Context.UnsignedIntTy; 15446 BestWidth = IntWidth; 15447 BestPromotionType 15448 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15449 ? Context.UnsignedIntTy : Context.IntTy; 15450 } else if (NumPositiveBits <= 15451 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15452 BestType = Context.UnsignedLongTy; 15453 BestPromotionType 15454 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15455 ? Context.UnsignedLongTy : Context.LongTy; 15456 } else { 15457 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15458 assert(NumPositiveBits <= BestWidth && 15459 "How could an initializer get larger than ULL?"); 15460 BestType = Context.UnsignedLongLongTy; 15461 BestPromotionType 15462 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15463 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15464 } 15465 } 15466 15467 // Loop over all of the enumerator constants, changing their types to match 15468 // the type of the enum if needed. 15469 for (auto *D : Elements) { 15470 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15471 if (!ECD) continue; // Already issued a diagnostic. 15472 15473 // Standard C says the enumerators have int type, but we allow, as an 15474 // extension, the enumerators to be larger than int size. If each 15475 // enumerator value fits in an int, type it as an int, otherwise type it the 15476 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15477 // that X has type 'int', not 'unsigned'. 15478 15479 // Determine whether the value fits into an int. 15480 llvm::APSInt InitVal = ECD->getInitVal(); 15481 15482 // If it fits into an integer type, force it. Otherwise force it to match 15483 // the enum decl type. 15484 QualType NewTy; 15485 unsigned NewWidth; 15486 bool NewSign; 15487 if (!getLangOpts().CPlusPlus && 15488 !Enum->isFixed() && 15489 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15490 NewTy = Context.IntTy; 15491 NewWidth = IntWidth; 15492 NewSign = true; 15493 } else if (ECD->getType() == BestType) { 15494 // Already the right type! 15495 if (getLangOpts().CPlusPlus) 15496 // C++ [dcl.enum]p4: Following the closing brace of an 15497 // enum-specifier, each enumerator has the type of its 15498 // enumeration. 15499 ECD->setType(EnumType); 15500 continue; 15501 } else { 15502 NewTy = BestType; 15503 NewWidth = BestWidth; 15504 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15505 } 15506 15507 // Adjust the APSInt value. 15508 InitVal = InitVal.extOrTrunc(NewWidth); 15509 InitVal.setIsSigned(NewSign); 15510 ECD->setInitVal(InitVal); 15511 15512 // Adjust the Expr initializer and type. 15513 if (ECD->getInitExpr() && 15514 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15515 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15516 CK_IntegralCast, 15517 ECD->getInitExpr(), 15518 /*base paths*/ nullptr, 15519 VK_RValue)); 15520 if (getLangOpts().CPlusPlus) 15521 // C++ [dcl.enum]p4: Following the closing brace of an 15522 // enum-specifier, each enumerator has the type of its 15523 // enumeration. 15524 ECD->setType(EnumType); 15525 else 15526 ECD->setType(NewTy); 15527 } 15528 15529 Enum->completeDefinition(BestType, BestPromotionType, 15530 NumPositiveBits, NumNegativeBits); 15531 15532 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15533 15534 if (Enum->hasAttr<FlagEnumAttr>()) { 15535 for (Decl *D : Elements) { 15536 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15537 if (!ECD) continue; // Already issued a diagnostic. 15538 15539 llvm::APSInt InitVal = ECD->getInitVal(); 15540 if (InitVal != 0 && !InitVal.isPowerOf2() && 15541 !IsValueInFlagEnum(Enum, InitVal, true)) 15542 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15543 << ECD << Enum; 15544 } 15545 } 15546 15547 // Now that the enum type is defined, ensure it's not been underaligned. 15548 if (Enum->hasAttrs()) 15549 CheckAlignasUnderalignment(Enum); 15550 } 15551 15552 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15553 SourceLocation StartLoc, 15554 SourceLocation EndLoc) { 15555 StringLiteral *AsmString = cast<StringLiteral>(expr); 15556 15557 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15558 AsmString, StartLoc, 15559 EndLoc); 15560 CurContext->addDecl(New); 15561 return New; 15562 } 15563 15564 static void checkModuleImportContext(Sema &S, Module *M, 15565 SourceLocation ImportLoc, DeclContext *DC, 15566 bool FromInclude = false) { 15567 SourceLocation ExternCLoc; 15568 15569 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15570 switch (LSD->getLanguage()) { 15571 case LinkageSpecDecl::lang_c: 15572 if (ExternCLoc.isInvalid()) 15573 ExternCLoc = LSD->getLocStart(); 15574 break; 15575 case LinkageSpecDecl::lang_cxx: 15576 break; 15577 } 15578 DC = LSD->getParent(); 15579 } 15580 15581 while (isa<LinkageSpecDecl>(DC)) 15582 DC = DC->getParent(); 15583 15584 if (!isa<TranslationUnitDecl>(DC)) { 15585 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15586 ? diag::ext_module_import_not_at_top_level_noop 15587 : diag::err_module_import_not_at_top_level_fatal) 15588 << M->getFullModuleName() << DC; 15589 S.Diag(cast<Decl>(DC)->getLocStart(), 15590 diag::note_module_import_not_at_top_level) << DC; 15591 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15592 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15593 << M->getFullModuleName(); 15594 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15595 } 15596 } 15597 15598 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15599 ModuleDeclKind MDK, 15600 ModuleIdPath Path) { 15601 // 'module implementation' requires that we are not compiling a module of any 15602 // kind. 'module' and 'module partition' require that we are compiling a 15603 // module inteface (not a module map). 15604 auto CMK = getLangOpts().getCompilingModule(); 15605 if (MDK == ModuleDeclKind::Implementation 15606 ? CMK != LangOptions::CMK_None 15607 : CMK != LangOptions::CMK_ModuleInterface) { 15608 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15609 << (unsigned)MDK; 15610 return nullptr; 15611 } 15612 15613 // FIXME: Create a ModuleDecl and return it. 15614 15615 // FIXME: Most of this work should be done by the preprocessor rather than 15616 // here, in case we look ahead across something where the current 15617 // module matters (eg a #include). 15618 15619 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15620 // hierarchical module map modules, the dots here are just another character 15621 // that can appear in a module name. Flatten down to the actual module name. 15622 std::string ModuleName; 15623 for (auto &Piece : Path) { 15624 if (!ModuleName.empty()) 15625 ModuleName += "."; 15626 ModuleName += Piece.first->getName(); 15627 } 15628 15629 // If a module name was explicitly specified on the command line, it must be 15630 // correct. 15631 if (!getLangOpts().CurrentModule.empty() && 15632 getLangOpts().CurrentModule != ModuleName) { 15633 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15634 << SourceRange(Path.front().second, Path.back().second) 15635 << getLangOpts().CurrentModule; 15636 return nullptr; 15637 } 15638 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15639 15640 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15641 15642 switch (MDK) { 15643 case ModuleDeclKind::Module: { 15644 // FIXME: Check we're not in a submodule. 15645 15646 // We can't have imported a definition of this module or parsed a module 15647 // map defining it already. 15648 if (auto *M = Map.findModule(ModuleName)) { 15649 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15650 if (M->DefinitionLoc.isValid()) 15651 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15652 else if (const auto *FE = M->getASTFile()) 15653 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15654 << FE->getName(); 15655 return nullptr; 15656 } 15657 15658 // Create a Module for the module that we're defining. 15659 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15660 assert(Mod && "module creation should not fail"); 15661 15662 // Enter the semantic scope of the module. 15663 ActOnModuleBegin(ModuleLoc, Mod); 15664 return nullptr; 15665 } 15666 15667 case ModuleDeclKind::Partition: 15668 // FIXME: Check we are in a submodule of the named module. 15669 return nullptr; 15670 15671 case ModuleDeclKind::Implementation: 15672 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15673 PP.getIdentifierInfo(ModuleName), Path[0].second); 15674 15675 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15676 if (Import.isInvalid()) 15677 return nullptr; 15678 return ConvertDeclToDeclGroup(Import.get()); 15679 } 15680 15681 llvm_unreachable("unexpected module decl kind"); 15682 } 15683 15684 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15685 SourceLocation ImportLoc, 15686 ModuleIdPath Path) { 15687 Module *Mod = 15688 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15689 /*IsIncludeDirective=*/false); 15690 if (!Mod) 15691 return true; 15692 15693 VisibleModules.setVisible(Mod, ImportLoc); 15694 15695 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15696 15697 // FIXME: we should support importing a submodule within a different submodule 15698 // of the same top-level module. Until we do, make it an error rather than 15699 // silently ignoring the import. 15700 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15701 // warn on a redundant import of the current module? 15702 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15703 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15704 Diag(ImportLoc, getLangOpts().isCompilingModule() 15705 ? diag::err_module_self_import 15706 : diag::err_module_import_in_implementation) 15707 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15708 15709 SmallVector<SourceLocation, 2> IdentifierLocs; 15710 Module *ModCheck = Mod; 15711 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15712 // If we've run out of module parents, just drop the remaining identifiers. 15713 // We need the length to be consistent. 15714 if (!ModCheck) 15715 break; 15716 ModCheck = ModCheck->Parent; 15717 15718 IdentifierLocs.push_back(Path[I].second); 15719 } 15720 15721 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15722 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15723 Mod, IdentifierLocs); 15724 if (!ModuleScopes.empty()) 15725 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15726 TU->addDecl(Import); 15727 return Import; 15728 } 15729 15730 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15731 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15732 BuildModuleInclude(DirectiveLoc, Mod); 15733 } 15734 15735 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15736 // Determine whether we're in the #include buffer for a module. The #includes 15737 // in that buffer do not qualify as module imports; they're just an 15738 // implementation detail of us building the module. 15739 // 15740 // FIXME: Should we even get ActOnModuleInclude calls for those? 15741 bool IsInModuleIncludes = 15742 TUKind == TU_Module && 15743 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15744 15745 bool ShouldAddImport = !IsInModuleIncludes; 15746 15747 // If this module import was due to an inclusion directive, create an 15748 // implicit import declaration to capture it in the AST. 15749 if (ShouldAddImport) { 15750 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15751 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15752 DirectiveLoc, Mod, 15753 DirectiveLoc); 15754 if (!ModuleScopes.empty()) 15755 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15756 TU->addDecl(ImportD); 15757 Consumer.HandleImplicitImportDecl(ImportD); 15758 } 15759 15760 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15761 VisibleModules.setVisible(Mod, DirectiveLoc); 15762 } 15763 15764 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15765 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15766 15767 ModuleScopes.push_back({}); 15768 ModuleScopes.back().Module = Mod; 15769 if (getLangOpts().ModulesLocalVisibility) 15770 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15771 15772 VisibleModules.setVisible(Mod, DirectiveLoc); 15773 } 15774 15775 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15776 if (getLangOpts().ModulesLocalVisibility) { 15777 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15778 // Leaving a module hides namespace names, so our visible namespace cache 15779 // is now out of date. 15780 VisibleNamespaceCache.clear(); 15781 } 15782 15783 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15784 "left the wrong module scope"); 15785 ModuleScopes.pop_back(); 15786 15787 // We got to the end of processing a #include of a local module. Create an 15788 // ImportDecl as we would for an imported module. 15789 FileID File = getSourceManager().getFileID(EofLoc); 15790 assert(File != getSourceManager().getMainFileID() && 15791 "end of submodule in main source file"); 15792 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15793 BuildModuleInclude(DirectiveLoc, Mod); 15794 } 15795 15796 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15797 Module *Mod) { 15798 // Bail if we're not allowed to implicitly import a module here. 15799 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15800 return; 15801 15802 // Create the implicit import declaration. 15803 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15804 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15805 Loc, Mod, Loc); 15806 TU->addDecl(ImportD); 15807 Consumer.HandleImplicitImportDecl(ImportD); 15808 15809 // Make the module visible. 15810 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15811 VisibleModules.setVisible(Mod, Loc); 15812 } 15813 15814 /// We have parsed the start of an export declaration, including the '{' 15815 /// (if present). 15816 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15817 SourceLocation LBraceLoc) { 15818 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15819 15820 // C++ Modules TS draft: 15821 // An export-declaration [...] shall not contain more than one 15822 // export keyword. 15823 // 15824 // The intent here is that an export-declaration cannot appear within another 15825 // export-declaration. 15826 if (D->isExported()) 15827 Diag(ExportLoc, diag::err_export_within_export); 15828 15829 CurContext->addDecl(D); 15830 PushDeclContext(S, D); 15831 return D; 15832 } 15833 15834 /// Complete the definition of an export declaration. 15835 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15836 auto *ED = cast<ExportDecl>(D); 15837 if (RBraceLoc.isValid()) 15838 ED->setRBraceLoc(RBraceLoc); 15839 15840 // FIXME: Diagnose export of internal-linkage declaration (including 15841 // anonymous namespace). 15842 15843 PopDeclContext(); 15844 return D; 15845 } 15846 15847 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15848 IdentifierInfo* AliasName, 15849 SourceLocation PragmaLoc, 15850 SourceLocation NameLoc, 15851 SourceLocation AliasNameLoc) { 15852 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15853 LookupOrdinaryName); 15854 AsmLabelAttr *Attr = 15855 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15856 15857 // If a declaration that: 15858 // 1) declares a function or a variable 15859 // 2) has external linkage 15860 // already exists, add a label attribute to it. 15861 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15862 if (isDeclExternC(PrevDecl)) 15863 PrevDecl->addAttr(Attr); 15864 else 15865 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15866 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15867 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15868 } else 15869 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15870 } 15871 15872 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15873 SourceLocation PragmaLoc, 15874 SourceLocation NameLoc) { 15875 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15876 15877 if (PrevDecl) { 15878 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15879 } else { 15880 (void)WeakUndeclaredIdentifiers.insert( 15881 std::pair<IdentifierInfo*,WeakInfo> 15882 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15883 } 15884 } 15885 15886 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15887 IdentifierInfo* AliasName, 15888 SourceLocation PragmaLoc, 15889 SourceLocation NameLoc, 15890 SourceLocation AliasNameLoc) { 15891 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15892 LookupOrdinaryName); 15893 WeakInfo W = WeakInfo(Name, NameLoc); 15894 15895 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15896 if (!PrevDecl->hasAttr<AliasAttr>()) 15897 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15898 DeclApplyPragmaWeak(TUScope, ND, W); 15899 } else { 15900 (void)WeakUndeclaredIdentifiers.insert( 15901 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15902 } 15903 } 15904 15905 Decl *Sema::getObjCDeclContext() const { 15906 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15907 } 15908