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 static bool isTypeTemplate(NamedDecl *ND) { 64 return isa<ClassTemplateDecl>(ND) || isa<TypeAliasTemplateDecl>(ND) || 65 isa<TemplateTemplateParmDecl>(ND); 66 } 67 68 namespace { 69 70 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 71 public: 72 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 73 bool AllowTemplates=false) 74 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 75 AllowTemplates(AllowTemplates) { 76 WantExpressionKeywords = false; 77 WantCXXNamedCasts = false; 78 WantRemainingKeywords = false; 79 } 80 81 bool ValidateCandidate(const TypoCorrection &candidate) override { 82 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 83 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 84 bool AllowedTemplate = AllowTemplates && isTypeTemplate(ND); 85 return (IsType || AllowedTemplate) && 86 (AllowInvalidDecl || !ND->isInvalidDecl()); 87 } 88 return !WantClassName && candidate.isKeyword(); 89 } 90 91 private: 92 bool AllowInvalidDecl; 93 bool WantClassName; 94 bool AllowTemplates; 95 }; 96 97 } // end anonymous namespace 98 99 /// \brief Determine whether the token kind starts a simple-type-specifier. 100 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 101 switch (Kind) { 102 // FIXME: Take into account the current language when deciding whether a 103 // token kind is a valid type specifier 104 case tok::kw_short: 105 case tok::kw_long: 106 case tok::kw___int64: 107 case tok::kw___int128: 108 case tok::kw_signed: 109 case tok::kw_unsigned: 110 case tok::kw_void: 111 case tok::kw_char: 112 case tok::kw_int: 113 case tok::kw_half: 114 case tok::kw_float: 115 case tok::kw_double: 116 case tok::kw___float128: 117 case tok::kw_wchar_t: 118 case tok::kw_bool: 119 case tok::kw___underlying_type: 120 case tok::kw___auto_type: 121 return true; 122 123 case tok::annot_typename: 124 case tok::kw_char16_t: 125 case tok::kw_char32_t: 126 case tok::kw_typeof: 127 case tok::annot_decltype: 128 case tok::kw_decltype: 129 return getLangOpts().CPlusPlus; 130 131 default: 132 break; 133 } 134 135 return false; 136 } 137 138 namespace { 139 enum class UnqualifiedTypeNameLookupResult { 140 NotFound, 141 FoundNonType, 142 FoundType 143 }; 144 } // end anonymous namespace 145 146 /// \brief Tries to perform unqualified lookup of the type decls in bases for 147 /// dependent class. 148 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 149 /// type decl, \a FoundType if only type decls are found. 150 static UnqualifiedTypeNameLookupResult 151 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 152 SourceLocation NameLoc, 153 const CXXRecordDecl *RD) { 154 if (!RD->hasDefinition()) 155 return UnqualifiedTypeNameLookupResult::NotFound; 156 // Look for type decls in base classes. 157 UnqualifiedTypeNameLookupResult FoundTypeDecl = 158 UnqualifiedTypeNameLookupResult::NotFound; 159 for (const auto &Base : RD->bases()) { 160 const CXXRecordDecl *BaseRD = nullptr; 161 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 162 BaseRD = BaseTT->getAsCXXRecordDecl(); 163 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 164 // Look for type decls in dependent base classes that have known primary 165 // templates. 166 if (!TST || !TST->isDependentType()) 167 continue; 168 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 169 if (!TD) 170 continue; 171 if (auto *BasePrimaryTemplate = 172 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 173 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 174 BaseRD = BasePrimaryTemplate; 175 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 176 if (const ClassTemplatePartialSpecializationDecl *PS = 177 CTD->findPartialSpecialization(Base.getType())) 178 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 179 BaseRD = PS; 180 } 181 } 182 } 183 if (BaseRD) { 184 for (NamedDecl *ND : BaseRD->lookup(&II)) { 185 if (!isa<TypeDecl>(ND)) 186 return UnqualifiedTypeNameLookupResult::FoundNonType; 187 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 188 } 189 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 190 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 191 case UnqualifiedTypeNameLookupResult::FoundNonType: 192 return UnqualifiedTypeNameLookupResult::FoundNonType; 193 case UnqualifiedTypeNameLookupResult::FoundType: 194 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 195 break; 196 case UnqualifiedTypeNameLookupResult::NotFound: 197 break; 198 } 199 } 200 } 201 } 202 203 return FoundTypeDecl; 204 } 205 206 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 207 const IdentifierInfo &II, 208 SourceLocation NameLoc) { 209 // Lookup in the parent class template context, if any. 210 const CXXRecordDecl *RD = nullptr; 211 UnqualifiedTypeNameLookupResult FoundTypeDecl = 212 UnqualifiedTypeNameLookupResult::NotFound; 213 for (DeclContext *DC = S.CurContext; 214 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 215 DC = DC->getParent()) { 216 // Look for type decls in dependent base classes that have known primary 217 // templates. 218 RD = dyn_cast<CXXRecordDecl>(DC); 219 if (RD && RD->getDescribedClassTemplate()) 220 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 221 } 222 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 223 return nullptr; 224 225 // We found some types in dependent base classes. Recover as if the user 226 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 227 // lookup during template instantiation. 228 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 229 230 ASTContext &Context = S.Context; 231 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 232 cast<Type>(Context.getRecordType(RD))); 233 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 234 235 CXXScopeSpec SS; 236 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 237 238 TypeLocBuilder Builder; 239 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 240 DepTL.setNameLoc(NameLoc); 241 DepTL.setElaboratedKeywordLoc(SourceLocation()); 242 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 243 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 244 } 245 246 /// \brief If the identifier refers to a type name within this scope, 247 /// return the declaration of that type. 248 /// 249 /// This routine performs ordinary name lookup of the identifier II 250 /// within the given scope, with optional C++ scope specifier SS, to 251 /// determine whether the name refers to a type. If so, returns an 252 /// opaque pointer (actually a QualType) corresponding to that 253 /// type. Otherwise, returns NULL. 254 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 255 Scope *S, CXXScopeSpec *SS, 256 bool isClassName, bool HasTrailingDot, 257 ParsedType ObjectTypePtr, 258 bool IsCtorOrDtorName, 259 bool WantNontrivialTypeSourceInfo, 260 bool IsClassTemplateDeductionContext, 261 IdentifierInfo **CorrectedII) { 262 // FIXME: Consider allowing this outside C++1z mode as an extension. 263 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 264 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 265 !isClassName && !HasTrailingDot; 266 267 // Determine where we will perform name lookup. 268 DeclContext *LookupCtx = nullptr; 269 if (ObjectTypePtr) { 270 QualType ObjectType = ObjectTypePtr.get(); 271 if (ObjectType->isRecordType()) 272 LookupCtx = computeDeclContext(ObjectType); 273 } else if (SS && SS->isNotEmpty()) { 274 LookupCtx = computeDeclContext(*SS, false); 275 276 if (!LookupCtx) { 277 if (isDependentScopeSpecifier(*SS)) { 278 // C++ [temp.res]p3: 279 // A qualified-id that refers to a type and in which the 280 // nested-name-specifier depends on a template-parameter (14.6.2) 281 // shall be prefixed by the keyword typename to indicate that the 282 // qualified-id denotes a type, forming an 283 // elaborated-type-specifier (7.1.5.3). 284 // 285 // We therefore do not perform any name lookup if the result would 286 // refer to a member of an unknown specialization. 287 if (!isClassName && !IsCtorOrDtorName) 288 return nullptr; 289 290 // We know from the grammar that this name refers to a type, 291 // so build a dependent node to describe the type. 292 if (WantNontrivialTypeSourceInfo) 293 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 294 295 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 296 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 297 II, NameLoc); 298 return ParsedType::make(T); 299 } 300 301 return nullptr; 302 } 303 304 if (!LookupCtx->isDependentContext() && 305 RequireCompleteDeclContext(*SS, LookupCtx)) 306 return nullptr; 307 } 308 309 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 310 // lookup for class-names. 311 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 312 LookupOrdinaryName; 313 LookupResult Result(*this, &II, NameLoc, Kind); 314 if (LookupCtx) { 315 // Perform "qualified" name lookup into the declaration context we 316 // computed, which is either the type of the base of a member access 317 // expression or the declaration context associated with a prior 318 // nested-name-specifier. 319 LookupQualifiedName(Result, LookupCtx); 320 321 if (ObjectTypePtr && Result.empty()) { 322 // C++ [basic.lookup.classref]p3: 323 // If the unqualified-id is ~type-name, the type-name is looked up 324 // in the context of the entire postfix-expression. If the type T of 325 // the object expression is of a class type C, the type-name is also 326 // looked up in the scope of class C. At least one of the lookups shall 327 // find a name that refers to (possibly cv-qualified) T. 328 LookupName(Result, S); 329 } 330 } else { 331 // Perform unqualified name lookup. 332 LookupName(Result, S); 333 334 // For unqualified lookup in a class template in MSVC mode, look into 335 // dependent base classes where the primary class template is known. 336 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 337 if (ParsedType TypeInBase = 338 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 339 return TypeInBase; 340 } 341 } 342 343 NamedDecl *IIDecl = nullptr; 344 switch (Result.getResultKind()) { 345 case LookupResult::NotFound: 346 case LookupResult::NotFoundInCurrentInstantiation: 347 if (CorrectedII) { 348 TypoCorrection Correction = 349 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 350 llvm::make_unique<TypeNameValidatorCCC>( 351 true, isClassName, AllowDeducedTemplate), 352 CTK_ErrorRecovery); 353 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 354 TemplateTy Template; 355 bool MemberOfUnknownSpecialization; 356 UnqualifiedId TemplateName; 357 TemplateName.setIdentifier(NewII, NameLoc); 358 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 359 CXXScopeSpec NewSS, *NewSSPtr = SS; 360 if (SS && NNS) { 361 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 362 NewSSPtr = &NewSS; 363 } 364 if (Correction && (NNS || NewII != &II) && 365 // Ignore a correction to a template type as the to-be-corrected 366 // identifier is not a template (typo correction for template names 367 // is handled elsewhere). 368 !(getLangOpts().CPlusPlus && NewSSPtr && 369 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 370 Template, MemberOfUnknownSpecialization))) { 371 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 372 isClassName, HasTrailingDot, ObjectTypePtr, 373 IsCtorOrDtorName, 374 WantNontrivialTypeSourceInfo, 375 IsClassTemplateDeductionContext); 376 if (Ty) { 377 diagnoseTypo(Correction, 378 PDiag(diag::err_unknown_type_or_class_name_suggest) 379 << Result.getLookupName() << isClassName); 380 if (SS && NNS) 381 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 382 *CorrectedII = NewII; 383 return Ty; 384 } 385 } 386 } 387 // If typo correction failed or was not performed, fall through 388 case LookupResult::FoundOverloaded: 389 case LookupResult::FoundUnresolvedValue: 390 Result.suppressDiagnostics(); 391 return nullptr; 392 393 case LookupResult::Ambiguous: 394 // Recover from type-hiding ambiguities by hiding the type. We'll 395 // do the lookup again when looking for an object, and we can 396 // diagnose the error then. If we don't do this, then the error 397 // about hiding the type will be immediately followed by an error 398 // that only makes sense if the identifier was treated like a type. 399 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 400 Result.suppressDiagnostics(); 401 return nullptr; 402 } 403 404 // Look to see if we have a type anywhere in the list of results. 405 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 406 Res != ResEnd; ++Res) { 407 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 408 (AllowDeducedTemplate && isTypeTemplate(*Res))) { 409 if (!IIDecl || 410 (*Res)->getLocation().getRawEncoding() < 411 IIDecl->getLocation().getRawEncoding()) 412 IIDecl = *Res; 413 } 414 } 415 416 if (!IIDecl) { 417 // None of the entities we found is a type, so there is no way 418 // to even assume that the result is a type. In this case, don't 419 // complain about the ambiguity. The parser will either try to 420 // perform this lookup again (e.g., as an object name), which 421 // will produce the ambiguity, or will complain that it expected 422 // a type name. 423 Result.suppressDiagnostics(); 424 return nullptr; 425 } 426 427 // We found a type within the ambiguous lookup; diagnose the 428 // ambiguity and then return that type. This might be the right 429 // answer, or it might not be, but it suppresses any attempt to 430 // perform the name lookup again. 431 break; 432 433 case LookupResult::Found: 434 IIDecl = Result.getFoundDecl(); 435 break; 436 } 437 438 assert(IIDecl && "Didn't find decl"); 439 440 QualType T; 441 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 442 // C++ [class.qual]p2: A lookup that would find the injected-class-name 443 // instead names the constructors of the class, except when naming a class. 444 // This is ill-formed when we're not actually forming a ctor or dtor name. 445 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 446 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 447 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 448 FoundRD->isInjectedClassName() && 449 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 450 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 451 << &II << /*Type*/1; 452 453 DiagnoseUseOfDecl(IIDecl, NameLoc); 454 455 T = Context.getTypeDeclType(TD); 456 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 457 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 458 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 459 if (!HasTrailingDot) 460 T = Context.getObjCInterfaceType(IDecl); 461 } else if (AllowDeducedTemplate && isTypeTemplate(IIDecl)) { 462 T = Context.getDeducedTemplateSpecializationType( 463 TemplateName(cast<TemplateDecl>(IIDecl)), QualType(), false); 464 } 465 466 if (T.isNull()) { 467 // If it's not plausibly a type, suppress diagnostics. 468 Result.suppressDiagnostics(); 469 return nullptr; 470 } 471 472 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 473 // constructor or destructor name (in such a case, the scope specifier 474 // will be attached to the enclosing Expr or Decl node). 475 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 476 !isa<ObjCInterfaceDecl>(IIDecl)) { 477 if (WantNontrivialTypeSourceInfo) { 478 // Construct a type with type-source information. 479 TypeLocBuilder Builder; 480 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 481 482 T = getElaboratedType(ETK_None, *SS, T); 483 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 484 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 485 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 486 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 487 } else { 488 T = getElaboratedType(ETK_None, *SS, T); 489 } 490 } 491 492 return ParsedType::make(T); 493 } 494 495 // Builds a fake NNS for the given decl context. 496 static NestedNameSpecifier * 497 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 498 for (;; DC = DC->getLookupParent()) { 499 DC = DC->getPrimaryContext(); 500 auto *ND = dyn_cast<NamespaceDecl>(DC); 501 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 502 return NestedNameSpecifier::Create(Context, nullptr, ND); 503 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 504 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 505 RD->getTypeForDecl()); 506 else if (isa<TranslationUnitDecl>(DC)) 507 return NestedNameSpecifier::GlobalSpecifier(Context); 508 } 509 llvm_unreachable("something isn't in TU scope?"); 510 } 511 512 /// Find the parent class with dependent bases of the innermost enclosing method 513 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 514 /// up allowing unqualified dependent type names at class-level, which MSVC 515 /// correctly rejects. 516 static const CXXRecordDecl * 517 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 518 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 519 DC = DC->getPrimaryContext(); 520 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 521 if (MD->getParent()->hasAnyDependentBases()) 522 return MD->getParent(); 523 } 524 return nullptr; 525 } 526 527 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 528 SourceLocation NameLoc, 529 bool IsTemplateTypeArg) { 530 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 531 532 NestedNameSpecifier *NNS = nullptr; 533 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 534 // If we weren't able to parse a default template argument, delay lookup 535 // until instantiation time by making a non-dependent DependentTypeName. We 536 // pretend we saw a NestedNameSpecifier referring to the current scope, and 537 // lookup is retried. 538 // FIXME: This hurts our diagnostic quality, since we get errors like "no 539 // type named 'Foo' in 'current_namespace'" when the user didn't write any 540 // name specifiers. 541 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 542 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 543 } else if (const CXXRecordDecl *RD = 544 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 545 // Build a DependentNameType that will perform lookup into RD at 546 // instantiation time. 547 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 548 RD->getTypeForDecl()); 549 550 // Diagnose that this identifier was undeclared, and retry the lookup during 551 // template instantiation. 552 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 553 << RD; 554 } else { 555 // This is not a situation that we should recover from. 556 return ParsedType(); 557 } 558 559 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 560 561 // Build type location information. We synthesized the qualifier, so we have 562 // to build a fake NestedNameSpecifierLoc. 563 NestedNameSpecifierLocBuilder NNSLocBuilder; 564 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 565 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 566 567 TypeLocBuilder Builder; 568 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 569 DepTL.setNameLoc(NameLoc); 570 DepTL.setElaboratedKeywordLoc(SourceLocation()); 571 DepTL.setQualifierLoc(QualifierLoc); 572 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 573 } 574 575 /// isTagName() - This method is called *for error recovery purposes only* 576 /// to determine if the specified name is a valid tag name ("struct foo"). If 577 /// so, this returns the TST for the tag corresponding to it (TST_enum, 578 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 579 /// cases in C where the user forgot to specify the tag. 580 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 581 // Do a tag name lookup in this scope. 582 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 583 LookupName(R, S, false); 584 R.suppressDiagnostics(); 585 if (R.getResultKind() == LookupResult::Found) 586 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 587 switch (TD->getTagKind()) { 588 case TTK_Struct: return DeclSpec::TST_struct; 589 case TTK_Interface: return DeclSpec::TST_interface; 590 case TTK_Union: return DeclSpec::TST_union; 591 case TTK_Class: return DeclSpec::TST_class; 592 case TTK_Enum: return DeclSpec::TST_enum; 593 } 594 } 595 596 return DeclSpec::TST_unspecified; 597 } 598 599 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 600 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 601 /// then downgrade the missing typename error to a warning. 602 /// This is needed for MSVC compatibility; Example: 603 /// @code 604 /// template<class T> class A { 605 /// public: 606 /// typedef int TYPE; 607 /// }; 608 /// template<class T> class B : public A<T> { 609 /// public: 610 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 611 /// }; 612 /// @endcode 613 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 614 if (CurContext->isRecord()) { 615 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 616 return true; 617 618 const Type *Ty = SS->getScopeRep()->getAsType(); 619 620 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 621 for (const auto &Base : RD->bases()) 622 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 623 return true; 624 return S->isFunctionPrototypeScope(); 625 } 626 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 627 } 628 629 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 630 SourceLocation IILoc, 631 Scope *S, 632 CXXScopeSpec *SS, 633 ParsedType &SuggestedType, 634 bool AllowClassTemplates) { 635 // We don't have anything to suggest (yet). 636 SuggestedType = nullptr; 637 638 // There may have been a typo in the name of the type. Look up typo 639 // results, in case we have something that we can suggest. 640 if (TypoCorrection Corrected = 641 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 642 llvm::make_unique<TypeNameValidatorCCC>( 643 false, false, AllowClassTemplates), 644 CTK_ErrorRecovery)) { 645 if (Corrected.isKeyword()) { 646 // We corrected to a keyword. 647 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 648 II = Corrected.getCorrectionAsIdentifierInfo(); 649 } else { 650 // We found a similarly-named type or interface; suggest that. 651 if (!SS || !SS->isSet()) { 652 diagnoseTypo(Corrected, 653 PDiag(diag::err_unknown_typename_suggest) << II); 654 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 655 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 656 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 657 II->getName().equals(CorrectedStr); 658 diagnoseTypo(Corrected, 659 PDiag(diag::err_unknown_nested_typename_suggest) 660 << II << DC << DroppedSpecifier << SS->getRange()); 661 } else { 662 llvm_unreachable("could not have corrected a typo here"); 663 } 664 665 CXXScopeSpec tmpSS; 666 if (Corrected.getCorrectionSpecifier()) 667 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 668 SourceRange(IILoc)); 669 // FIXME: Support class template argument deduction here. 670 SuggestedType = 671 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 672 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 673 /*IsCtorOrDtorName=*/false, 674 /*NonTrivialTypeSourceInfo=*/true); 675 } 676 return; 677 } 678 679 if (getLangOpts().CPlusPlus) { 680 // See if II is a class template that the user forgot to pass arguments to. 681 UnqualifiedId Name; 682 Name.setIdentifier(II, IILoc); 683 CXXScopeSpec EmptySS; 684 TemplateTy TemplateResult; 685 bool MemberOfUnknownSpecialization; 686 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 687 Name, nullptr, true, TemplateResult, 688 MemberOfUnknownSpecialization) == TNK_Type_template) { 689 TemplateName TplName = TemplateResult.get(); 690 Diag(IILoc, diag::err_template_missing_args) 691 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 692 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 693 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 694 << TplDecl->getTemplateParameters()->getSourceRange(); 695 } 696 return; 697 } 698 } 699 700 // FIXME: Should we move the logic that tries to recover from a missing tag 701 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 702 703 if (!SS || (!SS->isSet() && !SS->isInvalid())) 704 Diag(IILoc, diag::err_unknown_typename) << II; 705 else if (DeclContext *DC = computeDeclContext(*SS, false)) 706 Diag(IILoc, diag::err_typename_nested_not_found) 707 << II << DC << SS->getRange(); 708 else if (isDependentScopeSpecifier(*SS)) { 709 unsigned DiagID = diag::err_typename_missing; 710 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 711 DiagID = diag::ext_typename_missing; 712 713 Diag(SS->getRange().getBegin(), DiagID) 714 << SS->getScopeRep() << II->getName() 715 << SourceRange(SS->getRange().getBegin(), IILoc) 716 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 717 SuggestedType = ActOnTypenameType(S, SourceLocation(), 718 *SS, *II, IILoc).get(); 719 } else { 720 assert(SS && SS->isInvalid() && 721 "Invalid scope specifier has already been diagnosed"); 722 } 723 } 724 725 /// \brief Determine whether the given result set contains either a type name 726 /// or 727 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 728 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 729 NextToken.is(tok::less); 730 731 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 732 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 733 return true; 734 735 if (CheckTemplate && isa<TemplateDecl>(*I)) 736 return true; 737 } 738 739 return false; 740 } 741 742 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 743 Scope *S, CXXScopeSpec &SS, 744 IdentifierInfo *&Name, 745 SourceLocation NameLoc) { 746 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 747 SemaRef.LookupParsedName(R, S, &SS); 748 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 749 StringRef FixItTagName; 750 switch (Tag->getTagKind()) { 751 case TTK_Class: 752 FixItTagName = "class "; 753 break; 754 755 case TTK_Enum: 756 FixItTagName = "enum "; 757 break; 758 759 case TTK_Struct: 760 FixItTagName = "struct "; 761 break; 762 763 case TTK_Interface: 764 FixItTagName = "__interface "; 765 break; 766 767 case TTK_Union: 768 FixItTagName = "union "; 769 break; 770 } 771 772 StringRef TagName = FixItTagName.drop_back(); 773 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 774 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 775 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 776 777 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 778 I != IEnd; ++I) 779 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 780 << Name << TagName; 781 782 // Replace lookup results with just the tag decl. 783 Result.clear(Sema::LookupTagName); 784 SemaRef.LookupParsedName(Result, S, &SS); 785 return true; 786 } 787 788 return false; 789 } 790 791 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 792 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 793 QualType T, SourceLocation NameLoc) { 794 ASTContext &Context = S.Context; 795 796 TypeLocBuilder Builder; 797 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 798 799 T = S.getElaboratedType(ETK_None, SS, T); 800 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 801 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 802 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 803 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 804 } 805 806 Sema::NameClassification 807 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 808 SourceLocation NameLoc, const Token &NextToken, 809 bool IsAddressOfOperand, 810 std::unique_ptr<CorrectionCandidateCallback> CCC) { 811 DeclarationNameInfo NameInfo(Name, NameLoc); 812 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 813 814 if (NextToken.is(tok::coloncolon)) { 815 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 816 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 817 } else if (getLangOpts().CPlusPlus && SS.isSet() && 818 isCurrentClassName(*Name, S, &SS)) { 819 // Per [class.qual]p2, this names the constructors of SS, not the 820 // injected-class-name. We don't have a classification for that. 821 // There's not much point caching this result, since the parser 822 // will reject it later. 823 return NameClassification::Unknown(); 824 } 825 826 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 827 LookupParsedName(Result, S, &SS, !CurMethod); 828 829 // For unqualified lookup in a class template in MSVC mode, look into 830 // dependent base classes where the primary class template is known. 831 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 832 if (ParsedType TypeInBase = 833 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 834 return TypeInBase; 835 } 836 837 // Perform lookup for Objective-C instance variables (including automatically 838 // synthesized instance variables), if we're in an Objective-C method. 839 // FIXME: This lookup really, really needs to be folded in to the normal 840 // unqualified lookup mechanism. 841 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 842 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 843 if (E.get() || E.isInvalid()) 844 return E; 845 } 846 847 bool SecondTry = false; 848 bool IsFilteredTemplateName = false; 849 850 Corrected: 851 switch (Result.getResultKind()) { 852 case LookupResult::NotFound: 853 // If an unqualified-id is followed by a '(', then we have a function 854 // call. 855 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 856 // In C++, this is an ADL-only call. 857 // FIXME: Reference? 858 if (getLangOpts().CPlusPlus) 859 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 860 861 // C90 6.3.2.2: 862 // If the expression that precedes the parenthesized argument list in a 863 // function call consists solely of an identifier, and if no 864 // declaration is visible for this identifier, the identifier is 865 // implicitly declared exactly as if, in the innermost block containing 866 // the function call, the declaration 867 // 868 // extern int identifier (); 869 // 870 // appeared. 871 // 872 // We also allow this in C99 as an extension. 873 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 874 Result.addDecl(D); 875 Result.resolveKind(); 876 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 877 } 878 } 879 880 // In C, we first see whether there is a tag type by the same name, in 881 // which case it's likely that the user just forgot to write "enum", 882 // "struct", or "union". 883 if (!getLangOpts().CPlusPlus && !SecondTry && 884 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 885 break; 886 } 887 888 // Perform typo correction to determine if there is another name that is 889 // close to this name. 890 if (!SecondTry && CCC) { 891 SecondTry = true; 892 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 893 Result.getLookupKind(), S, 894 &SS, std::move(CCC), 895 CTK_ErrorRecovery)) { 896 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 897 unsigned QualifiedDiag = diag::err_no_member_suggest; 898 899 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 900 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 901 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 902 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 903 UnqualifiedDiag = diag::err_no_template_suggest; 904 QualifiedDiag = diag::err_no_member_template_suggest; 905 } else if (UnderlyingFirstDecl && 906 (isa<TypeDecl>(UnderlyingFirstDecl) || 907 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 908 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 909 UnqualifiedDiag = diag::err_unknown_typename_suggest; 910 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 911 } 912 913 if (SS.isEmpty()) { 914 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 915 } else {// FIXME: is this even reachable? Test it. 916 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 917 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 918 Name->getName().equals(CorrectedStr); 919 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 920 << Name << computeDeclContext(SS, false) 921 << DroppedSpecifier << SS.getRange()); 922 } 923 924 // Update the name, so that the caller has the new name. 925 Name = Corrected.getCorrectionAsIdentifierInfo(); 926 927 // Typo correction corrected to a keyword. 928 if (Corrected.isKeyword()) 929 return Name; 930 931 // Also update the LookupResult... 932 // FIXME: This should probably go away at some point 933 Result.clear(); 934 Result.setLookupName(Corrected.getCorrection()); 935 if (FirstDecl) 936 Result.addDecl(FirstDecl); 937 938 // If we found an Objective-C instance variable, let 939 // LookupInObjCMethod build the appropriate expression to 940 // reference the ivar. 941 // FIXME: This is a gross hack. 942 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 943 Result.clear(); 944 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 945 return E; 946 } 947 948 goto Corrected; 949 } 950 } 951 952 // We failed to correct; just fall through and let the parser deal with it. 953 Result.suppressDiagnostics(); 954 return NameClassification::Unknown(); 955 956 case LookupResult::NotFoundInCurrentInstantiation: { 957 // We performed name lookup into the current instantiation, and there were 958 // dependent bases, so we treat this result the same way as any other 959 // dependent nested-name-specifier. 960 961 // C++ [temp.res]p2: 962 // A name used in a template declaration or definition and that is 963 // dependent on a template-parameter is assumed not to name a type 964 // unless the applicable name lookup finds a type name or the name is 965 // qualified by the keyword typename. 966 // 967 // FIXME: If the next token is '<', we might want to ask the parser to 968 // perform some heroics to see if we actually have a 969 // template-argument-list, which would indicate a missing 'template' 970 // keyword here. 971 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 972 NameInfo, IsAddressOfOperand, 973 /*TemplateArgs=*/nullptr); 974 } 975 976 case LookupResult::Found: 977 case LookupResult::FoundOverloaded: 978 case LookupResult::FoundUnresolvedValue: 979 break; 980 981 case LookupResult::Ambiguous: 982 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 983 hasAnyAcceptableTemplateNames(Result)) { 984 // C++ [temp.local]p3: 985 // A lookup that finds an injected-class-name (10.2) can result in an 986 // ambiguity in certain cases (for example, if it is found in more than 987 // one base class). If all of the injected-class-names that are found 988 // refer to specializations of the same class template, and if the name 989 // is followed by a template-argument-list, the reference refers to the 990 // class template itself and not a specialization thereof, and is not 991 // ambiguous. 992 // 993 // This filtering can make an ambiguous result into an unambiguous one, 994 // so try again after filtering out template names. 995 FilterAcceptableTemplateNames(Result); 996 if (!Result.isAmbiguous()) { 997 IsFilteredTemplateName = true; 998 break; 999 } 1000 } 1001 1002 // Diagnose the ambiguity and return an error. 1003 return NameClassification::Error(); 1004 } 1005 1006 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1007 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1008 // C++ [temp.names]p3: 1009 // After name lookup (3.4) finds that a name is a template-name or that 1010 // an operator-function-id or a literal- operator-id refers to a set of 1011 // overloaded functions any member of which is a function template if 1012 // this is followed by a <, the < is always taken as the delimiter of a 1013 // template-argument-list and never as the less-than operator. 1014 if (!IsFilteredTemplateName) 1015 FilterAcceptableTemplateNames(Result); 1016 1017 if (!Result.empty()) { 1018 bool IsFunctionTemplate; 1019 bool IsVarTemplate; 1020 TemplateName Template; 1021 if (Result.end() - Result.begin() > 1) { 1022 IsFunctionTemplate = true; 1023 Template = Context.getOverloadedTemplateName(Result.begin(), 1024 Result.end()); 1025 } else { 1026 TemplateDecl *TD 1027 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1028 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1029 IsVarTemplate = isa<VarTemplateDecl>(TD); 1030 1031 if (SS.isSet() && !SS.isInvalid()) 1032 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1033 /*TemplateKeyword=*/false, 1034 TD); 1035 else 1036 Template = TemplateName(TD); 1037 } 1038 1039 if (IsFunctionTemplate) { 1040 // Function templates always go through overload resolution, at which 1041 // point we'll perform the various checks (e.g., accessibility) we need 1042 // to based on which function we selected. 1043 Result.suppressDiagnostics(); 1044 1045 return NameClassification::FunctionTemplate(Template); 1046 } 1047 1048 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1049 : NameClassification::TypeTemplate(Template); 1050 } 1051 } 1052 1053 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1054 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1055 DiagnoseUseOfDecl(Type, NameLoc); 1056 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1057 QualType T = Context.getTypeDeclType(Type); 1058 if (SS.isNotEmpty()) 1059 return buildNestedType(*this, SS, T, NameLoc); 1060 return ParsedType::make(T); 1061 } 1062 1063 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1064 if (!Class) { 1065 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1066 if (ObjCCompatibleAliasDecl *Alias = 1067 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1068 Class = Alias->getClassInterface(); 1069 } 1070 1071 if (Class) { 1072 DiagnoseUseOfDecl(Class, NameLoc); 1073 1074 if (NextToken.is(tok::period)) { 1075 // Interface. <something> is parsed as a property reference expression. 1076 // Just return "unknown" as a fall-through for now. 1077 Result.suppressDiagnostics(); 1078 return NameClassification::Unknown(); 1079 } 1080 1081 QualType T = Context.getObjCInterfaceType(Class); 1082 return ParsedType::make(T); 1083 } 1084 1085 // We can have a type template here if we're classifying a template argument. 1086 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1087 !isa<VarTemplateDecl>(FirstDecl)) 1088 return NameClassification::TypeTemplate( 1089 TemplateName(cast<TemplateDecl>(FirstDecl))); 1090 1091 // Check for a tag type hidden by a non-type decl in a few cases where it 1092 // seems likely a type is wanted instead of the non-type that was found. 1093 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1094 if ((NextToken.is(tok::identifier) || 1095 (NextIsOp && 1096 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1097 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1098 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1099 DiagnoseUseOfDecl(Type, NameLoc); 1100 QualType T = Context.getTypeDeclType(Type); 1101 if (SS.isNotEmpty()) 1102 return buildNestedType(*this, SS, T, NameLoc); 1103 return ParsedType::make(T); 1104 } 1105 1106 if (FirstDecl->isCXXClassMember()) 1107 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1108 nullptr, S); 1109 1110 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1111 return BuildDeclarationNameExpr(SS, Result, ADL); 1112 } 1113 1114 Sema::TemplateNameKindForDiagnostics 1115 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1116 auto *TD = Name.getAsTemplateDecl(); 1117 if (!TD) 1118 return TemplateNameKindForDiagnostics::DependentTemplate; 1119 if (isa<ClassTemplateDecl>(TD)) 1120 return TemplateNameKindForDiagnostics::ClassTemplate; 1121 if (isa<FunctionTemplateDecl>(TD)) 1122 return TemplateNameKindForDiagnostics::FunctionTemplate; 1123 if (isa<VarTemplateDecl>(TD)) 1124 return TemplateNameKindForDiagnostics::VarTemplate; 1125 if (isa<TypeAliasTemplateDecl>(TD)) 1126 return TemplateNameKindForDiagnostics::AliasTemplate; 1127 if (isa<TemplateTemplateParmDecl>(TD)) 1128 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1129 return TemplateNameKindForDiagnostics::DependentTemplate; 1130 } 1131 1132 // Determines the context to return to after temporarily entering a 1133 // context. This depends in an unnecessarily complicated way on the 1134 // exact ordering of callbacks from the parser. 1135 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1136 1137 // Functions defined inline within classes aren't parsed until we've 1138 // finished parsing the top-level class, so the top-level class is 1139 // the context we'll need to return to. 1140 // A Lambda call operator whose parent is a class must not be treated 1141 // as an inline member function. A Lambda can be used legally 1142 // either as an in-class member initializer or a default argument. These 1143 // are parsed once the class has been marked complete and so the containing 1144 // context would be the nested class (when the lambda is defined in one); 1145 // If the class is not complete, then the lambda is being used in an 1146 // ill-formed fashion (such as to specify the width of a bit-field, or 1147 // in an array-bound) - in which case we still want to return the 1148 // lexically containing DC (which could be a nested class). 1149 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1150 DC = DC->getLexicalParent(); 1151 1152 // A function not defined within a class will always return to its 1153 // lexical context. 1154 if (!isa<CXXRecordDecl>(DC)) 1155 return DC; 1156 1157 // A C++ inline method/friend is parsed *after* the topmost class 1158 // it was declared in is fully parsed ("complete"); the topmost 1159 // class is the context we need to return to. 1160 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1161 DC = RD; 1162 1163 // Return the declaration context of the topmost class the inline method is 1164 // declared in. 1165 return DC; 1166 } 1167 1168 return DC->getLexicalParent(); 1169 } 1170 1171 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1172 assert(getContainingDC(DC) == CurContext && 1173 "The next DeclContext should be lexically contained in the current one."); 1174 CurContext = DC; 1175 S->setEntity(DC); 1176 } 1177 1178 void Sema::PopDeclContext() { 1179 assert(CurContext && "DeclContext imbalance!"); 1180 1181 CurContext = getContainingDC(CurContext); 1182 assert(CurContext && "Popped translation unit!"); 1183 } 1184 1185 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1186 Decl *D) { 1187 // Unlike PushDeclContext, the context to which we return is not necessarily 1188 // the containing DC of TD, because the new context will be some pre-existing 1189 // TagDecl definition instead of a fresh one. 1190 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1191 CurContext = cast<TagDecl>(D)->getDefinition(); 1192 assert(CurContext && "skipping definition of undefined tag"); 1193 // Start lookups from the parent of the current context; we don't want to look 1194 // into the pre-existing complete definition. 1195 S->setEntity(CurContext->getLookupParent()); 1196 return Result; 1197 } 1198 1199 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1200 CurContext = static_cast<decltype(CurContext)>(Context); 1201 } 1202 1203 /// EnterDeclaratorContext - Used when we must lookup names in the context 1204 /// of a declarator's nested name specifier. 1205 /// 1206 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1207 // C++0x [basic.lookup.unqual]p13: 1208 // A name used in the definition of a static data member of class 1209 // X (after the qualified-id of the static member) is looked up as 1210 // if the name was used in a member function of X. 1211 // C++0x [basic.lookup.unqual]p14: 1212 // If a variable member of a namespace is defined outside of the 1213 // scope of its namespace then any name used in the definition of 1214 // the variable member (after the declarator-id) is looked up as 1215 // if the definition of the variable member occurred in its 1216 // namespace. 1217 // Both of these imply that we should push a scope whose context 1218 // is the semantic context of the declaration. We can't use 1219 // PushDeclContext here because that context is not necessarily 1220 // lexically contained in the current context. Fortunately, 1221 // the containing scope should have the appropriate information. 1222 1223 assert(!S->getEntity() && "scope already has entity"); 1224 1225 #ifndef NDEBUG 1226 Scope *Ancestor = S->getParent(); 1227 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1228 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1229 #endif 1230 1231 CurContext = DC; 1232 S->setEntity(DC); 1233 } 1234 1235 void Sema::ExitDeclaratorContext(Scope *S) { 1236 assert(S->getEntity() == CurContext && "Context imbalance!"); 1237 1238 // Switch back to the lexical context. The safety of this is 1239 // enforced by an assert in EnterDeclaratorContext. 1240 Scope *Ancestor = S->getParent(); 1241 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1242 CurContext = Ancestor->getEntity(); 1243 1244 // We don't need to do anything with the scope, which is going to 1245 // disappear. 1246 } 1247 1248 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1249 // We assume that the caller has already called 1250 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1251 FunctionDecl *FD = D->getAsFunction(); 1252 if (!FD) 1253 return; 1254 1255 // Same implementation as PushDeclContext, but enters the context 1256 // from the lexical parent, rather than the top-level class. 1257 assert(CurContext == FD->getLexicalParent() && 1258 "The next DeclContext should be lexically contained in the current one."); 1259 CurContext = FD; 1260 S->setEntity(CurContext); 1261 1262 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1263 ParmVarDecl *Param = FD->getParamDecl(P); 1264 // If the parameter has an identifier, then add it to the scope 1265 if (Param->getIdentifier()) { 1266 S->AddDecl(Param); 1267 IdResolver.AddDecl(Param); 1268 } 1269 } 1270 } 1271 1272 void Sema::ActOnExitFunctionContext() { 1273 // Same implementation as PopDeclContext, but returns to the lexical parent, 1274 // rather than the top-level class. 1275 assert(CurContext && "DeclContext imbalance!"); 1276 CurContext = CurContext->getLexicalParent(); 1277 assert(CurContext && "Popped translation unit!"); 1278 } 1279 1280 /// \brief Determine whether we allow overloading of the function 1281 /// PrevDecl with another declaration. 1282 /// 1283 /// This routine determines whether overloading is possible, not 1284 /// whether some new function is actually an overload. It will return 1285 /// true in C++ (where we can always provide overloads) or, as an 1286 /// extension, in C when the previous function is already an 1287 /// overloaded function declaration or has the "overloadable" 1288 /// attribute. 1289 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1290 ASTContext &Context) { 1291 if (Context.getLangOpts().CPlusPlus) 1292 return true; 1293 1294 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1295 return true; 1296 1297 return (Previous.getResultKind() == LookupResult::Found 1298 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1299 } 1300 1301 /// Add this decl to the scope shadowed decl chains. 1302 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1303 // Move up the scope chain until we find the nearest enclosing 1304 // non-transparent context. The declaration will be introduced into this 1305 // scope. 1306 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1307 S = S->getParent(); 1308 1309 // Add scoped declarations into their context, so that they can be 1310 // found later. Declarations without a context won't be inserted 1311 // into any context. 1312 if (AddToContext) 1313 CurContext->addDecl(D); 1314 1315 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1316 // are function-local declarations. 1317 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1318 !D->getDeclContext()->getRedeclContext()->Equals( 1319 D->getLexicalDeclContext()->getRedeclContext()) && 1320 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1321 return; 1322 1323 // Template instantiations should also not be pushed into scope. 1324 if (isa<FunctionDecl>(D) && 1325 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1326 return; 1327 1328 // If this replaces anything in the current scope, 1329 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1330 IEnd = IdResolver.end(); 1331 for (; I != IEnd; ++I) { 1332 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1333 S->RemoveDecl(*I); 1334 IdResolver.RemoveDecl(*I); 1335 1336 // Should only need to replace one decl. 1337 break; 1338 } 1339 } 1340 1341 S->AddDecl(D); 1342 1343 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1344 // Implicitly-generated labels may end up getting generated in an order that 1345 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1346 // the label at the appropriate place in the identifier chain. 1347 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1348 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1349 if (IDC == CurContext) { 1350 if (!S->isDeclScope(*I)) 1351 continue; 1352 } else if (IDC->Encloses(CurContext)) 1353 break; 1354 } 1355 1356 IdResolver.InsertDeclAfter(I, D); 1357 } else { 1358 IdResolver.AddDecl(D); 1359 } 1360 } 1361 1362 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1363 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1364 TUScope->AddDecl(D); 1365 } 1366 1367 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1368 bool AllowInlineNamespace) { 1369 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1370 } 1371 1372 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1373 DeclContext *TargetDC = DC->getPrimaryContext(); 1374 do { 1375 if (DeclContext *ScopeDC = S->getEntity()) 1376 if (ScopeDC->getPrimaryContext() == TargetDC) 1377 return S; 1378 } while ((S = S->getParent())); 1379 1380 return nullptr; 1381 } 1382 1383 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1384 DeclContext*, 1385 ASTContext&); 1386 1387 /// Filters out lookup results that don't fall within the given scope 1388 /// as determined by isDeclInScope. 1389 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1390 bool ConsiderLinkage, 1391 bool AllowInlineNamespace) { 1392 LookupResult::Filter F = R.makeFilter(); 1393 while (F.hasNext()) { 1394 NamedDecl *D = F.next(); 1395 1396 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1397 continue; 1398 1399 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1400 continue; 1401 1402 F.erase(); 1403 } 1404 1405 F.done(); 1406 } 1407 1408 static bool isUsingDecl(NamedDecl *D) { 1409 return isa<UsingShadowDecl>(D) || 1410 isa<UnresolvedUsingTypenameDecl>(D) || 1411 isa<UnresolvedUsingValueDecl>(D); 1412 } 1413 1414 /// Removes using shadow declarations from the lookup results. 1415 static void RemoveUsingDecls(LookupResult &R) { 1416 LookupResult::Filter F = R.makeFilter(); 1417 while (F.hasNext()) 1418 if (isUsingDecl(F.next())) 1419 F.erase(); 1420 1421 F.done(); 1422 } 1423 1424 /// \brief Check for this common pattern: 1425 /// @code 1426 /// class S { 1427 /// S(const S&); // DO NOT IMPLEMENT 1428 /// void operator=(const S&); // DO NOT IMPLEMENT 1429 /// }; 1430 /// @endcode 1431 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1432 // FIXME: Should check for private access too but access is set after we get 1433 // the decl here. 1434 if (D->doesThisDeclarationHaveABody()) 1435 return false; 1436 1437 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1438 return CD->isCopyConstructor(); 1439 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1440 return Method->isCopyAssignmentOperator(); 1441 return false; 1442 } 1443 1444 // We need this to handle 1445 // 1446 // typedef struct { 1447 // void *foo() { return 0; } 1448 // } A; 1449 // 1450 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1451 // for example. If 'A', foo will have external linkage. If we have '*A', 1452 // foo will have no linkage. Since we can't know until we get to the end 1453 // of the typedef, this function finds out if D might have non-external linkage. 1454 // Callers should verify at the end of the TU if it D has external linkage or 1455 // not. 1456 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1457 const DeclContext *DC = D->getDeclContext(); 1458 while (!DC->isTranslationUnit()) { 1459 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1460 if (!RD->hasNameForLinkage()) 1461 return true; 1462 } 1463 DC = DC->getParent(); 1464 } 1465 1466 return !D->isExternallyVisible(); 1467 } 1468 1469 // FIXME: This needs to be refactored; some other isInMainFile users want 1470 // these semantics. 1471 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1472 if (S.TUKind != TU_Complete) 1473 return false; 1474 return S.SourceMgr.isInMainFile(Loc); 1475 } 1476 1477 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1478 assert(D); 1479 1480 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1481 return false; 1482 1483 // Ignore all entities declared within templates, and out-of-line definitions 1484 // of members of class templates. 1485 if (D->getDeclContext()->isDependentContext() || 1486 D->getLexicalDeclContext()->isDependentContext()) 1487 return false; 1488 1489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1490 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1491 return false; 1492 1493 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1494 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1495 return false; 1496 } else { 1497 // 'static inline' functions are defined in headers; don't warn. 1498 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1499 return false; 1500 } 1501 1502 if (FD->doesThisDeclarationHaveABody() && 1503 Context.DeclMustBeEmitted(FD)) 1504 return false; 1505 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1506 // Constants and utility variables are defined in headers with internal 1507 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1508 // like "inline".) 1509 if (!isMainFileLoc(*this, VD->getLocation())) 1510 return false; 1511 1512 if (Context.DeclMustBeEmitted(VD)) 1513 return false; 1514 1515 if (VD->isStaticDataMember() && 1516 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1517 return false; 1518 1519 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1520 return false; 1521 } else { 1522 return false; 1523 } 1524 1525 // Only warn for unused decls internal to the translation unit. 1526 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1527 // for inline functions defined in the main source file, for instance. 1528 return mightHaveNonExternalLinkage(D); 1529 } 1530 1531 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1532 if (!D) 1533 return; 1534 1535 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1536 const FunctionDecl *First = FD->getFirstDecl(); 1537 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1538 return; // First should already be in the vector. 1539 } 1540 1541 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1542 const VarDecl *First = VD->getFirstDecl(); 1543 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1544 return; // First should already be in the vector. 1545 } 1546 1547 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1548 UnusedFileScopedDecls.push_back(D); 1549 } 1550 1551 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1552 if (D->isInvalidDecl()) 1553 return false; 1554 1555 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1556 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1557 return false; 1558 1559 if (isa<LabelDecl>(D)) 1560 return true; 1561 1562 // Except for labels, we only care about unused decls that are local to 1563 // functions. 1564 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1565 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1566 // For dependent types, the diagnostic is deferred. 1567 WithinFunction = 1568 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1569 if (!WithinFunction) 1570 return false; 1571 1572 if (isa<TypedefNameDecl>(D)) 1573 return true; 1574 1575 // White-list anything that isn't a local variable. 1576 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1577 return false; 1578 1579 // Types of valid local variables should be complete, so this should succeed. 1580 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1581 1582 // White-list anything with an __attribute__((unused)) type. 1583 const auto *Ty = VD->getType().getTypePtr(); 1584 1585 // Only look at the outermost level of typedef. 1586 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1587 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1588 return false; 1589 } 1590 1591 // If we failed to complete the type for some reason, or if the type is 1592 // dependent, don't diagnose the variable. 1593 if (Ty->isIncompleteType() || Ty->isDependentType()) 1594 return false; 1595 1596 // Look at the element type to ensure that the warning behaviour is 1597 // consistent for both scalars and arrays. 1598 Ty = Ty->getBaseElementTypeUnsafe(); 1599 1600 if (const TagType *TT = Ty->getAs<TagType>()) { 1601 const TagDecl *Tag = TT->getDecl(); 1602 if (Tag->hasAttr<UnusedAttr>()) 1603 return false; 1604 1605 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1606 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1607 return false; 1608 1609 if (const Expr *Init = VD->getInit()) { 1610 if (const ExprWithCleanups *Cleanups = 1611 dyn_cast<ExprWithCleanups>(Init)) 1612 Init = Cleanups->getSubExpr(); 1613 const CXXConstructExpr *Construct = 1614 dyn_cast<CXXConstructExpr>(Init); 1615 if (Construct && !Construct->isElidable()) { 1616 CXXConstructorDecl *CD = Construct->getConstructor(); 1617 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1618 return false; 1619 } 1620 } 1621 } 1622 } 1623 1624 // TODO: __attribute__((unused)) templates? 1625 } 1626 1627 return true; 1628 } 1629 1630 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1631 FixItHint &Hint) { 1632 if (isa<LabelDecl>(D)) { 1633 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1634 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1635 if (AfterColon.isInvalid()) 1636 return; 1637 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1638 getCharRange(D->getLocStart(), AfterColon)); 1639 } 1640 } 1641 1642 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1643 if (D->getTypeForDecl()->isDependentType()) 1644 return; 1645 1646 for (auto *TmpD : D->decls()) { 1647 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1648 DiagnoseUnusedDecl(T); 1649 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1650 DiagnoseUnusedNestedTypedefs(R); 1651 } 1652 } 1653 1654 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1655 /// unless they are marked attr(unused). 1656 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1657 if (!ShouldDiagnoseUnusedDecl(D)) 1658 return; 1659 1660 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1661 // typedefs can be referenced later on, so the diagnostics are emitted 1662 // at end-of-translation-unit. 1663 UnusedLocalTypedefNameCandidates.insert(TD); 1664 return; 1665 } 1666 1667 FixItHint Hint; 1668 GenerateFixForUnusedDecl(D, Context, Hint); 1669 1670 unsigned DiagID; 1671 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1672 DiagID = diag::warn_unused_exception_param; 1673 else if (isa<LabelDecl>(D)) 1674 DiagID = diag::warn_unused_label; 1675 else 1676 DiagID = diag::warn_unused_variable; 1677 1678 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1679 } 1680 1681 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1682 // Verify that we have no forward references left. If so, there was a goto 1683 // or address of a label taken, but no definition of it. Label fwd 1684 // definitions are indicated with a null substmt which is also not a resolved 1685 // MS inline assembly label name. 1686 bool Diagnose = false; 1687 if (L->isMSAsmLabel()) 1688 Diagnose = !L->isResolvedMSAsmLabel(); 1689 else 1690 Diagnose = L->getStmt() == nullptr; 1691 if (Diagnose) 1692 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1693 } 1694 1695 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1696 S->mergeNRVOIntoParent(); 1697 1698 if (S->decl_empty()) return; 1699 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1700 "Scope shouldn't contain decls!"); 1701 1702 for (auto *TmpD : S->decls()) { 1703 assert(TmpD && "This decl didn't get pushed??"); 1704 1705 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1706 NamedDecl *D = cast<NamedDecl>(TmpD); 1707 1708 if (!D->getDeclName()) continue; 1709 1710 // Diagnose unused variables in this scope. 1711 if (!S->hasUnrecoverableErrorOccurred()) { 1712 DiagnoseUnusedDecl(D); 1713 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1714 DiagnoseUnusedNestedTypedefs(RD); 1715 } 1716 1717 // If this was a forward reference to a label, verify it was defined. 1718 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1719 CheckPoppedLabel(LD, *this); 1720 1721 // Remove this name from our lexical scope, and warn on it if we haven't 1722 // already. 1723 IdResolver.RemoveDecl(D); 1724 auto ShadowI = ShadowingDecls.find(D); 1725 if (ShadowI != ShadowingDecls.end()) { 1726 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1727 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1728 << D << FD << FD->getParent(); 1729 Diag(FD->getLocation(), diag::note_previous_declaration); 1730 } 1731 ShadowingDecls.erase(ShadowI); 1732 } 1733 } 1734 } 1735 1736 /// \brief Look for an Objective-C class in the translation unit. 1737 /// 1738 /// \param Id The name of the Objective-C class we're looking for. If 1739 /// typo-correction fixes this name, the Id will be updated 1740 /// to the fixed name. 1741 /// 1742 /// \param IdLoc The location of the name in the translation unit. 1743 /// 1744 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1745 /// if there is no class with the given name. 1746 /// 1747 /// \returns The declaration of the named Objective-C class, or NULL if the 1748 /// class could not be found. 1749 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1750 SourceLocation IdLoc, 1751 bool DoTypoCorrection) { 1752 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1753 // creation from this context. 1754 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1755 1756 if (!IDecl && DoTypoCorrection) { 1757 // Perform typo correction at the given location, but only if we 1758 // find an Objective-C class name. 1759 if (TypoCorrection C = CorrectTypo( 1760 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1761 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1762 CTK_ErrorRecovery)) { 1763 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1764 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1765 Id = IDecl->getIdentifier(); 1766 } 1767 } 1768 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1769 // This routine must always return a class definition, if any. 1770 if (Def && Def->getDefinition()) 1771 Def = Def->getDefinition(); 1772 return Def; 1773 } 1774 1775 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1776 /// from S, where a non-field would be declared. This routine copes 1777 /// with the difference between C and C++ scoping rules in structs and 1778 /// unions. For example, the following code is well-formed in C but 1779 /// ill-formed in C++: 1780 /// @code 1781 /// struct S6 { 1782 /// enum { BAR } e; 1783 /// }; 1784 /// 1785 /// void test_S6() { 1786 /// struct S6 a; 1787 /// a.e = BAR; 1788 /// } 1789 /// @endcode 1790 /// For the declaration of BAR, this routine will return a different 1791 /// scope. The scope S will be the scope of the unnamed enumeration 1792 /// within S6. In C++, this routine will return the scope associated 1793 /// with S6, because the enumeration's scope is a transparent 1794 /// context but structures can contain non-field names. In C, this 1795 /// routine will return the translation unit scope, since the 1796 /// enumeration's scope is a transparent context and structures cannot 1797 /// contain non-field names. 1798 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1799 while (((S->getFlags() & Scope::DeclScope) == 0) || 1800 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1801 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1802 S = S->getParent(); 1803 return S; 1804 } 1805 1806 /// \brief Looks up the declaration of "struct objc_super" and 1807 /// saves it for later use in building builtin declaration of 1808 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1809 /// pre-existing declaration exists no action takes place. 1810 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1811 IdentifierInfo *II) { 1812 if (!II->isStr("objc_msgSendSuper")) 1813 return; 1814 ASTContext &Context = ThisSema.Context; 1815 1816 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1817 SourceLocation(), Sema::LookupTagName); 1818 ThisSema.LookupName(Result, S); 1819 if (Result.getResultKind() == LookupResult::Found) 1820 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1821 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1822 } 1823 1824 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1825 switch (Error) { 1826 case ASTContext::GE_None: 1827 return ""; 1828 case ASTContext::GE_Missing_stdio: 1829 return "stdio.h"; 1830 case ASTContext::GE_Missing_setjmp: 1831 return "setjmp.h"; 1832 case ASTContext::GE_Missing_ucontext: 1833 return "ucontext.h"; 1834 } 1835 llvm_unreachable("unhandled error kind"); 1836 } 1837 1838 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1839 /// file scope. lazily create a decl for it. ForRedeclaration is true 1840 /// if we're creating this built-in in anticipation of redeclaring the 1841 /// built-in. 1842 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1843 Scope *S, bool ForRedeclaration, 1844 SourceLocation Loc) { 1845 LookupPredefedObjCSuperType(*this, S, II); 1846 1847 ASTContext::GetBuiltinTypeError Error; 1848 QualType R = Context.GetBuiltinType(ID, Error); 1849 if (Error) { 1850 if (ForRedeclaration) 1851 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1852 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1853 return nullptr; 1854 } 1855 1856 if (!ForRedeclaration && 1857 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1858 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1859 Diag(Loc, diag::ext_implicit_lib_function_decl) 1860 << Context.BuiltinInfo.getName(ID) << R; 1861 if (Context.BuiltinInfo.getHeaderName(ID) && 1862 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1863 Diag(Loc, diag::note_include_header_or_declare) 1864 << Context.BuiltinInfo.getHeaderName(ID) 1865 << Context.BuiltinInfo.getName(ID); 1866 } 1867 1868 if (R.isNull()) 1869 return nullptr; 1870 1871 DeclContext *Parent = Context.getTranslationUnitDecl(); 1872 if (getLangOpts().CPlusPlus) { 1873 LinkageSpecDecl *CLinkageDecl = 1874 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1875 LinkageSpecDecl::lang_c, false); 1876 CLinkageDecl->setImplicit(); 1877 Parent->addDecl(CLinkageDecl); 1878 Parent = CLinkageDecl; 1879 } 1880 1881 FunctionDecl *New = FunctionDecl::Create(Context, 1882 Parent, 1883 Loc, Loc, II, R, /*TInfo=*/nullptr, 1884 SC_Extern, 1885 false, 1886 R->isFunctionProtoType()); 1887 New->setImplicit(); 1888 1889 // Create Decl objects for each parameter, adding them to the 1890 // FunctionDecl. 1891 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1892 SmallVector<ParmVarDecl*, 16> Params; 1893 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1894 ParmVarDecl *parm = 1895 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1896 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1897 SC_None, nullptr); 1898 parm->setScopeInfo(0, i); 1899 Params.push_back(parm); 1900 } 1901 New->setParams(Params); 1902 } 1903 1904 AddKnownFunctionAttributes(New); 1905 RegisterLocallyScopedExternCDecl(New, S); 1906 1907 // TUScope is the translation-unit scope to insert this function into. 1908 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1909 // relate Scopes to DeclContexts, and probably eliminate CurContext 1910 // entirely, but we're not there yet. 1911 DeclContext *SavedContext = CurContext; 1912 CurContext = Parent; 1913 PushOnScopeChains(New, TUScope); 1914 CurContext = SavedContext; 1915 return New; 1916 } 1917 1918 /// Typedef declarations don't have linkage, but they still denote the same 1919 /// entity if their types are the same. 1920 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1921 /// isSameEntity. 1922 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1923 TypedefNameDecl *Decl, 1924 LookupResult &Previous) { 1925 // This is only interesting when modules are enabled. 1926 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1927 return; 1928 1929 // Empty sets are uninteresting. 1930 if (Previous.empty()) 1931 return; 1932 1933 LookupResult::Filter Filter = Previous.makeFilter(); 1934 while (Filter.hasNext()) { 1935 NamedDecl *Old = Filter.next(); 1936 1937 // Non-hidden declarations are never ignored. 1938 if (S.isVisible(Old)) 1939 continue; 1940 1941 // Declarations of the same entity are not ignored, even if they have 1942 // different linkages. 1943 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1944 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1945 Decl->getUnderlyingType())) 1946 continue; 1947 1948 // If both declarations give a tag declaration a typedef name for linkage 1949 // purposes, then they declare the same entity. 1950 if (S.getLangOpts().CPlusPlus && 1951 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1952 Decl->getAnonDeclWithTypedefName()) 1953 continue; 1954 } 1955 1956 Filter.erase(); 1957 } 1958 1959 Filter.done(); 1960 } 1961 1962 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1963 QualType OldType; 1964 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1965 OldType = OldTypedef->getUnderlyingType(); 1966 else 1967 OldType = Context.getTypeDeclType(Old); 1968 QualType NewType = New->getUnderlyingType(); 1969 1970 if (NewType->isVariablyModifiedType()) { 1971 // Must not redefine a typedef with a variably-modified type. 1972 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1973 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1974 << Kind << NewType; 1975 if (Old->getLocation().isValid()) 1976 Diag(Old->getLocation(), diag::note_previous_definition); 1977 New->setInvalidDecl(); 1978 return true; 1979 } 1980 1981 if (OldType != NewType && 1982 !OldType->isDependentType() && 1983 !NewType->isDependentType() && 1984 !Context.hasSameType(OldType, NewType)) { 1985 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1986 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1987 << Kind << NewType << OldType; 1988 if (Old->getLocation().isValid()) 1989 Diag(Old->getLocation(), diag::note_previous_definition); 1990 New->setInvalidDecl(); 1991 return true; 1992 } 1993 return false; 1994 } 1995 1996 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1997 /// same name and scope as a previous declaration 'Old'. Figure out 1998 /// how to resolve this situation, merging decls or emitting 1999 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2000 /// 2001 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2002 LookupResult &OldDecls) { 2003 // If the new decl is known invalid already, don't bother doing any 2004 // merging checks. 2005 if (New->isInvalidDecl()) return; 2006 2007 // Allow multiple definitions for ObjC built-in typedefs. 2008 // FIXME: Verify the underlying types are equivalent! 2009 if (getLangOpts().ObjC1) { 2010 const IdentifierInfo *TypeID = New->getIdentifier(); 2011 switch (TypeID->getLength()) { 2012 default: break; 2013 case 2: 2014 { 2015 if (!TypeID->isStr("id")) 2016 break; 2017 QualType T = New->getUnderlyingType(); 2018 if (!T->isPointerType()) 2019 break; 2020 if (!T->isVoidPointerType()) { 2021 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2022 if (!PT->isStructureType()) 2023 break; 2024 } 2025 Context.setObjCIdRedefinitionType(T); 2026 // Install the built-in type for 'id', ignoring the current definition. 2027 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2028 return; 2029 } 2030 case 5: 2031 if (!TypeID->isStr("Class")) 2032 break; 2033 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2034 // Install the built-in type for 'Class', ignoring the current definition. 2035 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2036 return; 2037 case 3: 2038 if (!TypeID->isStr("SEL")) 2039 break; 2040 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2041 // Install the built-in type for 'SEL', ignoring the current definition. 2042 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2043 return; 2044 } 2045 // Fall through - the typedef name was not a builtin type. 2046 } 2047 2048 // Verify the old decl was also a type. 2049 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2050 if (!Old) { 2051 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2052 << New->getDeclName(); 2053 2054 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2055 if (OldD->getLocation().isValid()) 2056 Diag(OldD->getLocation(), diag::note_previous_definition); 2057 2058 return New->setInvalidDecl(); 2059 } 2060 2061 // If the old declaration is invalid, just give up here. 2062 if (Old->isInvalidDecl()) 2063 return New->setInvalidDecl(); 2064 2065 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2066 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2067 auto *NewTag = New->getAnonDeclWithTypedefName(); 2068 NamedDecl *Hidden = nullptr; 2069 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2070 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2071 !hasVisibleDefinition(OldTag, &Hidden)) { 2072 // There is a definition of this tag, but it is not visible. Use it 2073 // instead of our tag. 2074 New->setTypeForDecl(OldTD->getTypeForDecl()); 2075 if (OldTD->isModed()) 2076 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2077 OldTD->getUnderlyingType()); 2078 else 2079 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2080 2081 // Make the old tag definition visible. 2082 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2083 2084 // If this was an unscoped enumeration, yank all of its enumerators 2085 // out of the scope. 2086 if (isa<EnumDecl>(NewTag)) { 2087 Scope *EnumScope = getNonFieldDeclScope(S); 2088 for (auto *D : NewTag->decls()) { 2089 auto *ED = cast<EnumConstantDecl>(D); 2090 assert(EnumScope->isDeclScope(ED)); 2091 EnumScope->RemoveDecl(ED); 2092 IdResolver.RemoveDecl(ED); 2093 ED->getLexicalDeclContext()->removeDecl(ED); 2094 } 2095 } 2096 } 2097 } 2098 2099 // If the typedef types are not identical, reject them in all languages and 2100 // with any extensions enabled. 2101 if (isIncompatibleTypedef(Old, New)) 2102 return; 2103 2104 // The types match. Link up the redeclaration chain and merge attributes if 2105 // the old declaration was a typedef. 2106 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2107 New->setPreviousDecl(Typedef); 2108 mergeDeclAttributes(New, Old); 2109 } 2110 2111 if (getLangOpts().MicrosoftExt) 2112 return; 2113 2114 if (getLangOpts().CPlusPlus) { 2115 // C++ [dcl.typedef]p2: 2116 // In a given non-class scope, a typedef specifier can be used to 2117 // redefine the name of any type declared in that scope to refer 2118 // to the type to which it already refers. 2119 if (!isa<CXXRecordDecl>(CurContext)) 2120 return; 2121 2122 // C++0x [dcl.typedef]p4: 2123 // In a given class scope, a typedef specifier can be used to redefine 2124 // any class-name declared in that scope that is not also a typedef-name 2125 // to refer to the type to which it already refers. 2126 // 2127 // This wording came in via DR424, which was a correction to the 2128 // wording in DR56, which accidentally banned code like: 2129 // 2130 // struct S { 2131 // typedef struct A { } A; 2132 // }; 2133 // 2134 // in the C++03 standard. We implement the C++0x semantics, which 2135 // allow the above but disallow 2136 // 2137 // struct S { 2138 // typedef int I; 2139 // typedef int I; 2140 // }; 2141 // 2142 // since that was the intent of DR56. 2143 if (!isa<TypedefNameDecl>(Old)) 2144 return; 2145 2146 Diag(New->getLocation(), diag::err_redefinition) 2147 << New->getDeclName(); 2148 Diag(Old->getLocation(), diag::note_previous_definition); 2149 return New->setInvalidDecl(); 2150 } 2151 2152 // Modules always permit redefinition of typedefs, as does C11. 2153 if (getLangOpts().Modules || getLangOpts().C11) 2154 return; 2155 2156 // If we have a redefinition of a typedef in C, emit a warning. This warning 2157 // is normally mapped to an error, but can be controlled with 2158 // -Wtypedef-redefinition. If either the original or the redefinition is 2159 // in a system header, don't emit this for compatibility with GCC. 2160 if (getDiagnostics().getSuppressSystemWarnings() && 2161 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2162 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2163 return; 2164 2165 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2166 << New->getDeclName(); 2167 Diag(Old->getLocation(), diag::note_previous_definition); 2168 } 2169 2170 /// DeclhasAttr - returns true if decl Declaration already has the target 2171 /// attribute. 2172 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2173 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2174 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2175 for (const auto *i : D->attrs()) 2176 if (i->getKind() == A->getKind()) { 2177 if (Ann) { 2178 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2179 return true; 2180 continue; 2181 } 2182 // FIXME: Don't hardcode this check 2183 if (OA && isa<OwnershipAttr>(i)) 2184 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2185 return true; 2186 } 2187 2188 return false; 2189 } 2190 2191 static bool isAttributeTargetADefinition(Decl *D) { 2192 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2193 return VD->isThisDeclarationADefinition(); 2194 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2195 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2196 return true; 2197 } 2198 2199 /// Merge alignment attributes from \p Old to \p New, taking into account the 2200 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2201 /// 2202 /// \return \c true if any attributes were added to \p New. 2203 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2204 // Look for alignas attributes on Old, and pick out whichever attribute 2205 // specifies the strictest alignment requirement. 2206 AlignedAttr *OldAlignasAttr = nullptr; 2207 AlignedAttr *OldStrictestAlignAttr = nullptr; 2208 unsigned OldAlign = 0; 2209 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2210 // FIXME: We have no way of representing inherited dependent alignments 2211 // in a case like: 2212 // template<int A, int B> struct alignas(A) X; 2213 // template<int A, int B> struct alignas(B) X {}; 2214 // For now, we just ignore any alignas attributes which are not on the 2215 // definition in such a case. 2216 if (I->isAlignmentDependent()) 2217 return false; 2218 2219 if (I->isAlignas()) 2220 OldAlignasAttr = I; 2221 2222 unsigned Align = I->getAlignment(S.Context); 2223 if (Align > OldAlign) { 2224 OldAlign = Align; 2225 OldStrictestAlignAttr = I; 2226 } 2227 } 2228 2229 // Look for alignas attributes on New. 2230 AlignedAttr *NewAlignasAttr = nullptr; 2231 unsigned NewAlign = 0; 2232 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2233 if (I->isAlignmentDependent()) 2234 return false; 2235 2236 if (I->isAlignas()) 2237 NewAlignasAttr = I; 2238 2239 unsigned Align = I->getAlignment(S.Context); 2240 if (Align > NewAlign) 2241 NewAlign = Align; 2242 } 2243 2244 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2245 // Both declarations have 'alignas' attributes. We require them to match. 2246 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2247 // fall short. (If two declarations both have alignas, they must both match 2248 // every definition, and so must match each other if there is a definition.) 2249 2250 // If either declaration only contains 'alignas(0)' specifiers, then it 2251 // specifies the natural alignment for the type. 2252 if (OldAlign == 0 || NewAlign == 0) { 2253 QualType Ty; 2254 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2255 Ty = VD->getType(); 2256 else 2257 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2258 2259 if (OldAlign == 0) 2260 OldAlign = S.Context.getTypeAlign(Ty); 2261 if (NewAlign == 0) 2262 NewAlign = S.Context.getTypeAlign(Ty); 2263 } 2264 2265 if (OldAlign != NewAlign) { 2266 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2267 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2268 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2269 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2270 } 2271 } 2272 2273 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2274 // C++11 [dcl.align]p6: 2275 // if any declaration of an entity has an alignment-specifier, 2276 // every defining declaration of that entity shall specify an 2277 // equivalent alignment. 2278 // C11 6.7.5/7: 2279 // If the definition of an object does not have an alignment 2280 // specifier, any other declaration of that object shall also 2281 // have no alignment specifier. 2282 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2283 << OldAlignasAttr; 2284 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2285 << OldAlignasAttr; 2286 } 2287 2288 bool AnyAdded = false; 2289 2290 // Ensure we have an attribute representing the strictest alignment. 2291 if (OldAlign > NewAlign) { 2292 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2293 Clone->setInherited(true); 2294 New->addAttr(Clone); 2295 AnyAdded = true; 2296 } 2297 2298 // Ensure we have an alignas attribute if the old declaration had one. 2299 if (OldAlignasAttr && !NewAlignasAttr && 2300 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2301 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2302 Clone->setInherited(true); 2303 New->addAttr(Clone); 2304 AnyAdded = true; 2305 } 2306 2307 return AnyAdded; 2308 } 2309 2310 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2311 const InheritableAttr *Attr, 2312 Sema::AvailabilityMergeKind AMK) { 2313 // This function copies an attribute Attr from a previous declaration to the 2314 // new declaration D if the new declaration doesn't itself have that attribute 2315 // yet or if that attribute allows duplicates. 2316 // If you're adding a new attribute that requires logic different from 2317 // "use explicit attribute on decl if present, else use attribute from 2318 // previous decl", for example if the attribute needs to be consistent 2319 // between redeclarations, you need to call a custom merge function here. 2320 InheritableAttr *NewAttr = nullptr; 2321 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2322 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2323 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2324 AA->isImplicit(), AA->getIntroduced(), 2325 AA->getDeprecated(), 2326 AA->getObsoleted(), AA->getUnavailable(), 2327 AA->getMessage(), AA->getStrict(), 2328 AA->getReplacement(), AMK, 2329 AttrSpellingListIndex); 2330 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2331 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2332 AttrSpellingListIndex); 2333 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2334 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2335 AttrSpellingListIndex); 2336 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2337 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2338 AttrSpellingListIndex); 2339 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2340 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2341 AttrSpellingListIndex); 2342 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2343 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2344 FA->getFormatIdx(), FA->getFirstArg(), 2345 AttrSpellingListIndex); 2346 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2347 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2348 AttrSpellingListIndex); 2349 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2350 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2351 AttrSpellingListIndex, 2352 IA->getSemanticSpelling()); 2353 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2354 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2355 &S.Context.Idents.get(AA->getSpelling()), 2356 AttrSpellingListIndex); 2357 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2358 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2359 isa<CUDAGlobalAttr>(Attr))) { 2360 // CUDA target attributes are part of function signature for 2361 // overloading purposes and must not be merged. 2362 return false; 2363 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2364 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2365 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2366 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2367 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2368 NewAttr = S.mergeInternalLinkageAttr( 2369 D, InternalLinkageA->getRange(), 2370 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2371 AttrSpellingListIndex); 2372 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2373 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2374 &S.Context.Idents.get(CommonA->getSpelling()), 2375 AttrSpellingListIndex); 2376 else if (isa<AlignedAttr>(Attr)) 2377 // AlignedAttrs are handled separately, because we need to handle all 2378 // such attributes on a declaration at the same time. 2379 NewAttr = nullptr; 2380 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2381 (AMK == Sema::AMK_Override || 2382 AMK == Sema::AMK_ProtocolImplementation)) 2383 NewAttr = nullptr; 2384 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2385 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2386 UA->getGuid()); 2387 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2388 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2389 2390 if (NewAttr) { 2391 NewAttr->setInherited(true); 2392 D->addAttr(NewAttr); 2393 if (isa<MSInheritanceAttr>(NewAttr)) 2394 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2395 return true; 2396 } 2397 2398 return false; 2399 } 2400 2401 static const Decl *getDefinition(const Decl *D) { 2402 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2403 return TD->getDefinition(); 2404 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2405 const VarDecl *Def = VD->getDefinition(); 2406 if (Def) 2407 return Def; 2408 return VD->getActingDefinition(); 2409 } 2410 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2411 return FD->getDefinition(); 2412 return nullptr; 2413 } 2414 2415 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2416 for (const auto *Attribute : D->attrs()) 2417 if (Attribute->getKind() == Kind) 2418 return true; 2419 return false; 2420 } 2421 2422 /// checkNewAttributesAfterDef - If we already have a definition, check that 2423 /// there are no new attributes in this declaration. 2424 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2425 if (!New->hasAttrs()) 2426 return; 2427 2428 const Decl *Def = getDefinition(Old); 2429 if (!Def || Def == New) 2430 return; 2431 2432 AttrVec &NewAttributes = New->getAttrs(); 2433 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2434 const Attr *NewAttribute = NewAttributes[I]; 2435 2436 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2437 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2438 Sema::SkipBodyInfo SkipBody; 2439 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2440 2441 // If we're skipping this definition, drop the "alias" attribute. 2442 if (SkipBody.ShouldSkip) { 2443 NewAttributes.erase(NewAttributes.begin() + I); 2444 --E; 2445 continue; 2446 } 2447 } else { 2448 VarDecl *VD = cast<VarDecl>(New); 2449 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2450 VarDecl::TentativeDefinition 2451 ? diag::err_alias_after_tentative 2452 : diag::err_redefinition; 2453 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2454 S.Diag(Def->getLocation(), diag::note_previous_definition); 2455 VD->setInvalidDecl(); 2456 } 2457 ++I; 2458 continue; 2459 } 2460 2461 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2462 // Tentative definitions are only interesting for the alias check above. 2463 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2464 ++I; 2465 continue; 2466 } 2467 } 2468 2469 if (hasAttribute(Def, NewAttribute->getKind())) { 2470 ++I; 2471 continue; // regular attr merging will take care of validating this. 2472 } 2473 2474 if (isa<C11NoReturnAttr>(NewAttribute)) { 2475 // C's _Noreturn is allowed to be added to a function after it is defined. 2476 ++I; 2477 continue; 2478 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2479 if (AA->isAlignas()) { 2480 // C++11 [dcl.align]p6: 2481 // if any declaration of an entity has an alignment-specifier, 2482 // every defining declaration of that entity shall specify an 2483 // equivalent alignment. 2484 // C11 6.7.5/7: 2485 // If the definition of an object does not have an alignment 2486 // specifier, any other declaration of that object shall also 2487 // have no alignment specifier. 2488 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2489 << AA; 2490 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2491 << AA; 2492 NewAttributes.erase(NewAttributes.begin() + I); 2493 --E; 2494 continue; 2495 } 2496 } 2497 2498 S.Diag(NewAttribute->getLocation(), 2499 diag::warn_attribute_precede_definition); 2500 S.Diag(Def->getLocation(), diag::note_previous_definition); 2501 NewAttributes.erase(NewAttributes.begin() + I); 2502 --E; 2503 } 2504 } 2505 2506 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2507 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2508 AvailabilityMergeKind AMK) { 2509 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2510 UsedAttr *NewAttr = OldAttr->clone(Context); 2511 NewAttr->setInherited(true); 2512 New->addAttr(NewAttr); 2513 } 2514 2515 if (!Old->hasAttrs() && !New->hasAttrs()) 2516 return; 2517 2518 // Attributes declared post-definition are currently ignored. 2519 checkNewAttributesAfterDef(*this, New, Old); 2520 2521 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2522 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2523 if (OldA->getLabel() != NewA->getLabel()) { 2524 // This redeclaration changes __asm__ label. 2525 Diag(New->getLocation(), diag::err_different_asm_label); 2526 Diag(OldA->getLocation(), diag::note_previous_declaration); 2527 } 2528 } else if (Old->isUsed()) { 2529 // This redeclaration adds an __asm__ label to a declaration that has 2530 // already been ODR-used. 2531 Diag(New->getLocation(), diag::err_late_asm_label_name) 2532 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2533 } 2534 } 2535 2536 // Re-declaration cannot add abi_tag's. 2537 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2538 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2539 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2540 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2541 NewTag) == OldAbiTagAttr->tags_end()) { 2542 Diag(NewAbiTagAttr->getLocation(), 2543 diag::err_new_abi_tag_on_redeclaration) 2544 << NewTag; 2545 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2546 } 2547 } 2548 } else { 2549 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2550 Diag(Old->getLocation(), diag::note_previous_declaration); 2551 } 2552 } 2553 2554 if (!Old->hasAttrs()) 2555 return; 2556 2557 bool foundAny = New->hasAttrs(); 2558 2559 // Ensure that any moving of objects within the allocated map is done before 2560 // we process them. 2561 if (!foundAny) New->setAttrs(AttrVec()); 2562 2563 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2564 // Ignore deprecated/unavailable/availability attributes if requested. 2565 AvailabilityMergeKind LocalAMK = AMK_None; 2566 if (isa<DeprecatedAttr>(I) || 2567 isa<UnavailableAttr>(I) || 2568 isa<AvailabilityAttr>(I)) { 2569 switch (AMK) { 2570 case AMK_None: 2571 continue; 2572 2573 case AMK_Redeclaration: 2574 case AMK_Override: 2575 case AMK_ProtocolImplementation: 2576 LocalAMK = AMK; 2577 break; 2578 } 2579 } 2580 2581 // Already handled. 2582 if (isa<UsedAttr>(I)) 2583 continue; 2584 2585 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2586 foundAny = true; 2587 } 2588 2589 if (mergeAlignedAttrs(*this, New, Old)) 2590 foundAny = true; 2591 2592 if (!foundAny) New->dropAttrs(); 2593 } 2594 2595 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2596 /// to the new one. 2597 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2598 const ParmVarDecl *oldDecl, 2599 Sema &S) { 2600 // C++11 [dcl.attr.depend]p2: 2601 // The first declaration of a function shall specify the 2602 // carries_dependency attribute for its declarator-id if any declaration 2603 // of the function specifies the carries_dependency attribute. 2604 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2605 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2606 S.Diag(CDA->getLocation(), 2607 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2608 // Find the first declaration of the parameter. 2609 // FIXME: Should we build redeclaration chains for function parameters? 2610 const FunctionDecl *FirstFD = 2611 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2612 const ParmVarDecl *FirstVD = 2613 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2614 S.Diag(FirstVD->getLocation(), 2615 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2616 } 2617 2618 if (!oldDecl->hasAttrs()) 2619 return; 2620 2621 bool foundAny = newDecl->hasAttrs(); 2622 2623 // Ensure that any moving of objects within the allocated map is 2624 // done before we process them. 2625 if (!foundAny) newDecl->setAttrs(AttrVec()); 2626 2627 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2628 if (!DeclHasAttr(newDecl, I)) { 2629 InheritableAttr *newAttr = 2630 cast<InheritableParamAttr>(I->clone(S.Context)); 2631 newAttr->setInherited(true); 2632 newDecl->addAttr(newAttr); 2633 foundAny = true; 2634 } 2635 } 2636 2637 if (!foundAny) newDecl->dropAttrs(); 2638 } 2639 2640 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2641 const ParmVarDecl *OldParam, 2642 Sema &S) { 2643 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2644 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2645 if (*Oldnullability != *Newnullability) { 2646 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2647 << DiagNullabilityKind( 2648 *Newnullability, 2649 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2650 != 0)) 2651 << DiagNullabilityKind( 2652 *Oldnullability, 2653 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2654 != 0)); 2655 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2656 } 2657 } else { 2658 QualType NewT = NewParam->getType(); 2659 NewT = S.Context.getAttributedType( 2660 AttributedType::getNullabilityAttrKind(*Oldnullability), 2661 NewT, NewT); 2662 NewParam->setType(NewT); 2663 } 2664 } 2665 } 2666 2667 namespace { 2668 2669 /// Used in MergeFunctionDecl to keep track of function parameters in 2670 /// C. 2671 struct GNUCompatibleParamWarning { 2672 ParmVarDecl *OldParm; 2673 ParmVarDecl *NewParm; 2674 QualType PromotedType; 2675 }; 2676 2677 } // end anonymous namespace 2678 2679 /// getSpecialMember - get the special member enum for a method. 2680 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2681 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2682 if (Ctor->isDefaultConstructor()) 2683 return Sema::CXXDefaultConstructor; 2684 2685 if (Ctor->isCopyConstructor()) 2686 return Sema::CXXCopyConstructor; 2687 2688 if (Ctor->isMoveConstructor()) 2689 return Sema::CXXMoveConstructor; 2690 } else if (isa<CXXDestructorDecl>(MD)) { 2691 return Sema::CXXDestructor; 2692 } else if (MD->isCopyAssignmentOperator()) { 2693 return Sema::CXXCopyAssignment; 2694 } else if (MD->isMoveAssignmentOperator()) { 2695 return Sema::CXXMoveAssignment; 2696 } 2697 2698 return Sema::CXXInvalid; 2699 } 2700 2701 // Determine whether the previous declaration was a definition, implicit 2702 // declaration, or a declaration. 2703 template <typename T> 2704 static std::pair<diag::kind, SourceLocation> 2705 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2706 diag::kind PrevDiag; 2707 SourceLocation OldLocation = Old->getLocation(); 2708 if (Old->isThisDeclarationADefinition()) 2709 PrevDiag = diag::note_previous_definition; 2710 else if (Old->isImplicit()) { 2711 PrevDiag = diag::note_previous_implicit_declaration; 2712 if (OldLocation.isInvalid()) 2713 OldLocation = New->getLocation(); 2714 } else 2715 PrevDiag = diag::note_previous_declaration; 2716 return std::make_pair(PrevDiag, OldLocation); 2717 } 2718 2719 /// canRedefineFunction - checks if a function can be redefined. Currently, 2720 /// only extern inline functions can be redefined, and even then only in 2721 /// GNU89 mode. 2722 static bool canRedefineFunction(const FunctionDecl *FD, 2723 const LangOptions& LangOpts) { 2724 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2725 !LangOpts.CPlusPlus && 2726 FD->isInlineSpecified() && 2727 FD->getStorageClass() == SC_Extern); 2728 } 2729 2730 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2731 const AttributedType *AT = T->getAs<AttributedType>(); 2732 while (AT && !AT->isCallingConv()) 2733 AT = AT->getModifiedType()->getAs<AttributedType>(); 2734 return AT; 2735 } 2736 2737 template <typename T> 2738 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2739 const DeclContext *DC = Old->getDeclContext(); 2740 if (DC->isRecord()) 2741 return false; 2742 2743 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2744 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2745 return true; 2746 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2747 return true; 2748 return false; 2749 } 2750 2751 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2752 static bool isExternC(VarTemplateDecl *) { return false; } 2753 2754 /// \brief Check whether a redeclaration of an entity introduced by a 2755 /// using-declaration is valid, given that we know it's not an overload 2756 /// (nor a hidden tag declaration). 2757 template<typename ExpectedDecl> 2758 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2759 ExpectedDecl *New) { 2760 // C++11 [basic.scope.declarative]p4: 2761 // Given a set of declarations in a single declarative region, each of 2762 // which specifies the same unqualified name, 2763 // -- they shall all refer to the same entity, or all refer to functions 2764 // and function templates; or 2765 // -- exactly one declaration shall declare a class name or enumeration 2766 // name that is not a typedef name and the other declarations shall all 2767 // refer to the same variable or enumerator, or all refer to functions 2768 // and function templates; in this case the class name or enumeration 2769 // name is hidden (3.3.10). 2770 2771 // C++11 [namespace.udecl]p14: 2772 // If a function declaration in namespace scope or block scope has the 2773 // same name and the same parameter-type-list as a function introduced 2774 // by a using-declaration, and the declarations do not declare the same 2775 // function, the program is ill-formed. 2776 2777 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2778 if (Old && 2779 !Old->getDeclContext()->getRedeclContext()->Equals( 2780 New->getDeclContext()->getRedeclContext()) && 2781 !(isExternC(Old) && isExternC(New))) 2782 Old = nullptr; 2783 2784 if (!Old) { 2785 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2786 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2787 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2788 return true; 2789 } 2790 return false; 2791 } 2792 2793 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2794 const FunctionDecl *B) { 2795 assert(A->getNumParams() == B->getNumParams()); 2796 2797 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2798 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2799 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2800 if (AttrA == AttrB) 2801 return true; 2802 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2803 }; 2804 2805 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2806 } 2807 2808 /// MergeFunctionDecl - We just parsed a function 'New' from 2809 /// declarator D which has the same name and scope as a previous 2810 /// declaration 'Old'. Figure out how to resolve this situation, 2811 /// merging decls or emitting diagnostics as appropriate. 2812 /// 2813 /// In C++, New and Old must be declarations that are not 2814 /// overloaded. Use IsOverload to determine whether New and Old are 2815 /// overloaded, and to select the Old declaration that New should be 2816 /// merged with. 2817 /// 2818 /// Returns true if there was an error, false otherwise. 2819 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2820 Scope *S, bool MergeTypeWithOld) { 2821 // Verify the old decl was also a function. 2822 FunctionDecl *Old = OldD->getAsFunction(); 2823 if (!Old) { 2824 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2825 if (New->getFriendObjectKind()) { 2826 Diag(New->getLocation(), diag::err_using_decl_friend); 2827 Diag(Shadow->getTargetDecl()->getLocation(), 2828 diag::note_using_decl_target); 2829 Diag(Shadow->getUsingDecl()->getLocation(), 2830 diag::note_using_decl) << 0; 2831 return true; 2832 } 2833 2834 // Check whether the two declarations might declare the same function. 2835 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2836 return true; 2837 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2838 } else { 2839 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2840 << New->getDeclName(); 2841 Diag(OldD->getLocation(), diag::note_previous_definition); 2842 return true; 2843 } 2844 } 2845 2846 // If the old declaration is invalid, just give up here. 2847 if (Old->isInvalidDecl()) 2848 return true; 2849 2850 diag::kind PrevDiag; 2851 SourceLocation OldLocation; 2852 std::tie(PrevDiag, OldLocation) = 2853 getNoteDiagForInvalidRedeclaration(Old, New); 2854 2855 // Don't complain about this if we're in GNU89 mode and the old function 2856 // is an extern inline function. 2857 // Don't complain about specializations. They are not supposed to have 2858 // storage classes. 2859 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2860 New->getStorageClass() == SC_Static && 2861 Old->hasExternalFormalLinkage() && 2862 !New->getTemplateSpecializationInfo() && 2863 !canRedefineFunction(Old, getLangOpts())) { 2864 if (getLangOpts().MicrosoftExt) { 2865 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2866 Diag(OldLocation, PrevDiag); 2867 } else { 2868 Diag(New->getLocation(), diag::err_static_non_static) << New; 2869 Diag(OldLocation, PrevDiag); 2870 return true; 2871 } 2872 } 2873 2874 if (New->hasAttr<InternalLinkageAttr>() && 2875 !Old->hasAttr<InternalLinkageAttr>()) { 2876 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2877 << New->getDeclName(); 2878 Diag(Old->getLocation(), diag::note_previous_definition); 2879 New->dropAttr<InternalLinkageAttr>(); 2880 } 2881 2882 // If a function is first declared with a calling convention, but is later 2883 // declared or defined without one, all following decls assume the calling 2884 // convention of the first. 2885 // 2886 // It's OK if a function is first declared without a calling convention, 2887 // but is later declared or defined with the default calling convention. 2888 // 2889 // To test if either decl has an explicit calling convention, we look for 2890 // AttributedType sugar nodes on the type as written. If they are missing or 2891 // were canonicalized away, we assume the calling convention was implicit. 2892 // 2893 // Note also that we DO NOT return at this point, because we still have 2894 // other tests to run. 2895 QualType OldQType = Context.getCanonicalType(Old->getType()); 2896 QualType NewQType = Context.getCanonicalType(New->getType()); 2897 const FunctionType *OldType = cast<FunctionType>(OldQType); 2898 const FunctionType *NewType = cast<FunctionType>(NewQType); 2899 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2900 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2901 bool RequiresAdjustment = false; 2902 2903 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2904 FunctionDecl *First = Old->getFirstDecl(); 2905 const FunctionType *FT = 2906 First->getType().getCanonicalType()->castAs<FunctionType>(); 2907 FunctionType::ExtInfo FI = FT->getExtInfo(); 2908 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2909 if (!NewCCExplicit) { 2910 // Inherit the CC from the previous declaration if it was specified 2911 // there but not here. 2912 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2913 RequiresAdjustment = true; 2914 } else { 2915 // Calling conventions aren't compatible, so complain. 2916 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2917 Diag(New->getLocation(), diag::err_cconv_change) 2918 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2919 << !FirstCCExplicit 2920 << (!FirstCCExplicit ? "" : 2921 FunctionType::getNameForCallConv(FI.getCC())); 2922 2923 // Put the note on the first decl, since it is the one that matters. 2924 Diag(First->getLocation(), diag::note_previous_declaration); 2925 return true; 2926 } 2927 } 2928 2929 // FIXME: diagnose the other way around? 2930 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2931 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2932 RequiresAdjustment = true; 2933 } 2934 2935 // Merge regparm attribute. 2936 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2937 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2938 if (NewTypeInfo.getHasRegParm()) { 2939 Diag(New->getLocation(), diag::err_regparm_mismatch) 2940 << NewType->getRegParmType() 2941 << OldType->getRegParmType(); 2942 Diag(OldLocation, diag::note_previous_declaration); 2943 return true; 2944 } 2945 2946 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2947 RequiresAdjustment = true; 2948 } 2949 2950 // Merge ns_returns_retained attribute. 2951 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2952 if (NewTypeInfo.getProducesResult()) { 2953 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2954 Diag(OldLocation, diag::note_previous_declaration); 2955 return true; 2956 } 2957 2958 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2959 RequiresAdjustment = true; 2960 } 2961 2962 if (RequiresAdjustment) { 2963 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2964 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2965 New->setType(QualType(AdjustedType, 0)); 2966 NewQType = Context.getCanonicalType(New->getType()); 2967 NewType = cast<FunctionType>(NewQType); 2968 } 2969 2970 // If this redeclaration makes the function inline, we may need to add it to 2971 // UndefinedButUsed. 2972 if (!Old->isInlined() && New->isInlined() && 2973 !New->hasAttr<GNUInlineAttr>() && 2974 !getLangOpts().GNUInline && 2975 Old->isUsed(false) && 2976 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2977 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2978 SourceLocation())); 2979 2980 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2981 // about it. 2982 if (New->hasAttr<GNUInlineAttr>() && 2983 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2984 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2985 } 2986 2987 // If pass_object_size params don't match up perfectly, this isn't a valid 2988 // redeclaration. 2989 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2990 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2991 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2992 << New->getDeclName(); 2993 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2994 return true; 2995 } 2996 2997 if (getLangOpts().CPlusPlus) { 2998 // C++1z [over.load]p2 2999 // Certain function declarations cannot be overloaded: 3000 // -- Function declarations that differ only in the return type, 3001 // the exception specification, or both cannot be overloaded. 3002 3003 // Check the exception specifications match. This may recompute the type of 3004 // both Old and New if it resolved exception specifications, so grab the 3005 // types again after this. Because this updates the type, we do this before 3006 // any of the other checks below, which may update the "de facto" NewQType 3007 // but do not necessarily update the type of New. 3008 if (CheckEquivalentExceptionSpec(Old, New)) 3009 return true; 3010 OldQType = Context.getCanonicalType(Old->getType()); 3011 NewQType = Context.getCanonicalType(New->getType()); 3012 3013 // Go back to the type source info to compare the declared return types, 3014 // per C++1y [dcl.type.auto]p13: 3015 // Redeclarations or specializations of a function or function template 3016 // with a declared return type that uses a placeholder type shall also 3017 // use that placeholder, not a deduced type. 3018 QualType OldDeclaredReturnType = 3019 (Old->getTypeSourceInfo() 3020 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3021 : OldType)->getReturnType(); 3022 QualType NewDeclaredReturnType = 3023 (New->getTypeSourceInfo() 3024 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3025 : NewType)->getReturnType(); 3026 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3027 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3028 New->isLocalExternDecl())) { 3029 QualType ResQT; 3030 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3031 OldDeclaredReturnType->isObjCObjectPointerType()) 3032 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3033 if (ResQT.isNull()) { 3034 if (New->isCXXClassMember() && New->isOutOfLine()) 3035 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3036 << New << New->getReturnTypeSourceRange(); 3037 else 3038 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3039 << New->getReturnTypeSourceRange(); 3040 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3041 << Old->getReturnTypeSourceRange(); 3042 return true; 3043 } 3044 else 3045 NewQType = ResQT; 3046 } 3047 3048 QualType OldReturnType = OldType->getReturnType(); 3049 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3050 if (OldReturnType != NewReturnType) { 3051 // If this function has a deduced return type and has already been 3052 // defined, copy the deduced value from the old declaration. 3053 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3054 if (OldAT && OldAT->isDeduced()) { 3055 New->setType( 3056 SubstAutoType(New->getType(), 3057 OldAT->isDependentType() ? Context.DependentTy 3058 : OldAT->getDeducedType())); 3059 NewQType = Context.getCanonicalType( 3060 SubstAutoType(NewQType, 3061 OldAT->isDependentType() ? Context.DependentTy 3062 : OldAT->getDeducedType())); 3063 } 3064 } 3065 3066 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3068 if (OldMethod && NewMethod) { 3069 // Preserve triviality. 3070 NewMethod->setTrivial(OldMethod->isTrivial()); 3071 3072 // MSVC allows explicit template specialization at class scope: 3073 // 2 CXXMethodDecls referring to the same function will be injected. 3074 // We don't want a redeclaration error. 3075 bool IsClassScopeExplicitSpecialization = 3076 OldMethod->isFunctionTemplateSpecialization() && 3077 NewMethod->isFunctionTemplateSpecialization(); 3078 bool isFriend = NewMethod->getFriendObjectKind(); 3079 3080 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3081 !IsClassScopeExplicitSpecialization) { 3082 // -- Member function declarations with the same name and the 3083 // same parameter types cannot be overloaded if any of them 3084 // is a static member function declaration. 3085 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3086 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3087 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3088 return true; 3089 } 3090 3091 // C++ [class.mem]p1: 3092 // [...] A member shall not be declared twice in the 3093 // member-specification, except that a nested class or member 3094 // class template can be declared and then later defined. 3095 if (ActiveTemplateInstantiations.empty()) { 3096 unsigned NewDiag; 3097 if (isa<CXXConstructorDecl>(OldMethod)) 3098 NewDiag = diag::err_constructor_redeclared; 3099 else if (isa<CXXDestructorDecl>(NewMethod)) 3100 NewDiag = diag::err_destructor_redeclared; 3101 else if (isa<CXXConversionDecl>(NewMethod)) 3102 NewDiag = diag::err_conv_function_redeclared; 3103 else 3104 NewDiag = diag::err_member_redeclared; 3105 3106 Diag(New->getLocation(), NewDiag); 3107 } else { 3108 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3109 << New << New->getType(); 3110 } 3111 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3112 return true; 3113 3114 // Complain if this is an explicit declaration of a special 3115 // member that was initially declared implicitly. 3116 // 3117 // As an exception, it's okay to befriend such methods in order 3118 // to permit the implicit constructor/destructor/operator calls. 3119 } else if (OldMethod->isImplicit()) { 3120 if (isFriend) { 3121 NewMethod->setImplicit(); 3122 } else { 3123 Diag(NewMethod->getLocation(), 3124 diag::err_definition_of_implicitly_declared_member) 3125 << New << getSpecialMember(OldMethod); 3126 return true; 3127 } 3128 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3129 Diag(NewMethod->getLocation(), 3130 diag::err_definition_of_explicitly_defaulted_member) 3131 << getSpecialMember(OldMethod); 3132 return true; 3133 } 3134 } 3135 3136 // C++11 [dcl.attr.noreturn]p1: 3137 // The first declaration of a function shall specify the noreturn 3138 // attribute if any declaration of that function specifies the noreturn 3139 // attribute. 3140 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3141 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3142 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3143 Diag(Old->getFirstDecl()->getLocation(), 3144 diag::note_noreturn_missing_first_decl); 3145 } 3146 3147 // C++11 [dcl.attr.depend]p2: 3148 // The first declaration of a function shall specify the 3149 // carries_dependency attribute for its declarator-id if any declaration 3150 // of the function specifies the carries_dependency attribute. 3151 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3152 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3153 Diag(CDA->getLocation(), 3154 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3155 Diag(Old->getFirstDecl()->getLocation(), 3156 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3157 } 3158 3159 // (C++98 8.3.5p3): 3160 // All declarations for a function shall agree exactly in both the 3161 // return type and the parameter-type-list. 3162 // We also want to respect all the extended bits except noreturn. 3163 3164 // noreturn should now match unless the old type info didn't have it. 3165 QualType OldQTypeForComparison = OldQType; 3166 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3167 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3168 const FunctionType *OldTypeForComparison 3169 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3170 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3171 assert(OldQTypeForComparison.isCanonical()); 3172 } 3173 3174 if (haveIncompatibleLanguageLinkages(Old, New)) { 3175 // As a special case, retain the language linkage from previous 3176 // declarations of a friend function as an extension. 3177 // 3178 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3179 // and is useful because there's otherwise no way to specify language 3180 // linkage within class scope. 3181 // 3182 // Check cautiously as the friend object kind isn't yet complete. 3183 if (New->getFriendObjectKind() != Decl::FOK_None) { 3184 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3185 Diag(OldLocation, PrevDiag); 3186 } else { 3187 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3188 Diag(OldLocation, PrevDiag); 3189 return true; 3190 } 3191 } 3192 3193 if (OldQTypeForComparison == NewQType) 3194 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3195 3196 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3197 New->isLocalExternDecl()) { 3198 // It's OK if we couldn't merge types for a local function declaraton 3199 // if either the old or new type is dependent. We'll merge the types 3200 // when we instantiate the function. 3201 return false; 3202 } 3203 3204 // Fall through for conflicting redeclarations and redefinitions. 3205 } 3206 3207 // C: Function types need to be compatible, not identical. This handles 3208 // duplicate function decls like "void f(int); void f(enum X);" properly. 3209 if (!getLangOpts().CPlusPlus && 3210 Context.typesAreCompatible(OldQType, NewQType)) { 3211 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3212 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3213 const FunctionProtoType *OldProto = nullptr; 3214 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3215 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3216 // The old declaration provided a function prototype, but the 3217 // new declaration does not. Merge in the prototype. 3218 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3219 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3220 NewQType = 3221 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3222 OldProto->getExtProtoInfo()); 3223 New->setType(NewQType); 3224 New->setHasInheritedPrototype(); 3225 3226 // Synthesize parameters with the same types. 3227 SmallVector<ParmVarDecl*, 16> Params; 3228 for (const auto &ParamType : OldProto->param_types()) { 3229 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3230 SourceLocation(), nullptr, 3231 ParamType, /*TInfo=*/nullptr, 3232 SC_None, nullptr); 3233 Param->setScopeInfo(0, Params.size()); 3234 Param->setImplicit(); 3235 Params.push_back(Param); 3236 } 3237 3238 New->setParams(Params); 3239 } 3240 3241 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3242 } 3243 3244 // GNU C permits a K&R definition to follow a prototype declaration 3245 // if the declared types of the parameters in the K&R definition 3246 // match the types in the prototype declaration, even when the 3247 // promoted types of the parameters from the K&R definition differ 3248 // from the types in the prototype. GCC then keeps the types from 3249 // the prototype. 3250 // 3251 // If a variadic prototype is followed by a non-variadic K&R definition, 3252 // the K&R definition becomes variadic. This is sort of an edge case, but 3253 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3254 // C99 6.9.1p8. 3255 if (!getLangOpts().CPlusPlus && 3256 Old->hasPrototype() && !New->hasPrototype() && 3257 New->getType()->getAs<FunctionProtoType>() && 3258 Old->getNumParams() == New->getNumParams()) { 3259 SmallVector<QualType, 16> ArgTypes; 3260 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3261 const FunctionProtoType *OldProto 3262 = Old->getType()->getAs<FunctionProtoType>(); 3263 const FunctionProtoType *NewProto 3264 = New->getType()->getAs<FunctionProtoType>(); 3265 3266 // Determine whether this is the GNU C extension. 3267 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3268 NewProto->getReturnType()); 3269 bool LooseCompatible = !MergedReturn.isNull(); 3270 for (unsigned Idx = 0, End = Old->getNumParams(); 3271 LooseCompatible && Idx != End; ++Idx) { 3272 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3273 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3274 if (Context.typesAreCompatible(OldParm->getType(), 3275 NewProto->getParamType(Idx))) { 3276 ArgTypes.push_back(NewParm->getType()); 3277 } else if (Context.typesAreCompatible(OldParm->getType(), 3278 NewParm->getType(), 3279 /*CompareUnqualified=*/true)) { 3280 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3281 NewProto->getParamType(Idx) }; 3282 Warnings.push_back(Warn); 3283 ArgTypes.push_back(NewParm->getType()); 3284 } else 3285 LooseCompatible = false; 3286 } 3287 3288 if (LooseCompatible) { 3289 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3290 Diag(Warnings[Warn].NewParm->getLocation(), 3291 diag::ext_param_promoted_not_compatible_with_prototype) 3292 << Warnings[Warn].PromotedType 3293 << Warnings[Warn].OldParm->getType(); 3294 if (Warnings[Warn].OldParm->getLocation().isValid()) 3295 Diag(Warnings[Warn].OldParm->getLocation(), 3296 diag::note_previous_declaration); 3297 } 3298 3299 if (MergeTypeWithOld) 3300 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3301 OldProto->getExtProtoInfo())); 3302 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3303 } 3304 3305 // Fall through to diagnose conflicting types. 3306 } 3307 3308 // A function that has already been declared has been redeclared or 3309 // defined with a different type; show an appropriate diagnostic. 3310 3311 // If the previous declaration was an implicitly-generated builtin 3312 // declaration, then at the very least we should use a specialized note. 3313 unsigned BuiltinID; 3314 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3315 // If it's actually a library-defined builtin function like 'malloc' 3316 // or 'printf', just warn about the incompatible redeclaration. 3317 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3318 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3319 Diag(OldLocation, diag::note_previous_builtin_declaration) 3320 << Old << Old->getType(); 3321 3322 // If this is a global redeclaration, just forget hereafter 3323 // about the "builtin-ness" of the function. 3324 // 3325 // Doing this for local extern declarations is problematic. If 3326 // the builtin declaration remains visible, a second invalid 3327 // local declaration will produce a hard error; if it doesn't 3328 // remain visible, a single bogus local redeclaration (which is 3329 // actually only a warning) could break all the downstream code. 3330 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3331 New->getIdentifier()->revertBuiltin(); 3332 3333 return false; 3334 } 3335 3336 PrevDiag = diag::note_previous_builtin_declaration; 3337 } 3338 3339 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3340 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3341 return true; 3342 } 3343 3344 /// \brief Completes the merge of two function declarations that are 3345 /// known to be compatible. 3346 /// 3347 /// This routine handles the merging of attributes and other 3348 /// properties of function declarations from the old declaration to 3349 /// the new declaration, once we know that New is in fact a 3350 /// redeclaration of Old. 3351 /// 3352 /// \returns false 3353 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3354 Scope *S, bool MergeTypeWithOld) { 3355 // Merge the attributes 3356 mergeDeclAttributes(New, Old); 3357 3358 // Merge "pure" flag. 3359 if (Old->isPure()) 3360 New->setPure(); 3361 3362 // Merge "used" flag. 3363 if (Old->getMostRecentDecl()->isUsed(false)) 3364 New->setIsUsed(); 3365 3366 // Merge attributes from the parameters. These can mismatch with K&R 3367 // declarations. 3368 if (New->getNumParams() == Old->getNumParams()) 3369 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3370 ParmVarDecl *NewParam = New->getParamDecl(i); 3371 ParmVarDecl *OldParam = Old->getParamDecl(i); 3372 mergeParamDeclAttributes(NewParam, OldParam, *this); 3373 mergeParamDeclTypes(NewParam, OldParam, *this); 3374 } 3375 3376 if (getLangOpts().CPlusPlus) 3377 return MergeCXXFunctionDecl(New, Old, S); 3378 3379 // Merge the function types so the we get the composite types for the return 3380 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3381 // was visible. 3382 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3383 if (!Merged.isNull() && MergeTypeWithOld) 3384 New->setType(Merged); 3385 3386 return false; 3387 } 3388 3389 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3390 ObjCMethodDecl *oldMethod) { 3391 // Merge the attributes, including deprecated/unavailable 3392 AvailabilityMergeKind MergeKind = 3393 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3394 ? AMK_ProtocolImplementation 3395 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3396 : AMK_Override; 3397 3398 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3399 3400 // Merge attributes from the parameters. 3401 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3402 oe = oldMethod->param_end(); 3403 for (ObjCMethodDecl::param_iterator 3404 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3405 ni != ne && oi != oe; ++ni, ++oi) 3406 mergeParamDeclAttributes(*ni, *oi, *this); 3407 3408 CheckObjCMethodOverride(newMethod, oldMethod); 3409 } 3410 3411 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3412 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3413 3414 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3415 ? diag::err_redefinition_different_type 3416 : diag::err_redeclaration_different_type) 3417 << New->getDeclName() << New->getType() << Old->getType(); 3418 3419 diag::kind PrevDiag; 3420 SourceLocation OldLocation; 3421 std::tie(PrevDiag, OldLocation) 3422 = getNoteDiagForInvalidRedeclaration(Old, New); 3423 S.Diag(OldLocation, PrevDiag); 3424 New->setInvalidDecl(); 3425 } 3426 3427 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3428 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3429 /// emitting diagnostics as appropriate. 3430 /// 3431 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3432 /// to here in AddInitializerToDecl. We can't check them before the initializer 3433 /// is attached. 3434 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3435 bool MergeTypeWithOld) { 3436 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3437 return; 3438 3439 QualType MergedT; 3440 if (getLangOpts().CPlusPlus) { 3441 if (New->getType()->isUndeducedType()) { 3442 // We don't know what the new type is until the initializer is attached. 3443 return; 3444 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3445 // These could still be something that needs exception specs checked. 3446 return MergeVarDeclExceptionSpecs(New, Old); 3447 } 3448 // C++ [basic.link]p10: 3449 // [...] the types specified by all declarations referring to a given 3450 // object or function shall be identical, except that declarations for an 3451 // array object can specify array types that differ by the presence or 3452 // absence of a major array bound (8.3.4). 3453 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3454 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3455 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3456 3457 // We are merging a variable declaration New into Old. If it has an array 3458 // bound, and that bound differs from Old's bound, we should diagnose the 3459 // mismatch. 3460 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3461 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3462 PrevVD = PrevVD->getPreviousDecl()) { 3463 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3464 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3465 continue; 3466 3467 if (!Context.hasSameType(NewArray, PrevVDTy)) 3468 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3469 } 3470 } 3471 3472 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3473 if (Context.hasSameType(OldArray->getElementType(), 3474 NewArray->getElementType())) 3475 MergedT = New->getType(); 3476 } 3477 // FIXME: Check visibility. New is hidden but has a complete type. If New 3478 // has no array bound, it should not inherit one from Old, if Old is not 3479 // visible. 3480 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3481 if (Context.hasSameType(OldArray->getElementType(), 3482 NewArray->getElementType())) 3483 MergedT = Old->getType(); 3484 } 3485 } 3486 else if (New->getType()->isObjCObjectPointerType() && 3487 Old->getType()->isObjCObjectPointerType()) { 3488 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3489 Old->getType()); 3490 } 3491 } else { 3492 // C 6.2.7p2: 3493 // All declarations that refer to the same object or function shall have 3494 // compatible type. 3495 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3496 } 3497 if (MergedT.isNull()) { 3498 // It's OK if we couldn't merge types if either type is dependent, for a 3499 // block-scope variable. In other cases (static data members of class 3500 // templates, variable templates, ...), we require the types to be 3501 // equivalent. 3502 // FIXME: The C++ standard doesn't say anything about this. 3503 if ((New->getType()->isDependentType() || 3504 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3505 // If the old type was dependent, we can't merge with it, so the new type 3506 // becomes dependent for now. We'll reproduce the original type when we 3507 // instantiate the TypeSourceInfo for the variable. 3508 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3509 New->setType(Context.DependentTy); 3510 return; 3511 } 3512 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3513 } 3514 3515 // Don't actually update the type on the new declaration if the old 3516 // declaration was an extern declaration in a different scope. 3517 if (MergeTypeWithOld) 3518 New->setType(MergedT); 3519 } 3520 3521 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3522 LookupResult &Previous) { 3523 // C11 6.2.7p4: 3524 // For an identifier with internal or external linkage declared 3525 // in a scope in which a prior declaration of that identifier is 3526 // visible, if the prior declaration specifies internal or 3527 // external linkage, the type of the identifier at the later 3528 // declaration becomes the composite type. 3529 // 3530 // If the variable isn't visible, we do not merge with its type. 3531 if (Previous.isShadowed()) 3532 return false; 3533 3534 if (S.getLangOpts().CPlusPlus) { 3535 // C++11 [dcl.array]p3: 3536 // If there is a preceding declaration of the entity in the same 3537 // scope in which the bound was specified, an omitted array bound 3538 // is taken to be the same as in that earlier declaration. 3539 return NewVD->isPreviousDeclInSameBlockScope() || 3540 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3541 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3542 } else { 3543 // If the old declaration was function-local, don't merge with its 3544 // type unless we're in the same function. 3545 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3546 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3547 } 3548 } 3549 3550 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3551 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3552 /// situation, merging decls or emitting diagnostics as appropriate. 3553 /// 3554 /// Tentative definition rules (C99 6.9.2p2) are checked by 3555 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3556 /// definitions here, since the initializer hasn't been attached. 3557 /// 3558 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3559 // If the new decl is already invalid, don't do any other checking. 3560 if (New->isInvalidDecl()) 3561 return; 3562 3563 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3564 return; 3565 3566 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3567 3568 // Verify the old decl was also a variable or variable template. 3569 VarDecl *Old = nullptr; 3570 VarTemplateDecl *OldTemplate = nullptr; 3571 if (Previous.isSingleResult()) { 3572 if (NewTemplate) { 3573 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3574 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3575 3576 if (auto *Shadow = 3577 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3578 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3579 return New->setInvalidDecl(); 3580 } else { 3581 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3582 3583 if (auto *Shadow = 3584 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3585 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3586 return New->setInvalidDecl(); 3587 } 3588 } 3589 if (!Old) { 3590 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3591 << New->getDeclName(); 3592 Diag(Previous.getRepresentativeDecl()->getLocation(), 3593 diag::note_previous_definition); 3594 return New->setInvalidDecl(); 3595 } 3596 3597 // Ensure the template parameters are compatible. 3598 if (NewTemplate && 3599 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3600 OldTemplate->getTemplateParameters(), 3601 /*Complain=*/true, TPL_TemplateMatch)) 3602 return New->setInvalidDecl(); 3603 3604 // C++ [class.mem]p1: 3605 // A member shall not be declared twice in the member-specification [...] 3606 // 3607 // Here, we need only consider static data members. 3608 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3609 Diag(New->getLocation(), diag::err_duplicate_member) 3610 << New->getIdentifier(); 3611 Diag(Old->getLocation(), diag::note_previous_declaration); 3612 New->setInvalidDecl(); 3613 } 3614 3615 mergeDeclAttributes(New, Old); 3616 // Warn if an already-declared variable is made a weak_import in a subsequent 3617 // declaration 3618 if (New->hasAttr<WeakImportAttr>() && 3619 Old->getStorageClass() == SC_None && 3620 !Old->hasAttr<WeakImportAttr>()) { 3621 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3622 Diag(Old->getLocation(), diag::note_previous_definition); 3623 // Remove weak_import attribute on new declaration. 3624 New->dropAttr<WeakImportAttr>(); 3625 } 3626 3627 if (New->hasAttr<InternalLinkageAttr>() && 3628 !Old->hasAttr<InternalLinkageAttr>()) { 3629 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3630 << New->getDeclName(); 3631 Diag(Old->getLocation(), diag::note_previous_definition); 3632 New->dropAttr<InternalLinkageAttr>(); 3633 } 3634 3635 // Merge the types. 3636 VarDecl *MostRecent = Old->getMostRecentDecl(); 3637 if (MostRecent != Old) { 3638 MergeVarDeclTypes(New, MostRecent, 3639 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3640 if (New->isInvalidDecl()) 3641 return; 3642 } 3643 3644 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3645 if (New->isInvalidDecl()) 3646 return; 3647 3648 diag::kind PrevDiag; 3649 SourceLocation OldLocation; 3650 std::tie(PrevDiag, OldLocation) = 3651 getNoteDiagForInvalidRedeclaration(Old, New); 3652 3653 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3654 if (New->getStorageClass() == SC_Static && 3655 !New->isStaticDataMember() && 3656 Old->hasExternalFormalLinkage()) { 3657 if (getLangOpts().MicrosoftExt) { 3658 Diag(New->getLocation(), diag::ext_static_non_static) 3659 << New->getDeclName(); 3660 Diag(OldLocation, PrevDiag); 3661 } else { 3662 Diag(New->getLocation(), diag::err_static_non_static) 3663 << New->getDeclName(); 3664 Diag(OldLocation, PrevDiag); 3665 return New->setInvalidDecl(); 3666 } 3667 } 3668 // C99 6.2.2p4: 3669 // For an identifier declared with the storage-class specifier 3670 // extern in a scope in which a prior declaration of that 3671 // identifier is visible,23) if the prior declaration specifies 3672 // internal or external linkage, the linkage of the identifier at 3673 // the later declaration is the same as the linkage specified at 3674 // the prior declaration. If no prior declaration is visible, or 3675 // if the prior declaration specifies no linkage, then the 3676 // identifier has external linkage. 3677 if (New->hasExternalStorage() && Old->hasLinkage()) 3678 /* Okay */; 3679 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3680 !New->isStaticDataMember() && 3681 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3682 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3683 Diag(OldLocation, PrevDiag); 3684 return New->setInvalidDecl(); 3685 } 3686 3687 // Check if extern is followed by non-extern and vice-versa. 3688 if (New->hasExternalStorage() && 3689 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3690 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3691 Diag(OldLocation, PrevDiag); 3692 return New->setInvalidDecl(); 3693 } 3694 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3695 !New->hasExternalStorage()) { 3696 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3697 Diag(OldLocation, PrevDiag); 3698 return New->setInvalidDecl(); 3699 } 3700 3701 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3702 3703 // FIXME: The test for external storage here seems wrong? We still 3704 // need to check for mismatches. 3705 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3706 // Don't complain about out-of-line definitions of static members. 3707 !(Old->getLexicalDeclContext()->isRecord() && 3708 !New->getLexicalDeclContext()->isRecord())) { 3709 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3710 Diag(OldLocation, PrevDiag); 3711 return New->setInvalidDecl(); 3712 } 3713 3714 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3715 if (VarDecl *Def = Old->getDefinition()) { 3716 // C++1z [dcl.fcn.spec]p4: 3717 // If the definition of a variable appears in a translation unit before 3718 // its first declaration as inline, the program is ill-formed. 3719 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3720 Diag(Def->getLocation(), diag::note_previous_definition); 3721 } 3722 } 3723 3724 // If this redeclaration makes the function inline, we may need to add it to 3725 // UndefinedButUsed. 3726 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3727 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3728 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3729 SourceLocation())); 3730 3731 if (New->getTLSKind() != Old->getTLSKind()) { 3732 if (!Old->getTLSKind()) { 3733 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3734 Diag(OldLocation, PrevDiag); 3735 } else if (!New->getTLSKind()) { 3736 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3737 Diag(OldLocation, PrevDiag); 3738 } else { 3739 // Do not allow redeclaration to change the variable between requiring 3740 // static and dynamic initialization. 3741 // FIXME: GCC allows this, but uses the TLS keyword on the first 3742 // declaration to determine the kind. Do we need to be compatible here? 3743 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3744 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3745 Diag(OldLocation, PrevDiag); 3746 } 3747 } 3748 3749 // C++ doesn't have tentative definitions, so go right ahead and check here. 3750 if (getLangOpts().CPlusPlus && 3751 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3752 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3753 Old->getCanonicalDecl()->isConstexpr()) { 3754 // This definition won't be a definition any more once it's been merged. 3755 Diag(New->getLocation(), 3756 diag::warn_deprecated_redundant_constexpr_static_def); 3757 } else if (VarDecl *Def = Old->getDefinition()) { 3758 if (checkVarDeclRedefinition(Def, New)) 3759 return; 3760 } 3761 } 3762 3763 if (haveIncompatibleLanguageLinkages(Old, New)) { 3764 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3765 Diag(OldLocation, PrevDiag); 3766 New->setInvalidDecl(); 3767 return; 3768 } 3769 3770 // Merge "used" flag. 3771 if (Old->getMostRecentDecl()->isUsed(false)) 3772 New->setIsUsed(); 3773 3774 // Keep a chain of previous declarations. 3775 New->setPreviousDecl(Old); 3776 if (NewTemplate) 3777 NewTemplate->setPreviousDecl(OldTemplate); 3778 3779 // Inherit access appropriately. 3780 New->setAccess(Old->getAccess()); 3781 if (NewTemplate) 3782 NewTemplate->setAccess(New->getAccess()); 3783 3784 if (Old->isInline()) 3785 New->setImplicitlyInline(); 3786 } 3787 3788 /// We've just determined that \p Old and \p New both appear to be definitions 3789 /// of the same variable. Either diagnose or fix the problem. 3790 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3791 if (!hasVisibleDefinition(Old) && 3792 (New->getFormalLinkage() == InternalLinkage || 3793 New->isInline() || 3794 New->getDescribedVarTemplate() || 3795 New->getNumTemplateParameterLists() || 3796 New->getDeclContext()->isDependentContext())) { 3797 // The previous definition is hidden, and multiple definitions are 3798 // permitted (in separate TUs). Demote this to a declaration. 3799 New->demoteThisDefinitionToDeclaration(); 3800 3801 // Make the canonical definition visible. 3802 if (auto *OldTD = Old->getDescribedVarTemplate()) 3803 makeMergedDefinitionVisible(OldTD, New->getLocation()); 3804 makeMergedDefinitionVisible(Old, New->getLocation()); 3805 return false; 3806 } else { 3807 Diag(New->getLocation(), diag::err_redefinition) << New; 3808 Diag(Old->getLocation(), diag::note_previous_definition); 3809 New->setInvalidDecl(); 3810 return true; 3811 } 3812 } 3813 3814 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3815 /// no declarator (e.g. "struct foo;") is parsed. 3816 Decl * 3817 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3818 RecordDecl *&AnonRecord) { 3819 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3820 AnonRecord); 3821 } 3822 3823 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3824 // disambiguate entities defined in different scopes. 3825 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3826 // compatibility. 3827 // We will pick our mangling number depending on which version of MSVC is being 3828 // targeted. 3829 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3830 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3831 ? S->getMSCurManglingNumber() 3832 : S->getMSLastManglingNumber(); 3833 } 3834 3835 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3836 if (!Context.getLangOpts().CPlusPlus) 3837 return; 3838 3839 if (isa<CXXRecordDecl>(Tag->getParent())) { 3840 // If this tag is the direct child of a class, number it if 3841 // it is anonymous. 3842 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3843 return; 3844 MangleNumberingContext &MCtx = 3845 Context.getManglingNumberContext(Tag->getParent()); 3846 Context.setManglingNumber( 3847 Tag, MCtx.getManglingNumber( 3848 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3849 return; 3850 } 3851 3852 // If this tag isn't a direct child of a class, number it if it is local. 3853 Decl *ManglingContextDecl; 3854 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3855 Tag->getDeclContext(), ManglingContextDecl)) { 3856 Context.setManglingNumber( 3857 Tag, MCtx->getManglingNumber( 3858 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3859 } 3860 } 3861 3862 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3863 TypedefNameDecl *NewTD) { 3864 if (TagFromDeclSpec->isInvalidDecl()) 3865 return; 3866 3867 // Do nothing if the tag already has a name for linkage purposes. 3868 if (TagFromDeclSpec->hasNameForLinkage()) 3869 return; 3870 3871 // A well-formed anonymous tag must always be a TUK_Definition. 3872 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3873 3874 // The type must match the tag exactly; no qualifiers allowed. 3875 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3876 Context.getTagDeclType(TagFromDeclSpec))) { 3877 if (getLangOpts().CPlusPlus) 3878 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3879 return; 3880 } 3881 3882 // If we've already computed linkage for the anonymous tag, then 3883 // adding a typedef name for the anonymous decl can change that 3884 // linkage, which might be a serious problem. Diagnose this as 3885 // unsupported and ignore the typedef name. TODO: we should 3886 // pursue this as a language defect and establish a formal rule 3887 // for how to handle it. 3888 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3889 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3890 3891 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3892 tagLoc = getLocForEndOfToken(tagLoc); 3893 3894 llvm::SmallString<40> textToInsert; 3895 textToInsert += ' '; 3896 textToInsert += NewTD->getIdentifier()->getName(); 3897 Diag(tagLoc, diag::note_typedef_changes_linkage) 3898 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3899 return; 3900 } 3901 3902 // Otherwise, set this is the anon-decl typedef for the tag. 3903 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3904 } 3905 3906 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3907 switch (T) { 3908 case DeclSpec::TST_class: 3909 return 0; 3910 case DeclSpec::TST_struct: 3911 return 1; 3912 case DeclSpec::TST_interface: 3913 return 2; 3914 case DeclSpec::TST_union: 3915 return 3; 3916 case DeclSpec::TST_enum: 3917 return 4; 3918 default: 3919 llvm_unreachable("unexpected type specifier"); 3920 } 3921 } 3922 3923 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3924 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3925 /// parameters to cope with template friend declarations. 3926 Decl * 3927 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3928 MultiTemplateParamsArg TemplateParams, 3929 bool IsExplicitInstantiation, 3930 RecordDecl *&AnonRecord) { 3931 Decl *TagD = nullptr; 3932 TagDecl *Tag = nullptr; 3933 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3934 DS.getTypeSpecType() == DeclSpec::TST_struct || 3935 DS.getTypeSpecType() == DeclSpec::TST_interface || 3936 DS.getTypeSpecType() == DeclSpec::TST_union || 3937 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3938 TagD = DS.getRepAsDecl(); 3939 3940 if (!TagD) // We probably had an error 3941 return nullptr; 3942 3943 // Note that the above type specs guarantee that the 3944 // type rep is a Decl, whereas in many of the others 3945 // it's a Type. 3946 if (isa<TagDecl>(TagD)) 3947 Tag = cast<TagDecl>(TagD); 3948 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3949 Tag = CTD->getTemplatedDecl(); 3950 } 3951 3952 if (Tag) { 3953 handleTagNumbering(Tag, S); 3954 Tag->setFreeStanding(); 3955 if (Tag->isInvalidDecl()) 3956 return Tag; 3957 } 3958 3959 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3960 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3961 // or incomplete types shall not be restrict-qualified." 3962 if (TypeQuals & DeclSpec::TQ_restrict) 3963 Diag(DS.getRestrictSpecLoc(), 3964 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3965 << DS.getSourceRange(); 3966 } 3967 3968 if (DS.isInlineSpecified()) 3969 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3970 << getLangOpts().CPlusPlus1z; 3971 3972 if (DS.isConstexprSpecified()) { 3973 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3974 // and definitions of functions and variables. 3975 if (Tag) 3976 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3977 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3978 else 3979 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3980 // Don't emit warnings after this error. 3981 return TagD; 3982 } 3983 3984 if (DS.isConceptSpecified()) { 3985 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3986 // either a function concept and its definition or a variable concept and 3987 // its initializer. 3988 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3989 return TagD; 3990 } 3991 3992 DiagnoseFunctionSpecifiers(DS); 3993 3994 if (DS.isFriendSpecified()) { 3995 // If we're dealing with a decl but not a TagDecl, assume that 3996 // whatever routines created it handled the friendship aspect. 3997 if (TagD && !Tag) 3998 return nullptr; 3999 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4000 } 4001 4002 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4003 bool IsExplicitSpecialization = 4004 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4005 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4006 !IsExplicitInstantiation && !IsExplicitSpecialization && 4007 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4008 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4009 // nested-name-specifier unless it is an explicit instantiation 4010 // or an explicit specialization. 4011 // 4012 // FIXME: We allow class template partial specializations here too, per the 4013 // obvious intent of DR1819. 4014 // 4015 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4016 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4017 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4018 return nullptr; 4019 } 4020 4021 // Track whether this decl-specifier declares anything. 4022 bool DeclaresAnything = true; 4023 4024 // Handle anonymous struct definitions. 4025 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4026 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4027 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4028 if (getLangOpts().CPlusPlus || 4029 Record->getDeclContext()->isRecord()) { 4030 // If CurContext is a DeclContext that can contain statements, 4031 // RecursiveASTVisitor won't visit the decls that 4032 // BuildAnonymousStructOrUnion() will put into CurContext. 4033 // Also store them here so that they can be part of the 4034 // DeclStmt that gets created in this case. 4035 // FIXME: Also return the IndirectFieldDecls created by 4036 // BuildAnonymousStructOr union, for the same reason? 4037 if (CurContext->isFunctionOrMethod()) 4038 AnonRecord = Record; 4039 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4040 Context.getPrintingPolicy()); 4041 } 4042 4043 DeclaresAnything = false; 4044 } 4045 } 4046 4047 // C11 6.7.2.1p2: 4048 // A struct-declaration that does not declare an anonymous structure or 4049 // anonymous union shall contain a struct-declarator-list. 4050 // 4051 // This rule also existed in C89 and C99; the grammar for struct-declaration 4052 // did not permit a struct-declaration without a struct-declarator-list. 4053 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4054 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4055 // Check for Microsoft C extension: anonymous struct/union member. 4056 // Handle 2 kinds of anonymous struct/union: 4057 // struct STRUCT; 4058 // union UNION; 4059 // and 4060 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4061 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4062 if ((Tag && Tag->getDeclName()) || 4063 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4064 RecordDecl *Record = nullptr; 4065 if (Tag) 4066 Record = dyn_cast<RecordDecl>(Tag); 4067 else if (const RecordType *RT = 4068 DS.getRepAsType().get()->getAsStructureType()) 4069 Record = RT->getDecl(); 4070 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4071 Record = UT->getDecl(); 4072 4073 if (Record && getLangOpts().MicrosoftExt) { 4074 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4075 << Record->isUnion() << DS.getSourceRange(); 4076 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4077 } 4078 4079 DeclaresAnything = false; 4080 } 4081 } 4082 4083 // Skip all the checks below if we have a type error. 4084 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4085 (TagD && TagD->isInvalidDecl())) 4086 return TagD; 4087 4088 if (getLangOpts().CPlusPlus && 4089 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4090 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4091 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4092 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4093 DeclaresAnything = false; 4094 4095 if (!DS.isMissingDeclaratorOk()) { 4096 // Customize diagnostic for a typedef missing a name. 4097 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4098 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4099 << DS.getSourceRange(); 4100 else 4101 DeclaresAnything = false; 4102 } 4103 4104 if (DS.isModulePrivateSpecified() && 4105 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4106 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4107 << Tag->getTagKind() 4108 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4109 4110 ActOnDocumentableDecl(TagD); 4111 4112 // C 6.7/2: 4113 // A declaration [...] shall declare at least a declarator [...], a tag, 4114 // or the members of an enumeration. 4115 // C++ [dcl.dcl]p3: 4116 // [If there are no declarators], and except for the declaration of an 4117 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4118 // names into the program, or shall redeclare a name introduced by a 4119 // previous declaration. 4120 if (!DeclaresAnything) { 4121 // In C, we allow this as a (popular) extension / bug. Don't bother 4122 // producing further diagnostics for redundant qualifiers after this. 4123 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4124 return TagD; 4125 } 4126 4127 // C++ [dcl.stc]p1: 4128 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4129 // init-declarator-list of the declaration shall not be empty. 4130 // C++ [dcl.fct.spec]p1: 4131 // If a cv-qualifier appears in a decl-specifier-seq, the 4132 // init-declarator-list of the declaration shall not be empty. 4133 // 4134 // Spurious qualifiers here appear to be valid in C. 4135 unsigned DiagID = diag::warn_standalone_specifier; 4136 if (getLangOpts().CPlusPlus) 4137 DiagID = diag::ext_standalone_specifier; 4138 4139 // Note that a linkage-specification sets a storage class, but 4140 // 'extern "C" struct foo;' is actually valid and not theoretically 4141 // useless. 4142 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4143 if (SCS == DeclSpec::SCS_mutable) 4144 // Since mutable is not a viable storage class specifier in C, there is 4145 // no reason to treat it as an extension. Instead, diagnose as an error. 4146 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4147 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4148 Diag(DS.getStorageClassSpecLoc(), DiagID) 4149 << DeclSpec::getSpecifierName(SCS); 4150 } 4151 4152 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4153 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4154 << DeclSpec::getSpecifierName(TSCS); 4155 if (DS.getTypeQualifiers()) { 4156 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4157 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4158 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4159 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4160 // Restrict is covered above. 4161 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4162 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4163 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4164 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4165 } 4166 4167 // Warn about ignored type attributes, for example: 4168 // __attribute__((aligned)) struct A; 4169 // Attributes should be placed after tag to apply to type declaration. 4170 if (!DS.getAttributes().empty()) { 4171 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4172 if (TypeSpecType == DeclSpec::TST_class || 4173 TypeSpecType == DeclSpec::TST_struct || 4174 TypeSpecType == DeclSpec::TST_interface || 4175 TypeSpecType == DeclSpec::TST_union || 4176 TypeSpecType == DeclSpec::TST_enum) { 4177 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4178 attrs = attrs->getNext()) 4179 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4180 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4181 } 4182 } 4183 4184 return TagD; 4185 } 4186 4187 /// We are trying to inject an anonymous member into the given scope; 4188 /// check if there's an existing declaration that can't be overloaded. 4189 /// 4190 /// \return true if this is a forbidden redeclaration 4191 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4192 Scope *S, 4193 DeclContext *Owner, 4194 DeclarationName Name, 4195 SourceLocation NameLoc, 4196 bool IsUnion) { 4197 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4198 Sema::ForRedeclaration); 4199 if (!SemaRef.LookupName(R, S)) return false; 4200 4201 // Pick a representative declaration. 4202 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4203 assert(PrevDecl && "Expected a non-null Decl"); 4204 4205 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4206 return false; 4207 4208 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4209 << IsUnion << Name; 4210 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4211 4212 return true; 4213 } 4214 4215 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4216 /// anonymous struct or union AnonRecord into the owning context Owner 4217 /// and scope S. This routine will be invoked just after we realize 4218 /// that an unnamed union or struct is actually an anonymous union or 4219 /// struct, e.g., 4220 /// 4221 /// @code 4222 /// union { 4223 /// int i; 4224 /// float f; 4225 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4226 /// // f into the surrounding scope.x 4227 /// @endcode 4228 /// 4229 /// This routine is recursive, injecting the names of nested anonymous 4230 /// structs/unions into the owning context and scope as well. 4231 static bool 4232 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4233 RecordDecl *AnonRecord, AccessSpecifier AS, 4234 SmallVectorImpl<NamedDecl *> &Chaining) { 4235 bool Invalid = false; 4236 4237 // Look every FieldDecl and IndirectFieldDecl with a name. 4238 for (auto *D : AnonRecord->decls()) { 4239 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4240 cast<NamedDecl>(D)->getDeclName()) { 4241 ValueDecl *VD = cast<ValueDecl>(D); 4242 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4243 VD->getLocation(), 4244 AnonRecord->isUnion())) { 4245 // C++ [class.union]p2: 4246 // The names of the members of an anonymous union shall be 4247 // distinct from the names of any other entity in the 4248 // scope in which the anonymous union is declared. 4249 Invalid = true; 4250 } else { 4251 // C++ [class.union]p2: 4252 // For the purpose of name lookup, after the anonymous union 4253 // definition, the members of the anonymous union are 4254 // considered to have been defined in the scope in which the 4255 // anonymous union is declared. 4256 unsigned OldChainingSize = Chaining.size(); 4257 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4258 Chaining.append(IF->chain_begin(), IF->chain_end()); 4259 else 4260 Chaining.push_back(VD); 4261 4262 assert(Chaining.size() >= 2); 4263 NamedDecl **NamedChain = 4264 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4265 for (unsigned i = 0; i < Chaining.size(); i++) 4266 NamedChain[i] = Chaining[i]; 4267 4268 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4269 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4270 VD->getType(), {NamedChain, Chaining.size()}); 4271 4272 for (const auto *Attr : VD->attrs()) 4273 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4274 4275 IndirectField->setAccess(AS); 4276 IndirectField->setImplicit(); 4277 SemaRef.PushOnScopeChains(IndirectField, S); 4278 4279 // That includes picking up the appropriate access specifier. 4280 if (AS != AS_none) IndirectField->setAccess(AS); 4281 4282 Chaining.resize(OldChainingSize); 4283 } 4284 } 4285 } 4286 4287 return Invalid; 4288 } 4289 4290 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4291 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4292 /// illegal input values are mapped to SC_None. 4293 static StorageClass 4294 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4295 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4296 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4297 "Parser allowed 'typedef' as storage class VarDecl."); 4298 switch (StorageClassSpec) { 4299 case DeclSpec::SCS_unspecified: return SC_None; 4300 case DeclSpec::SCS_extern: 4301 if (DS.isExternInLinkageSpec()) 4302 return SC_None; 4303 return SC_Extern; 4304 case DeclSpec::SCS_static: return SC_Static; 4305 case DeclSpec::SCS_auto: return SC_Auto; 4306 case DeclSpec::SCS_register: return SC_Register; 4307 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4308 // Illegal SCSs map to None: error reporting is up to the caller. 4309 case DeclSpec::SCS_mutable: // Fall through. 4310 case DeclSpec::SCS_typedef: return SC_None; 4311 } 4312 llvm_unreachable("unknown storage class specifier"); 4313 } 4314 4315 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4316 assert(Record->hasInClassInitializer()); 4317 4318 for (const auto *I : Record->decls()) { 4319 const auto *FD = dyn_cast<FieldDecl>(I); 4320 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4321 FD = IFD->getAnonField(); 4322 if (FD && FD->hasInClassInitializer()) 4323 return FD->getLocation(); 4324 } 4325 4326 llvm_unreachable("couldn't find in-class initializer"); 4327 } 4328 4329 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4330 SourceLocation DefaultInitLoc) { 4331 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4332 return; 4333 4334 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4335 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4336 } 4337 4338 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4339 CXXRecordDecl *AnonUnion) { 4340 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4341 return; 4342 4343 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4344 } 4345 4346 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4347 /// anonymous structure or union. Anonymous unions are a C++ feature 4348 /// (C++ [class.union]) and a C11 feature; anonymous structures 4349 /// are a C11 feature and GNU C++ extension. 4350 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4351 AccessSpecifier AS, 4352 RecordDecl *Record, 4353 const PrintingPolicy &Policy) { 4354 DeclContext *Owner = Record->getDeclContext(); 4355 4356 // Diagnose whether this anonymous struct/union is an extension. 4357 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4358 Diag(Record->getLocation(), diag::ext_anonymous_union); 4359 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4360 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4361 else if (!Record->isUnion() && !getLangOpts().C11) 4362 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4363 4364 // C and C++ require different kinds of checks for anonymous 4365 // structs/unions. 4366 bool Invalid = false; 4367 if (getLangOpts().CPlusPlus) { 4368 const char *PrevSpec = nullptr; 4369 unsigned DiagID; 4370 if (Record->isUnion()) { 4371 // C++ [class.union]p6: 4372 // Anonymous unions declared in a named namespace or in the 4373 // global namespace shall be declared static. 4374 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4375 (isa<TranslationUnitDecl>(Owner) || 4376 (isa<NamespaceDecl>(Owner) && 4377 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4378 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4379 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4380 4381 // Recover by adding 'static'. 4382 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4383 PrevSpec, DiagID, Policy); 4384 } 4385 // C++ [class.union]p6: 4386 // A storage class is not allowed in a declaration of an 4387 // anonymous union in a class scope. 4388 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4389 isa<RecordDecl>(Owner)) { 4390 Diag(DS.getStorageClassSpecLoc(), 4391 diag::err_anonymous_union_with_storage_spec) 4392 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4393 4394 // Recover by removing the storage specifier. 4395 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4396 SourceLocation(), 4397 PrevSpec, DiagID, Context.getPrintingPolicy()); 4398 } 4399 } 4400 4401 // Ignore const/volatile/restrict qualifiers. 4402 if (DS.getTypeQualifiers()) { 4403 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4404 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4405 << Record->isUnion() << "const" 4406 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4407 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4408 Diag(DS.getVolatileSpecLoc(), 4409 diag::ext_anonymous_struct_union_qualified) 4410 << Record->isUnion() << "volatile" 4411 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4412 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4413 Diag(DS.getRestrictSpecLoc(), 4414 diag::ext_anonymous_struct_union_qualified) 4415 << Record->isUnion() << "restrict" 4416 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4417 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4418 Diag(DS.getAtomicSpecLoc(), 4419 diag::ext_anonymous_struct_union_qualified) 4420 << Record->isUnion() << "_Atomic" 4421 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4422 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4423 Diag(DS.getUnalignedSpecLoc(), 4424 diag::ext_anonymous_struct_union_qualified) 4425 << Record->isUnion() << "__unaligned" 4426 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4427 4428 DS.ClearTypeQualifiers(); 4429 } 4430 4431 // C++ [class.union]p2: 4432 // The member-specification of an anonymous union shall only 4433 // define non-static data members. [Note: nested types and 4434 // functions cannot be declared within an anonymous union. ] 4435 for (auto *Mem : Record->decls()) { 4436 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4437 // C++ [class.union]p3: 4438 // An anonymous union shall not have private or protected 4439 // members (clause 11). 4440 assert(FD->getAccess() != AS_none); 4441 if (FD->getAccess() != AS_public) { 4442 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4443 << Record->isUnion() << (FD->getAccess() == AS_protected); 4444 Invalid = true; 4445 } 4446 4447 // C++ [class.union]p1 4448 // An object of a class with a non-trivial constructor, a non-trivial 4449 // copy constructor, a non-trivial destructor, or a non-trivial copy 4450 // assignment operator cannot be a member of a union, nor can an 4451 // array of such objects. 4452 if (CheckNontrivialField(FD)) 4453 Invalid = true; 4454 } else if (Mem->isImplicit()) { 4455 // Any implicit members are fine. 4456 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4457 // This is a type that showed up in an 4458 // elaborated-type-specifier inside the anonymous struct or 4459 // union, but which actually declares a type outside of the 4460 // anonymous struct or union. It's okay. 4461 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4462 if (!MemRecord->isAnonymousStructOrUnion() && 4463 MemRecord->getDeclName()) { 4464 // Visual C++ allows type definition in anonymous struct or union. 4465 if (getLangOpts().MicrosoftExt) 4466 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4467 << Record->isUnion(); 4468 else { 4469 // This is a nested type declaration. 4470 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4471 << Record->isUnion(); 4472 Invalid = true; 4473 } 4474 } else { 4475 // This is an anonymous type definition within another anonymous type. 4476 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4477 // not part of standard C++. 4478 Diag(MemRecord->getLocation(), 4479 diag::ext_anonymous_record_with_anonymous_type) 4480 << Record->isUnion(); 4481 } 4482 } else if (isa<AccessSpecDecl>(Mem)) { 4483 // Any access specifier is fine. 4484 } else if (isa<StaticAssertDecl>(Mem)) { 4485 // In C++1z, static_assert declarations are also fine. 4486 } else { 4487 // We have something that isn't a non-static data 4488 // member. Complain about it. 4489 unsigned DK = diag::err_anonymous_record_bad_member; 4490 if (isa<TypeDecl>(Mem)) 4491 DK = diag::err_anonymous_record_with_type; 4492 else if (isa<FunctionDecl>(Mem)) 4493 DK = diag::err_anonymous_record_with_function; 4494 else if (isa<VarDecl>(Mem)) 4495 DK = diag::err_anonymous_record_with_static; 4496 4497 // Visual C++ allows type definition in anonymous struct or union. 4498 if (getLangOpts().MicrosoftExt && 4499 DK == diag::err_anonymous_record_with_type) 4500 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4501 << Record->isUnion(); 4502 else { 4503 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4504 Invalid = true; 4505 } 4506 } 4507 } 4508 4509 // C++11 [class.union]p8 (DR1460): 4510 // At most one variant member of a union may have a 4511 // brace-or-equal-initializer. 4512 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4513 Owner->isRecord()) 4514 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4515 cast<CXXRecordDecl>(Record)); 4516 } 4517 4518 if (!Record->isUnion() && !Owner->isRecord()) { 4519 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4520 << getLangOpts().CPlusPlus; 4521 Invalid = true; 4522 } 4523 4524 // Mock up a declarator. 4525 Declarator Dc(DS, Declarator::MemberContext); 4526 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4527 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4528 4529 // Create a declaration for this anonymous struct/union. 4530 NamedDecl *Anon = nullptr; 4531 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4532 Anon = FieldDecl::Create(Context, OwningClass, 4533 DS.getLocStart(), 4534 Record->getLocation(), 4535 /*IdentifierInfo=*/nullptr, 4536 Context.getTypeDeclType(Record), 4537 TInfo, 4538 /*BitWidth=*/nullptr, /*Mutable=*/false, 4539 /*InitStyle=*/ICIS_NoInit); 4540 Anon->setAccess(AS); 4541 if (getLangOpts().CPlusPlus) 4542 FieldCollector->Add(cast<FieldDecl>(Anon)); 4543 } else { 4544 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4545 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4546 if (SCSpec == DeclSpec::SCS_mutable) { 4547 // mutable can only appear on non-static class members, so it's always 4548 // an error here 4549 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4550 Invalid = true; 4551 SC = SC_None; 4552 } 4553 4554 Anon = VarDecl::Create(Context, Owner, 4555 DS.getLocStart(), 4556 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4557 Context.getTypeDeclType(Record), 4558 TInfo, SC); 4559 4560 // Default-initialize the implicit variable. This initialization will be 4561 // trivial in almost all cases, except if a union member has an in-class 4562 // initializer: 4563 // union { int n = 0; }; 4564 ActOnUninitializedDecl(Anon); 4565 } 4566 Anon->setImplicit(); 4567 4568 // Mark this as an anonymous struct/union type. 4569 Record->setAnonymousStructOrUnion(true); 4570 4571 // Add the anonymous struct/union object to the current 4572 // context. We'll be referencing this object when we refer to one of 4573 // its members. 4574 Owner->addDecl(Anon); 4575 4576 // Inject the members of the anonymous struct/union into the owning 4577 // context and into the identifier resolver chain for name lookup 4578 // purposes. 4579 SmallVector<NamedDecl*, 2> Chain; 4580 Chain.push_back(Anon); 4581 4582 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4583 Invalid = true; 4584 4585 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4586 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4587 Decl *ManglingContextDecl; 4588 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4589 NewVD->getDeclContext(), ManglingContextDecl)) { 4590 Context.setManglingNumber( 4591 NewVD, MCtx->getManglingNumber( 4592 NewVD, getMSManglingNumber(getLangOpts(), S))); 4593 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4594 } 4595 } 4596 } 4597 4598 if (Invalid) 4599 Anon->setInvalidDecl(); 4600 4601 return Anon; 4602 } 4603 4604 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4605 /// Microsoft C anonymous structure. 4606 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4607 /// Example: 4608 /// 4609 /// struct A { int a; }; 4610 /// struct B { struct A; int b; }; 4611 /// 4612 /// void foo() { 4613 /// B var; 4614 /// var.a = 3; 4615 /// } 4616 /// 4617 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4618 RecordDecl *Record) { 4619 assert(Record && "expected a record!"); 4620 4621 // Mock up a declarator. 4622 Declarator Dc(DS, Declarator::TypeNameContext); 4623 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4624 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4625 4626 auto *ParentDecl = cast<RecordDecl>(CurContext); 4627 QualType RecTy = Context.getTypeDeclType(Record); 4628 4629 // Create a declaration for this anonymous struct. 4630 NamedDecl *Anon = FieldDecl::Create(Context, 4631 ParentDecl, 4632 DS.getLocStart(), 4633 DS.getLocStart(), 4634 /*IdentifierInfo=*/nullptr, 4635 RecTy, 4636 TInfo, 4637 /*BitWidth=*/nullptr, /*Mutable=*/false, 4638 /*InitStyle=*/ICIS_NoInit); 4639 Anon->setImplicit(); 4640 4641 // Add the anonymous struct object to the current context. 4642 CurContext->addDecl(Anon); 4643 4644 // Inject the members of the anonymous struct into the current 4645 // context and into the identifier resolver chain for name lookup 4646 // purposes. 4647 SmallVector<NamedDecl*, 2> Chain; 4648 Chain.push_back(Anon); 4649 4650 RecordDecl *RecordDef = Record->getDefinition(); 4651 if (RequireCompleteType(Anon->getLocation(), RecTy, 4652 diag::err_field_incomplete) || 4653 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4654 AS_none, Chain)) { 4655 Anon->setInvalidDecl(); 4656 ParentDecl->setInvalidDecl(); 4657 } 4658 4659 return Anon; 4660 } 4661 4662 /// GetNameForDeclarator - Determine the full declaration name for the 4663 /// given Declarator. 4664 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4665 return GetNameFromUnqualifiedId(D.getName()); 4666 } 4667 4668 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4669 DeclarationNameInfo 4670 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4671 DeclarationNameInfo NameInfo; 4672 NameInfo.setLoc(Name.StartLocation); 4673 4674 switch (Name.getKind()) { 4675 4676 case UnqualifiedId::IK_ImplicitSelfParam: 4677 case UnqualifiedId::IK_Identifier: 4678 NameInfo.setName(Name.Identifier); 4679 NameInfo.setLoc(Name.StartLocation); 4680 return NameInfo; 4681 4682 case UnqualifiedId::IK_OperatorFunctionId: 4683 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4684 Name.OperatorFunctionId.Operator)); 4685 NameInfo.setLoc(Name.StartLocation); 4686 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4687 = Name.OperatorFunctionId.SymbolLocations[0]; 4688 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4689 = Name.EndLocation.getRawEncoding(); 4690 return NameInfo; 4691 4692 case UnqualifiedId::IK_LiteralOperatorId: 4693 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4694 Name.Identifier)); 4695 NameInfo.setLoc(Name.StartLocation); 4696 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4697 return NameInfo; 4698 4699 case UnqualifiedId::IK_ConversionFunctionId: { 4700 TypeSourceInfo *TInfo; 4701 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4702 if (Ty.isNull()) 4703 return DeclarationNameInfo(); 4704 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4705 Context.getCanonicalType(Ty))); 4706 NameInfo.setLoc(Name.StartLocation); 4707 NameInfo.setNamedTypeInfo(TInfo); 4708 return NameInfo; 4709 } 4710 4711 case UnqualifiedId::IK_ConstructorName: { 4712 TypeSourceInfo *TInfo; 4713 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4714 if (Ty.isNull()) 4715 return DeclarationNameInfo(); 4716 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4717 Context.getCanonicalType(Ty))); 4718 NameInfo.setLoc(Name.StartLocation); 4719 NameInfo.setNamedTypeInfo(TInfo); 4720 return NameInfo; 4721 } 4722 4723 case UnqualifiedId::IK_ConstructorTemplateId: { 4724 // In well-formed code, we can only have a constructor 4725 // template-id that refers to the current context, so go there 4726 // to find the actual type being constructed. 4727 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4728 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4729 return DeclarationNameInfo(); 4730 4731 // Determine the type of the class being constructed. 4732 QualType CurClassType = Context.getTypeDeclType(CurClass); 4733 4734 // FIXME: Check two things: that the template-id names the same type as 4735 // CurClassType, and that the template-id does not occur when the name 4736 // was qualified. 4737 4738 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4739 Context.getCanonicalType(CurClassType))); 4740 NameInfo.setLoc(Name.StartLocation); 4741 // FIXME: should we retrieve TypeSourceInfo? 4742 NameInfo.setNamedTypeInfo(nullptr); 4743 return NameInfo; 4744 } 4745 4746 case UnqualifiedId::IK_DestructorName: { 4747 TypeSourceInfo *TInfo; 4748 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4749 if (Ty.isNull()) 4750 return DeclarationNameInfo(); 4751 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4752 Context.getCanonicalType(Ty))); 4753 NameInfo.setLoc(Name.StartLocation); 4754 NameInfo.setNamedTypeInfo(TInfo); 4755 return NameInfo; 4756 } 4757 4758 case UnqualifiedId::IK_TemplateId: { 4759 TemplateName TName = Name.TemplateId->Template.get(); 4760 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4761 return Context.getNameForTemplate(TName, TNameLoc); 4762 } 4763 4764 } // switch (Name.getKind()) 4765 4766 llvm_unreachable("Unknown name kind"); 4767 } 4768 4769 static QualType getCoreType(QualType Ty) { 4770 do { 4771 if (Ty->isPointerType() || Ty->isReferenceType()) 4772 Ty = Ty->getPointeeType(); 4773 else if (Ty->isArrayType()) 4774 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4775 else 4776 return Ty.withoutLocalFastQualifiers(); 4777 } while (true); 4778 } 4779 4780 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4781 /// and Definition have "nearly" matching parameters. This heuristic is 4782 /// used to improve diagnostics in the case where an out-of-line function 4783 /// definition doesn't match any declaration within the class or namespace. 4784 /// Also sets Params to the list of indices to the parameters that differ 4785 /// between the declaration and the definition. If hasSimilarParameters 4786 /// returns true and Params is empty, then all of the parameters match. 4787 static bool hasSimilarParameters(ASTContext &Context, 4788 FunctionDecl *Declaration, 4789 FunctionDecl *Definition, 4790 SmallVectorImpl<unsigned> &Params) { 4791 Params.clear(); 4792 if (Declaration->param_size() != Definition->param_size()) 4793 return false; 4794 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4795 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4796 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4797 4798 // The parameter types are identical 4799 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4800 continue; 4801 4802 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4803 QualType DefParamBaseTy = getCoreType(DefParamTy); 4804 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4805 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4806 4807 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4808 (DeclTyName && DeclTyName == DefTyName)) 4809 Params.push_back(Idx); 4810 else // The two parameters aren't even close 4811 return false; 4812 } 4813 4814 return true; 4815 } 4816 4817 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4818 /// declarator needs to be rebuilt in the current instantiation. 4819 /// Any bits of declarator which appear before the name are valid for 4820 /// consideration here. That's specifically the type in the decl spec 4821 /// and the base type in any member-pointer chunks. 4822 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4823 DeclarationName Name) { 4824 // The types we specifically need to rebuild are: 4825 // - typenames, typeofs, and decltypes 4826 // - types which will become injected class names 4827 // Of course, we also need to rebuild any type referencing such a 4828 // type. It's safest to just say "dependent", but we call out a 4829 // few cases here. 4830 4831 DeclSpec &DS = D.getMutableDeclSpec(); 4832 switch (DS.getTypeSpecType()) { 4833 case DeclSpec::TST_typename: 4834 case DeclSpec::TST_typeofType: 4835 case DeclSpec::TST_underlyingType: 4836 case DeclSpec::TST_atomic: { 4837 // Grab the type from the parser. 4838 TypeSourceInfo *TSI = nullptr; 4839 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4840 if (T.isNull() || !T->isDependentType()) break; 4841 4842 // Make sure there's a type source info. This isn't really much 4843 // of a waste; most dependent types should have type source info 4844 // attached already. 4845 if (!TSI) 4846 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4847 4848 // Rebuild the type in the current instantiation. 4849 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4850 if (!TSI) return true; 4851 4852 // Store the new type back in the decl spec. 4853 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4854 DS.UpdateTypeRep(LocType); 4855 break; 4856 } 4857 4858 case DeclSpec::TST_decltype: 4859 case DeclSpec::TST_typeofExpr: { 4860 Expr *E = DS.getRepAsExpr(); 4861 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4862 if (Result.isInvalid()) return true; 4863 DS.UpdateExprRep(Result.get()); 4864 break; 4865 } 4866 4867 default: 4868 // Nothing to do for these decl specs. 4869 break; 4870 } 4871 4872 // It doesn't matter what order we do this in. 4873 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4874 DeclaratorChunk &Chunk = D.getTypeObject(I); 4875 4876 // The only type information in the declarator which can come 4877 // before the declaration name is the base type of a member 4878 // pointer. 4879 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4880 continue; 4881 4882 // Rebuild the scope specifier in-place. 4883 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4884 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4885 return true; 4886 } 4887 4888 return false; 4889 } 4890 4891 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4892 D.setFunctionDefinitionKind(FDK_Declaration); 4893 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4894 4895 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4896 Dcl && Dcl->getDeclContext()->isFileContext()) 4897 Dcl->setTopLevelDeclInObjCContainer(); 4898 4899 if (getLangOpts().OpenCL) 4900 setCurrentOpenCLExtensionForDecl(Dcl); 4901 4902 return Dcl; 4903 } 4904 4905 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4906 /// If T is the name of a class, then each of the following shall have a 4907 /// name different from T: 4908 /// - every static data member of class T; 4909 /// - every member function of class T 4910 /// - every member of class T that is itself a type; 4911 /// \returns true if the declaration name violates these rules. 4912 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4913 DeclarationNameInfo NameInfo) { 4914 DeclarationName Name = NameInfo.getName(); 4915 4916 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4917 while (Record && Record->isAnonymousStructOrUnion()) 4918 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4919 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4920 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4921 return true; 4922 } 4923 4924 return false; 4925 } 4926 4927 /// \brief Diagnose a declaration whose declarator-id has the given 4928 /// nested-name-specifier. 4929 /// 4930 /// \param SS The nested-name-specifier of the declarator-id. 4931 /// 4932 /// \param DC The declaration context to which the nested-name-specifier 4933 /// resolves. 4934 /// 4935 /// \param Name The name of the entity being declared. 4936 /// 4937 /// \param Loc The location of the name of the entity being declared. 4938 /// 4939 /// \returns true if we cannot safely recover from this error, false otherwise. 4940 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4941 DeclarationName Name, 4942 SourceLocation Loc) { 4943 DeclContext *Cur = CurContext; 4944 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4945 Cur = Cur->getParent(); 4946 4947 // If the user provided a superfluous scope specifier that refers back to the 4948 // class in which the entity is already declared, diagnose and ignore it. 4949 // 4950 // class X { 4951 // void X::f(); 4952 // }; 4953 // 4954 // Note, it was once ill-formed to give redundant qualification in all 4955 // contexts, but that rule was removed by DR482. 4956 if (Cur->Equals(DC)) { 4957 if (Cur->isRecord()) { 4958 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4959 : diag::err_member_extra_qualification) 4960 << Name << FixItHint::CreateRemoval(SS.getRange()); 4961 SS.clear(); 4962 } else { 4963 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4964 } 4965 return false; 4966 } 4967 4968 // Check whether the qualifying scope encloses the scope of the original 4969 // declaration. 4970 if (!Cur->Encloses(DC)) { 4971 if (Cur->isRecord()) 4972 Diag(Loc, diag::err_member_qualification) 4973 << Name << SS.getRange(); 4974 else if (isa<TranslationUnitDecl>(DC)) 4975 Diag(Loc, diag::err_invalid_declarator_global_scope) 4976 << Name << SS.getRange(); 4977 else if (isa<FunctionDecl>(Cur)) 4978 Diag(Loc, diag::err_invalid_declarator_in_function) 4979 << Name << SS.getRange(); 4980 else if (isa<BlockDecl>(Cur)) 4981 Diag(Loc, diag::err_invalid_declarator_in_block) 4982 << Name << SS.getRange(); 4983 else 4984 Diag(Loc, diag::err_invalid_declarator_scope) 4985 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4986 4987 return true; 4988 } 4989 4990 if (Cur->isRecord()) { 4991 // Cannot qualify members within a class. 4992 Diag(Loc, diag::err_member_qualification) 4993 << Name << SS.getRange(); 4994 SS.clear(); 4995 4996 // C++ constructors and destructors with incorrect scopes can break 4997 // our AST invariants by having the wrong underlying types. If 4998 // that's the case, then drop this declaration entirely. 4999 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5000 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5001 !Context.hasSameType(Name.getCXXNameType(), 5002 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5003 return true; 5004 5005 return false; 5006 } 5007 5008 // C++11 [dcl.meaning]p1: 5009 // [...] "The nested-name-specifier of the qualified declarator-id shall 5010 // not begin with a decltype-specifer" 5011 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5012 while (SpecLoc.getPrefix()) 5013 SpecLoc = SpecLoc.getPrefix(); 5014 if (dyn_cast_or_null<DecltypeType>( 5015 SpecLoc.getNestedNameSpecifier()->getAsType())) 5016 Diag(Loc, diag::err_decltype_in_declarator) 5017 << SpecLoc.getTypeLoc().getSourceRange(); 5018 5019 return false; 5020 } 5021 5022 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5023 MultiTemplateParamsArg TemplateParamLists) { 5024 // TODO: consider using NameInfo for diagnostic. 5025 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5026 DeclarationName Name = NameInfo.getName(); 5027 5028 // All of these full declarators require an identifier. If it doesn't have 5029 // one, the ParsedFreeStandingDeclSpec action should be used. 5030 if (D.isDecompositionDeclarator()) { 5031 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5032 } else if (!Name) { 5033 if (!D.isInvalidType()) // Reject this if we think it is valid. 5034 Diag(D.getDeclSpec().getLocStart(), 5035 diag::err_declarator_need_ident) 5036 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5037 return nullptr; 5038 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5039 return nullptr; 5040 5041 // The scope passed in may not be a decl scope. Zip up the scope tree until 5042 // we find one that is. 5043 while ((S->getFlags() & Scope::DeclScope) == 0 || 5044 (S->getFlags() & Scope::TemplateParamScope) != 0) 5045 S = S->getParent(); 5046 5047 DeclContext *DC = CurContext; 5048 if (D.getCXXScopeSpec().isInvalid()) 5049 D.setInvalidType(); 5050 else if (D.getCXXScopeSpec().isSet()) { 5051 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5052 UPPC_DeclarationQualifier)) 5053 return nullptr; 5054 5055 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5056 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5057 if (!DC || isa<EnumDecl>(DC)) { 5058 // If we could not compute the declaration context, it's because the 5059 // declaration context is dependent but does not refer to a class, 5060 // class template, or class template partial specialization. Complain 5061 // and return early, to avoid the coming semantic disaster. 5062 Diag(D.getIdentifierLoc(), 5063 diag::err_template_qualified_declarator_no_match) 5064 << D.getCXXScopeSpec().getScopeRep() 5065 << D.getCXXScopeSpec().getRange(); 5066 return nullptr; 5067 } 5068 bool IsDependentContext = DC->isDependentContext(); 5069 5070 if (!IsDependentContext && 5071 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5072 return nullptr; 5073 5074 // If a class is incomplete, do not parse entities inside it. 5075 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5076 Diag(D.getIdentifierLoc(), 5077 diag::err_member_def_undefined_record) 5078 << Name << DC << D.getCXXScopeSpec().getRange(); 5079 return nullptr; 5080 } 5081 if (!D.getDeclSpec().isFriendSpecified()) { 5082 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5083 Name, D.getIdentifierLoc())) { 5084 if (DC->isRecord()) 5085 return nullptr; 5086 5087 D.setInvalidType(); 5088 } 5089 } 5090 5091 // Check whether we need to rebuild the type of the given 5092 // declaration in the current instantiation. 5093 if (EnteringContext && IsDependentContext && 5094 TemplateParamLists.size() != 0) { 5095 ContextRAII SavedContext(*this, DC); 5096 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5097 D.setInvalidType(); 5098 } 5099 } 5100 5101 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5102 QualType R = TInfo->getType(); 5103 5104 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5105 // If this is a typedef, we'll end up spewing multiple diagnostics. 5106 // Just return early; it's safer. If this is a function, let the 5107 // "constructor cannot have a return type" diagnostic handle it. 5108 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5109 return nullptr; 5110 5111 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5112 UPPC_DeclarationType)) 5113 D.setInvalidType(); 5114 5115 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5116 ForRedeclaration); 5117 5118 // See if this is a redefinition of a variable in the same scope. 5119 if (!D.getCXXScopeSpec().isSet()) { 5120 bool IsLinkageLookup = false; 5121 bool CreateBuiltins = false; 5122 5123 // If the declaration we're planning to build will be a function 5124 // or object with linkage, then look for another declaration with 5125 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5126 // 5127 // If the declaration we're planning to build will be declared with 5128 // external linkage in the translation unit, create any builtin with 5129 // the same name. 5130 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5131 /* Do nothing*/; 5132 else if (CurContext->isFunctionOrMethod() && 5133 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5134 R->isFunctionType())) { 5135 IsLinkageLookup = true; 5136 CreateBuiltins = 5137 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5138 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5139 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5140 CreateBuiltins = true; 5141 5142 if (IsLinkageLookup) 5143 Previous.clear(LookupRedeclarationWithLinkage); 5144 5145 LookupName(Previous, S, CreateBuiltins); 5146 } else { // Something like "int foo::x;" 5147 LookupQualifiedName(Previous, DC); 5148 5149 // C++ [dcl.meaning]p1: 5150 // When the declarator-id is qualified, the declaration shall refer to a 5151 // previously declared member of the class or namespace to which the 5152 // qualifier refers (or, in the case of a namespace, of an element of the 5153 // inline namespace set of that namespace (7.3.1)) or to a specialization 5154 // thereof; [...] 5155 // 5156 // Note that we already checked the context above, and that we do not have 5157 // enough information to make sure that Previous contains the declaration 5158 // we want to match. For example, given: 5159 // 5160 // class X { 5161 // void f(); 5162 // void f(float); 5163 // }; 5164 // 5165 // void X::f(int) { } // ill-formed 5166 // 5167 // In this case, Previous will point to the overload set 5168 // containing the two f's declared in X, but neither of them 5169 // matches. 5170 5171 // C++ [dcl.meaning]p1: 5172 // [...] the member shall not merely have been introduced by a 5173 // using-declaration in the scope of the class or namespace nominated by 5174 // the nested-name-specifier of the declarator-id. 5175 RemoveUsingDecls(Previous); 5176 } 5177 5178 if (Previous.isSingleResult() && 5179 Previous.getFoundDecl()->isTemplateParameter()) { 5180 // Maybe we will complain about the shadowed template parameter. 5181 if (!D.isInvalidType()) 5182 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5183 Previous.getFoundDecl()); 5184 5185 // Just pretend that we didn't see the previous declaration. 5186 Previous.clear(); 5187 } 5188 5189 // In C++, the previous declaration we find might be a tag type 5190 // (class or enum). In this case, the new declaration will hide the 5191 // tag type. Note that this does does not apply if we're declaring a 5192 // typedef (C++ [dcl.typedef]p4). 5193 if (Previous.isSingleTagDecl() && 5194 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5195 Previous.clear(); 5196 5197 // Check that there are no default arguments other than in the parameters 5198 // of a function declaration (C++ only). 5199 if (getLangOpts().CPlusPlus) 5200 CheckExtraCXXDefaultArguments(D); 5201 5202 if (D.getDeclSpec().isConceptSpecified()) { 5203 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5204 // applied only to the definition of a function template or variable 5205 // template, declared in namespace scope 5206 if (!TemplateParamLists.size()) { 5207 Diag(D.getDeclSpec().getConceptSpecLoc(), 5208 diag:: err_concept_wrong_decl_kind); 5209 return nullptr; 5210 } 5211 5212 if (!DC->getRedeclContext()->isFileContext()) { 5213 Diag(D.getIdentifierLoc(), 5214 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5215 return nullptr; 5216 } 5217 } 5218 5219 NamedDecl *New; 5220 5221 bool AddToScope = true; 5222 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5223 if (TemplateParamLists.size()) { 5224 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5225 return nullptr; 5226 } 5227 5228 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5229 } else if (R->isFunctionType()) { 5230 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5231 TemplateParamLists, 5232 AddToScope); 5233 } else { 5234 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5235 AddToScope); 5236 } 5237 5238 if (!New) 5239 return nullptr; 5240 5241 // If this has an identifier and is not a function template specialization, 5242 // add it to the scope stack. 5243 if (New->getDeclName() && AddToScope) { 5244 // Only make a locally-scoped extern declaration visible if it is the first 5245 // declaration of this entity. Qualified lookup for such an entity should 5246 // only find this declaration if there is no visible declaration of it. 5247 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5248 PushOnScopeChains(New, S, AddToContext); 5249 if (!AddToContext) 5250 CurContext->addHiddenDecl(New); 5251 } 5252 5253 if (isInOpenMPDeclareTargetContext()) 5254 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5255 5256 return New; 5257 } 5258 5259 /// Helper method to turn variable array types into constant array 5260 /// types in certain situations which would otherwise be errors (for 5261 /// GCC compatibility). 5262 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5263 ASTContext &Context, 5264 bool &SizeIsNegative, 5265 llvm::APSInt &Oversized) { 5266 // This method tries to turn a variable array into a constant 5267 // array even when the size isn't an ICE. This is necessary 5268 // for compatibility with code that depends on gcc's buggy 5269 // constant expression folding, like struct {char x[(int)(char*)2];} 5270 SizeIsNegative = false; 5271 Oversized = 0; 5272 5273 if (T->isDependentType()) 5274 return QualType(); 5275 5276 QualifierCollector Qs; 5277 const Type *Ty = Qs.strip(T); 5278 5279 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5280 QualType Pointee = PTy->getPointeeType(); 5281 QualType FixedType = 5282 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5283 Oversized); 5284 if (FixedType.isNull()) return FixedType; 5285 FixedType = Context.getPointerType(FixedType); 5286 return Qs.apply(Context, FixedType); 5287 } 5288 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5289 QualType Inner = PTy->getInnerType(); 5290 QualType FixedType = 5291 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5292 Oversized); 5293 if (FixedType.isNull()) return FixedType; 5294 FixedType = Context.getParenType(FixedType); 5295 return Qs.apply(Context, FixedType); 5296 } 5297 5298 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5299 if (!VLATy) 5300 return QualType(); 5301 // FIXME: We should probably handle this case 5302 if (VLATy->getElementType()->isVariablyModifiedType()) 5303 return QualType(); 5304 5305 llvm::APSInt Res; 5306 if (!VLATy->getSizeExpr() || 5307 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5308 return QualType(); 5309 5310 // Check whether the array size is negative. 5311 if (Res.isSigned() && Res.isNegative()) { 5312 SizeIsNegative = true; 5313 return QualType(); 5314 } 5315 5316 // Check whether the array is too large to be addressed. 5317 unsigned ActiveSizeBits 5318 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5319 Res); 5320 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5321 Oversized = Res; 5322 return QualType(); 5323 } 5324 5325 return Context.getConstantArrayType(VLATy->getElementType(), 5326 Res, ArrayType::Normal, 0); 5327 } 5328 5329 static void 5330 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5331 SrcTL = SrcTL.getUnqualifiedLoc(); 5332 DstTL = DstTL.getUnqualifiedLoc(); 5333 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5334 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5335 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5336 DstPTL.getPointeeLoc()); 5337 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5338 return; 5339 } 5340 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5341 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5342 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5343 DstPTL.getInnerLoc()); 5344 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5345 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5346 return; 5347 } 5348 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5349 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5350 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5351 TypeLoc DstElemTL = DstATL.getElementLoc(); 5352 DstElemTL.initializeFullCopy(SrcElemTL); 5353 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5354 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5355 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5356 } 5357 5358 /// Helper method to turn variable array types into constant array 5359 /// types in certain situations which would otherwise be errors (for 5360 /// GCC compatibility). 5361 static TypeSourceInfo* 5362 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5363 ASTContext &Context, 5364 bool &SizeIsNegative, 5365 llvm::APSInt &Oversized) { 5366 QualType FixedTy 5367 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5368 SizeIsNegative, Oversized); 5369 if (FixedTy.isNull()) 5370 return nullptr; 5371 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5372 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5373 FixedTInfo->getTypeLoc()); 5374 return FixedTInfo; 5375 } 5376 5377 /// \brief Register the given locally-scoped extern "C" declaration so 5378 /// that it can be found later for redeclarations. We include any extern "C" 5379 /// declaration that is not visible in the translation unit here, not just 5380 /// function-scope declarations. 5381 void 5382 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5383 if (!getLangOpts().CPlusPlus && 5384 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5385 // Don't need to track declarations in the TU in C. 5386 return; 5387 5388 // Note that we have a locally-scoped external with this name. 5389 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5390 } 5391 5392 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5393 // FIXME: We can have multiple results via __attribute__((overloadable)). 5394 auto Result = Context.getExternCContextDecl()->lookup(Name); 5395 return Result.empty() ? nullptr : *Result.begin(); 5396 } 5397 5398 /// \brief Diagnose function specifiers on a declaration of an identifier that 5399 /// does not identify a function. 5400 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5401 // FIXME: We should probably indicate the identifier in question to avoid 5402 // confusion for constructs like "virtual int a(), b;" 5403 if (DS.isVirtualSpecified()) 5404 Diag(DS.getVirtualSpecLoc(), 5405 diag::err_virtual_non_function); 5406 5407 if (DS.isExplicitSpecified()) 5408 Diag(DS.getExplicitSpecLoc(), 5409 diag::err_explicit_non_function); 5410 5411 if (DS.isNoreturnSpecified()) 5412 Diag(DS.getNoreturnSpecLoc(), 5413 diag::err_noreturn_non_function); 5414 } 5415 5416 NamedDecl* 5417 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5418 TypeSourceInfo *TInfo, LookupResult &Previous) { 5419 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5420 if (D.getCXXScopeSpec().isSet()) { 5421 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5422 << D.getCXXScopeSpec().getRange(); 5423 D.setInvalidType(); 5424 // Pretend we didn't see the scope specifier. 5425 DC = CurContext; 5426 Previous.clear(); 5427 } 5428 5429 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5430 5431 if (D.getDeclSpec().isInlineSpecified()) 5432 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5433 << getLangOpts().CPlusPlus1z; 5434 if (D.getDeclSpec().isConstexprSpecified()) 5435 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5436 << 1; 5437 if (D.getDeclSpec().isConceptSpecified()) 5438 Diag(D.getDeclSpec().getConceptSpecLoc(), 5439 diag::err_concept_wrong_decl_kind); 5440 5441 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5442 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5443 << D.getName().getSourceRange(); 5444 return nullptr; 5445 } 5446 5447 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5448 if (!NewTD) return nullptr; 5449 5450 // Handle attributes prior to checking for duplicates in MergeVarDecl 5451 ProcessDeclAttributes(S, NewTD, D); 5452 5453 CheckTypedefForVariablyModifiedType(S, NewTD); 5454 5455 bool Redeclaration = D.isRedeclaration(); 5456 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5457 D.setRedeclaration(Redeclaration); 5458 return ND; 5459 } 5460 5461 void 5462 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5463 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5464 // then it shall have block scope. 5465 // Note that variably modified types must be fixed before merging the decl so 5466 // that redeclarations will match. 5467 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5468 QualType T = TInfo->getType(); 5469 if (T->isVariablyModifiedType()) { 5470 getCurFunction()->setHasBranchProtectedScope(); 5471 5472 if (S->getFnParent() == nullptr) { 5473 bool SizeIsNegative; 5474 llvm::APSInt Oversized; 5475 TypeSourceInfo *FixedTInfo = 5476 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5477 SizeIsNegative, 5478 Oversized); 5479 if (FixedTInfo) { 5480 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5481 NewTD->setTypeSourceInfo(FixedTInfo); 5482 } else { 5483 if (SizeIsNegative) 5484 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5485 else if (T->isVariableArrayType()) 5486 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5487 else if (Oversized.getBoolValue()) 5488 Diag(NewTD->getLocation(), diag::err_array_too_large) 5489 << Oversized.toString(10); 5490 else 5491 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5492 NewTD->setInvalidDecl(); 5493 } 5494 } 5495 } 5496 } 5497 5498 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5499 /// declares a typedef-name, either using the 'typedef' type specifier or via 5500 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5501 NamedDecl* 5502 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5503 LookupResult &Previous, bool &Redeclaration) { 5504 // Merge the decl with the existing one if appropriate. If the decl is 5505 // in an outer scope, it isn't the same thing. 5506 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5507 /*AllowInlineNamespace*/false); 5508 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5509 if (!Previous.empty()) { 5510 Redeclaration = true; 5511 MergeTypedefNameDecl(S, NewTD, Previous); 5512 } 5513 5514 // If this is the C FILE type, notify the AST context. 5515 if (IdentifierInfo *II = NewTD->getIdentifier()) 5516 if (!NewTD->isInvalidDecl() && 5517 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5518 if (II->isStr("FILE")) 5519 Context.setFILEDecl(NewTD); 5520 else if (II->isStr("jmp_buf")) 5521 Context.setjmp_bufDecl(NewTD); 5522 else if (II->isStr("sigjmp_buf")) 5523 Context.setsigjmp_bufDecl(NewTD); 5524 else if (II->isStr("ucontext_t")) 5525 Context.setucontext_tDecl(NewTD); 5526 } 5527 5528 return NewTD; 5529 } 5530 5531 /// \brief Determines whether the given declaration is an out-of-scope 5532 /// previous declaration. 5533 /// 5534 /// This routine should be invoked when name lookup has found a 5535 /// previous declaration (PrevDecl) that is not in the scope where a 5536 /// new declaration by the same name is being introduced. If the new 5537 /// declaration occurs in a local scope, previous declarations with 5538 /// linkage may still be considered previous declarations (C99 5539 /// 6.2.2p4-5, C++ [basic.link]p6). 5540 /// 5541 /// \param PrevDecl the previous declaration found by name 5542 /// lookup 5543 /// 5544 /// \param DC the context in which the new declaration is being 5545 /// declared. 5546 /// 5547 /// \returns true if PrevDecl is an out-of-scope previous declaration 5548 /// for a new delcaration with the same name. 5549 static bool 5550 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5551 ASTContext &Context) { 5552 if (!PrevDecl) 5553 return false; 5554 5555 if (!PrevDecl->hasLinkage()) 5556 return false; 5557 5558 if (Context.getLangOpts().CPlusPlus) { 5559 // C++ [basic.link]p6: 5560 // If there is a visible declaration of an entity with linkage 5561 // having the same name and type, ignoring entities declared 5562 // outside the innermost enclosing namespace scope, the block 5563 // scope declaration declares that same entity and receives the 5564 // linkage of the previous declaration. 5565 DeclContext *OuterContext = DC->getRedeclContext(); 5566 if (!OuterContext->isFunctionOrMethod()) 5567 // This rule only applies to block-scope declarations. 5568 return false; 5569 5570 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5571 if (PrevOuterContext->isRecord()) 5572 // We found a member function: ignore it. 5573 return false; 5574 5575 // Find the innermost enclosing namespace for the new and 5576 // previous declarations. 5577 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5578 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5579 5580 // The previous declaration is in a different namespace, so it 5581 // isn't the same function. 5582 if (!OuterContext->Equals(PrevOuterContext)) 5583 return false; 5584 } 5585 5586 return true; 5587 } 5588 5589 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5590 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5591 if (!SS.isSet()) return; 5592 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5593 } 5594 5595 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5596 QualType type = decl->getType(); 5597 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5598 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5599 // Various kinds of declaration aren't allowed to be __autoreleasing. 5600 unsigned kind = -1U; 5601 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5602 if (var->hasAttr<BlocksAttr>()) 5603 kind = 0; // __block 5604 else if (!var->hasLocalStorage()) 5605 kind = 1; // global 5606 } else if (isa<ObjCIvarDecl>(decl)) { 5607 kind = 3; // ivar 5608 } else if (isa<FieldDecl>(decl)) { 5609 kind = 2; // field 5610 } 5611 5612 if (kind != -1U) { 5613 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5614 << kind; 5615 } 5616 } else if (lifetime == Qualifiers::OCL_None) { 5617 // Try to infer lifetime. 5618 if (!type->isObjCLifetimeType()) 5619 return false; 5620 5621 lifetime = type->getObjCARCImplicitLifetime(); 5622 type = Context.getLifetimeQualifiedType(type, lifetime); 5623 decl->setType(type); 5624 } 5625 5626 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5627 // Thread-local variables cannot have lifetime. 5628 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5629 var->getTLSKind()) { 5630 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5631 << var->getType(); 5632 return true; 5633 } 5634 } 5635 5636 return false; 5637 } 5638 5639 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5640 // Ensure that an auto decl is deduced otherwise the checks below might cache 5641 // the wrong linkage. 5642 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5643 5644 // 'weak' only applies to declarations with external linkage. 5645 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5646 if (!ND.isExternallyVisible()) { 5647 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5648 ND.dropAttr<WeakAttr>(); 5649 } 5650 } 5651 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5652 if (ND.isExternallyVisible()) { 5653 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5654 ND.dropAttr<WeakRefAttr>(); 5655 ND.dropAttr<AliasAttr>(); 5656 } 5657 } 5658 5659 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5660 if (VD->hasInit()) { 5661 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5662 assert(VD->isThisDeclarationADefinition() && 5663 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5664 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5665 VD->dropAttr<AliasAttr>(); 5666 } 5667 } 5668 } 5669 5670 // 'selectany' only applies to externally visible variable declarations. 5671 // It does not apply to functions. 5672 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5673 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5674 S.Diag(Attr->getLocation(), 5675 diag::err_attribute_selectany_non_extern_data); 5676 ND.dropAttr<SelectAnyAttr>(); 5677 } 5678 } 5679 5680 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5681 // dll attributes require external linkage. Static locals may have external 5682 // linkage but still cannot be explicitly imported or exported. 5683 auto *VD = dyn_cast<VarDecl>(&ND); 5684 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5685 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5686 << &ND << Attr; 5687 ND.setInvalidDecl(); 5688 } 5689 } 5690 5691 // Virtual functions cannot be marked as 'notail'. 5692 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5693 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5694 if (MD->isVirtual()) { 5695 S.Diag(ND.getLocation(), 5696 diag::err_invalid_attribute_on_virtual_function) 5697 << Attr; 5698 ND.dropAttr<NotTailCalledAttr>(); 5699 } 5700 } 5701 5702 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5703 NamedDecl *NewDecl, 5704 bool IsSpecialization, 5705 bool IsDefinition) { 5706 if (OldDecl->isInvalidDecl()) 5707 return; 5708 5709 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5710 OldDecl = OldTD->getTemplatedDecl(); 5711 if (!IsSpecialization) 5712 IsDefinition = false; 5713 } 5714 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5715 NewDecl = NewTD->getTemplatedDecl(); 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, local extern declarations, 5769 // qualified friend declarations or special MSVC extension: in the last case, 5770 // the declaration is treated as if it were marked dllexport. 5771 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5772 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5773 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5774 // Ignore static data because out-of-line definitions are diagnosed 5775 // separately. 5776 IsStaticDataMember = VD->isStaticDataMember(); 5777 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5778 VarDecl::DeclarationOnly; 5779 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5780 IsInline = FD->isInlined(); 5781 IsQualifiedFriend = FD->getQualifier() && 5782 FD->getFriendObjectKind() == Decl::FOK_Declared; 5783 } 5784 5785 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5786 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5787 if (IsMicrosoft && IsDefinition) { 5788 S.Diag(NewDecl->getLocation(), 5789 diag::warn_redeclaration_without_import_attribute) 5790 << NewDecl; 5791 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5792 NewDecl->dropAttr<DLLImportAttr>(); 5793 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5794 NewImportAttr->getRange(), S.Context, 5795 NewImportAttr->getSpellingListIndex())); 5796 } else { 5797 S.Diag(NewDecl->getLocation(), 5798 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5799 << NewDecl << OldImportAttr; 5800 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5801 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5802 OldDecl->dropAttr<DLLImportAttr>(); 5803 NewDecl->dropAttr<DLLImportAttr>(); 5804 } 5805 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5806 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5807 OldDecl->dropAttr<DLLImportAttr>(); 5808 NewDecl->dropAttr<DLLImportAttr>(); 5809 S.Diag(NewDecl->getLocation(), 5810 diag::warn_dllimport_dropped_from_inline_function) 5811 << NewDecl << OldImportAttr; 5812 } 5813 } 5814 5815 /// Given that we are within the definition of the given function, 5816 /// will that definition behave like C99's 'inline', where the 5817 /// definition is discarded except for optimization purposes? 5818 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5819 // Try to avoid calling GetGVALinkageForFunction. 5820 5821 // All cases of this require the 'inline' keyword. 5822 if (!FD->isInlined()) return false; 5823 5824 // This is only possible in C++ with the gnu_inline attribute. 5825 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5826 return false; 5827 5828 // Okay, go ahead and call the relatively-more-expensive function. 5829 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5830 } 5831 5832 /// Determine whether a variable is extern "C" prior to attaching 5833 /// an initializer. We can't just call isExternC() here, because that 5834 /// will also compute and cache whether the declaration is externally 5835 /// visible, which might change when we attach the initializer. 5836 /// 5837 /// This can only be used if the declaration is known to not be a 5838 /// redeclaration of an internal linkage declaration. 5839 /// 5840 /// For instance: 5841 /// 5842 /// auto x = []{}; 5843 /// 5844 /// Attaching the initializer here makes this declaration not externally 5845 /// visible, because its type has internal linkage. 5846 /// 5847 /// FIXME: This is a hack. 5848 template<typename T> 5849 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5850 if (S.getLangOpts().CPlusPlus) { 5851 // In C++, the overloadable attribute negates the effects of extern "C". 5852 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5853 return false; 5854 5855 // So do CUDA's host/device attributes. 5856 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5857 D->template hasAttr<CUDAHostAttr>())) 5858 return false; 5859 } 5860 return D->isExternC(); 5861 } 5862 5863 static bool shouldConsiderLinkage(const VarDecl *VD) { 5864 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5865 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5866 return VD->hasExternalStorage(); 5867 if (DC->isFileContext()) 5868 return true; 5869 if (DC->isRecord()) 5870 return false; 5871 llvm_unreachable("Unexpected context"); 5872 } 5873 5874 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5875 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5876 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5877 isa<OMPDeclareReductionDecl>(DC)) 5878 return true; 5879 if (DC->isRecord()) 5880 return false; 5881 llvm_unreachable("Unexpected context"); 5882 } 5883 5884 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5885 AttributeList::Kind Kind) { 5886 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5887 if (L->getKind() == Kind) 5888 return true; 5889 return false; 5890 } 5891 5892 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5893 AttributeList::Kind Kind) { 5894 // Check decl attributes on the DeclSpec. 5895 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5896 return true; 5897 5898 // Walk the declarator structure, checking decl attributes that were in a type 5899 // position to the decl itself. 5900 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5901 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5902 return true; 5903 } 5904 5905 // Finally, check attributes on the decl itself. 5906 return hasParsedAttr(S, PD.getAttributes(), Kind); 5907 } 5908 5909 /// Adjust the \c DeclContext for a function or variable that might be a 5910 /// function-local external declaration. 5911 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5912 if (!DC->isFunctionOrMethod()) 5913 return false; 5914 5915 // If this is a local extern function or variable declared within a function 5916 // template, don't add it into the enclosing namespace scope until it is 5917 // instantiated; it might have a dependent type right now. 5918 if (DC->isDependentContext()) 5919 return true; 5920 5921 // C++11 [basic.link]p7: 5922 // When a block scope declaration of an entity with linkage is not found to 5923 // refer to some other declaration, then that entity is a member of the 5924 // innermost enclosing namespace. 5925 // 5926 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5927 // semantically-enclosing namespace, not a lexically-enclosing one. 5928 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5929 DC = DC->getParent(); 5930 return true; 5931 } 5932 5933 /// \brief Returns true if given declaration has external C language linkage. 5934 static bool isDeclExternC(const Decl *D) { 5935 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5936 return FD->isExternC(); 5937 if (const auto *VD = dyn_cast<VarDecl>(D)) 5938 return VD->isExternC(); 5939 5940 llvm_unreachable("Unknown type of decl!"); 5941 } 5942 5943 NamedDecl *Sema::ActOnVariableDeclarator( 5944 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5945 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5946 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5947 QualType R = TInfo->getType(); 5948 DeclarationName Name = GetNameForDeclarator(D).getName(); 5949 5950 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5951 5952 if (D.isDecompositionDeclarator()) { 5953 AddToScope = false; 5954 // Take the name of the first declarator as our name for diagnostic 5955 // purposes. 5956 auto &Decomp = D.getDecompositionDeclarator(); 5957 if (!Decomp.bindings().empty()) { 5958 II = Decomp.bindings()[0].Name; 5959 Name = II; 5960 } 5961 } else if (!II) { 5962 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5963 << Name; 5964 return nullptr; 5965 } 5966 5967 if (getLangOpts().OpenCL) { 5968 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5969 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5970 // argument. 5971 if (R->isImageType() || R->isPipeType()) { 5972 Diag(D.getIdentifierLoc(), 5973 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5974 << R; 5975 D.setInvalidType(); 5976 return nullptr; 5977 } 5978 5979 // OpenCL v1.2 s6.9.r: 5980 // The event type cannot be used to declare a program scope variable. 5981 // OpenCL v2.0 s6.9.q: 5982 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 5983 if (NULL == S->getParent()) { 5984 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 5985 Diag(D.getIdentifierLoc(), 5986 diag::err_invalid_type_for_program_scope_var) << R; 5987 D.setInvalidType(); 5988 return nullptr; 5989 } 5990 } 5991 5992 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5993 QualType NR = R; 5994 while (NR->isPointerType()) { 5995 if (NR->isFunctionPointerType()) { 5996 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5997 D.setInvalidType(); 5998 break; 5999 } 6000 NR = NR->getPointeeType(); 6001 } 6002 6003 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6004 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6005 // half array type (unless the cl_khr_fp16 extension is enabled). 6006 if (Context.getBaseElementType(R)->isHalfType()) { 6007 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6008 D.setInvalidType(); 6009 } 6010 } 6011 6012 // OpenCL v1.2 s6.9.b p4: 6013 // The sampler type cannot be used with the __local and __global address 6014 // space qualifiers. 6015 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 6016 R.getAddressSpace() == LangAS::opencl_global)) { 6017 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6018 } 6019 6020 // OpenCL v1.2 s6.9.r: 6021 // The event type cannot be used with the __local, __constant and __global 6022 // address space qualifiers. 6023 if (R->isEventT()) { 6024 if (R.getAddressSpace()) { 6025 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6026 D.setInvalidType(); 6027 } 6028 } 6029 } 6030 6031 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6032 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6033 6034 // dllimport globals without explicit storage class are treated as extern. We 6035 // have to change the storage class this early to get the right DeclContext. 6036 if (SC == SC_None && !DC->isRecord() && 6037 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6038 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6039 SC = SC_Extern; 6040 6041 DeclContext *OriginalDC = DC; 6042 bool IsLocalExternDecl = SC == SC_Extern && 6043 adjustContextForLocalExternDecl(DC); 6044 6045 if (SCSpec == DeclSpec::SCS_mutable) { 6046 // mutable can only appear on non-static class members, so it's always 6047 // an error here 6048 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6049 D.setInvalidType(); 6050 SC = SC_None; 6051 } 6052 6053 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6054 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6055 D.getDeclSpec().getStorageClassSpecLoc())) { 6056 // In C++11, the 'register' storage class specifier is deprecated. 6057 // Suppress the warning in system macros, it's used in macros in some 6058 // popular C system headers, such as in glibc's htonl() macro. 6059 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6060 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6061 : diag::warn_deprecated_register) 6062 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6063 } 6064 6065 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6066 6067 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6068 // C99 6.9p2: The storage-class specifiers auto and register shall not 6069 // appear in the declaration specifiers in an external declaration. 6070 // Global Register+Asm is a GNU extension we support. 6071 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6072 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6073 D.setInvalidType(); 6074 } 6075 } 6076 6077 bool IsExplicitSpecialization = false; 6078 bool IsVariableTemplateSpecialization = false; 6079 bool IsPartialSpecialization = false; 6080 bool IsVariableTemplate = false; 6081 VarDecl *NewVD = nullptr; 6082 VarTemplateDecl *NewTemplate = nullptr; 6083 TemplateParameterList *TemplateParams = nullptr; 6084 if (!getLangOpts().CPlusPlus) { 6085 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6086 D.getIdentifierLoc(), II, 6087 R, TInfo, SC); 6088 6089 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6090 ParsingInitForAutoVars.insert(NewVD); 6091 6092 if (D.isInvalidType()) 6093 NewVD->setInvalidDecl(); 6094 } else { 6095 bool Invalid = false; 6096 6097 if (DC->isRecord() && !CurContext->isRecord()) { 6098 // This is an out-of-line definition of a static data member. 6099 switch (SC) { 6100 case SC_None: 6101 break; 6102 case SC_Static: 6103 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6104 diag::err_static_out_of_line) 6105 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6106 break; 6107 case SC_Auto: 6108 case SC_Register: 6109 case SC_Extern: 6110 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6111 // to names of variables declared in a block or to function parameters. 6112 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6113 // of class members 6114 6115 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6116 diag::err_storage_class_for_static_member) 6117 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6118 break; 6119 case SC_PrivateExtern: 6120 llvm_unreachable("C storage class in c++!"); 6121 } 6122 } 6123 6124 if (SC == SC_Static && CurContext->isRecord()) { 6125 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6126 if (RD->isLocalClass()) 6127 Diag(D.getIdentifierLoc(), 6128 diag::err_static_data_member_not_allowed_in_local_class) 6129 << Name << RD->getDeclName(); 6130 6131 // C++98 [class.union]p1: If a union contains a static data member, 6132 // the program is ill-formed. C++11 drops this restriction. 6133 if (RD->isUnion()) 6134 Diag(D.getIdentifierLoc(), 6135 getLangOpts().CPlusPlus11 6136 ? diag::warn_cxx98_compat_static_data_member_in_union 6137 : diag::ext_static_data_member_in_union) << Name; 6138 // We conservatively disallow static data members in anonymous structs. 6139 else if (!RD->getDeclName()) 6140 Diag(D.getIdentifierLoc(), 6141 diag::err_static_data_member_not_allowed_in_anon_struct) 6142 << Name << RD->isUnion(); 6143 } 6144 } 6145 6146 // Match up the template parameter lists with the scope specifier, then 6147 // determine whether we have a template or a template specialization. 6148 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6149 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6150 D.getCXXScopeSpec(), 6151 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6152 ? D.getName().TemplateId 6153 : nullptr, 6154 TemplateParamLists, 6155 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6156 6157 if (TemplateParams) { 6158 if (!TemplateParams->size() && 6159 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6160 // There is an extraneous 'template<>' for this variable. Complain 6161 // about it, but allow the declaration of the variable. 6162 Diag(TemplateParams->getTemplateLoc(), 6163 diag::err_template_variable_noparams) 6164 << II 6165 << SourceRange(TemplateParams->getTemplateLoc(), 6166 TemplateParams->getRAngleLoc()); 6167 TemplateParams = nullptr; 6168 } else { 6169 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6170 // This is an explicit specialization or a partial specialization. 6171 // FIXME: Check that we can declare a specialization here. 6172 IsVariableTemplateSpecialization = true; 6173 IsPartialSpecialization = TemplateParams->size() > 0; 6174 } else { // if (TemplateParams->size() > 0) 6175 // This is a template declaration. 6176 IsVariableTemplate = true; 6177 6178 // Check that we can declare a template here. 6179 if (CheckTemplateDeclScope(S, TemplateParams)) 6180 return nullptr; 6181 6182 // Only C++1y supports variable templates (N3651). 6183 Diag(D.getIdentifierLoc(), 6184 getLangOpts().CPlusPlus14 6185 ? diag::warn_cxx11_compat_variable_template 6186 : diag::ext_variable_template); 6187 } 6188 } 6189 } else { 6190 assert( 6191 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6192 "should have a 'template<>' for this decl"); 6193 } 6194 6195 if (IsVariableTemplateSpecialization) { 6196 SourceLocation TemplateKWLoc = 6197 TemplateParamLists.size() > 0 6198 ? TemplateParamLists[0]->getTemplateLoc() 6199 : SourceLocation(); 6200 DeclResult Res = ActOnVarTemplateSpecialization( 6201 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6202 IsPartialSpecialization); 6203 if (Res.isInvalid()) 6204 return nullptr; 6205 NewVD = cast<VarDecl>(Res.get()); 6206 AddToScope = false; 6207 } else if (D.isDecompositionDeclarator()) { 6208 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6209 D.getIdentifierLoc(), R, TInfo, SC, 6210 Bindings); 6211 } else 6212 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6213 D.getIdentifierLoc(), II, R, TInfo, SC); 6214 6215 // If this is supposed to be a variable template, create it as such. 6216 if (IsVariableTemplate) { 6217 NewTemplate = 6218 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6219 TemplateParams, NewVD); 6220 NewVD->setDescribedVarTemplate(NewTemplate); 6221 } 6222 6223 // If this decl has an auto type in need of deduction, make a note of the 6224 // Decl so we can diagnose uses of it in its own initializer. 6225 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6226 ParsingInitForAutoVars.insert(NewVD); 6227 6228 if (D.isInvalidType() || Invalid) { 6229 NewVD->setInvalidDecl(); 6230 if (NewTemplate) 6231 NewTemplate->setInvalidDecl(); 6232 } 6233 6234 SetNestedNameSpecifier(NewVD, D); 6235 6236 // If we have any template parameter lists that don't directly belong to 6237 // the variable (matching the scope specifier), store them. 6238 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6239 if (TemplateParamLists.size() > VDTemplateParamLists) 6240 NewVD->setTemplateParameterListsInfo( 6241 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6242 6243 if (D.getDeclSpec().isConstexprSpecified()) { 6244 NewVD->setConstexpr(true); 6245 // C++1z [dcl.spec.constexpr]p1: 6246 // A static data member declared with the constexpr specifier is 6247 // implicitly an inline variable. 6248 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6249 NewVD->setImplicitlyInline(); 6250 } 6251 6252 if (D.getDeclSpec().isConceptSpecified()) { 6253 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6254 VTD->setConcept(); 6255 6256 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6257 // be declared with the thread_local, inline, friend, or constexpr 6258 // specifiers, [...] 6259 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6260 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6261 diag::err_concept_decl_invalid_specifiers) 6262 << 0 << 0; 6263 NewVD->setInvalidDecl(true); 6264 } 6265 6266 if (D.getDeclSpec().isConstexprSpecified()) { 6267 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6268 diag::err_concept_decl_invalid_specifiers) 6269 << 0 << 3; 6270 NewVD->setInvalidDecl(true); 6271 } 6272 6273 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6274 // applied only to the definition of a function template or variable 6275 // template, declared in namespace scope. 6276 if (IsVariableTemplateSpecialization) { 6277 Diag(D.getDeclSpec().getConceptSpecLoc(), 6278 diag::err_concept_specified_specialization) 6279 << (IsPartialSpecialization ? 2 : 1); 6280 } 6281 6282 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6283 // following restrictions: 6284 // - The declared type shall have the type bool. 6285 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6286 !NewVD->isInvalidDecl()) { 6287 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6288 NewVD->setInvalidDecl(true); 6289 } 6290 } 6291 } 6292 6293 if (D.getDeclSpec().isInlineSpecified()) { 6294 if (!getLangOpts().CPlusPlus) { 6295 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6296 << 0; 6297 } else if (CurContext->isFunctionOrMethod()) { 6298 // 'inline' is not allowed on block scope variable declaration. 6299 Diag(D.getDeclSpec().getInlineSpecLoc(), 6300 diag::err_inline_declaration_block_scope) << Name 6301 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6302 } else { 6303 Diag(D.getDeclSpec().getInlineSpecLoc(), 6304 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6305 : diag::ext_inline_variable); 6306 NewVD->setInlineSpecified(); 6307 } 6308 } 6309 6310 // Set the lexical context. If the declarator has a C++ scope specifier, the 6311 // lexical context will be different from the semantic context. 6312 NewVD->setLexicalDeclContext(CurContext); 6313 if (NewTemplate) 6314 NewTemplate->setLexicalDeclContext(CurContext); 6315 6316 if (IsLocalExternDecl) { 6317 if (D.isDecompositionDeclarator()) 6318 for (auto *B : Bindings) 6319 B->setLocalExternDecl(); 6320 else 6321 NewVD->setLocalExternDecl(); 6322 } 6323 6324 bool EmitTLSUnsupportedError = false; 6325 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6326 // C++11 [dcl.stc]p4: 6327 // When thread_local is applied to a variable of block scope the 6328 // storage-class-specifier static is implied if it does not appear 6329 // explicitly. 6330 // Core issue: 'static' is not implied if the variable is declared 6331 // 'extern'. 6332 if (NewVD->hasLocalStorage() && 6333 (SCSpec != DeclSpec::SCS_unspecified || 6334 TSCS != DeclSpec::TSCS_thread_local || 6335 !DC->isFunctionOrMethod())) 6336 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6337 diag::err_thread_non_global) 6338 << DeclSpec::getSpecifierName(TSCS); 6339 else if (!Context.getTargetInfo().isTLSSupported()) { 6340 if (getLangOpts().CUDA) { 6341 // Postpone error emission until we've collected attributes required to 6342 // figure out whether it's a host or device variable and whether the 6343 // error should be ignored. 6344 EmitTLSUnsupportedError = true; 6345 // We still need to mark the variable as TLS so it shows up in AST with 6346 // proper storage class for other tools to use even if we're not going 6347 // to emit any code for it. 6348 NewVD->setTSCSpec(TSCS); 6349 } else 6350 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6351 diag::err_thread_unsupported); 6352 } else 6353 NewVD->setTSCSpec(TSCS); 6354 } 6355 6356 // C99 6.7.4p3 6357 // An inline definition of a function with external linkage shall 6358 // not contain a definition of a modifiable object with static or 6359 // thread storage duration... 6360 // We only apply this when the function is required to be defined 6361 // elsewhere, i.e. when the function is not 'extern inline'. Note 6362 // that a local variable with thread storage duration still has to 6363 // be marked 'static'. Also note that it's possible to get these 6364 // semantics in C++ using __attribute__((gnu_inline)). 6365 if (SC == SC_Static && S->getFnParent() != nullptr && 6366 !NewVD->getType().isConstQualified()) { 6367 FunctionDecl *CurFD = getCurFunctionDecl(); 6368 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6369 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6370 diag::warn_static_local_in_extern_inline); 6371 MaybeSuggestAddingStaticToDecl(CurFD); 6372 } 6373 } 6374 6375 if (D.getDeclSpec().isModulePrivateSpecified()) { 6376 if (IsVariableTemplateSpecialization) 6377 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6378 << (IsPartialSpecialization ? 1 : 0) 6379 << FixItHint::CreateRemoval( 6380 D.getDeclSpec().getModulePrivateSpecLoc()); 6381 else if (IsExplicitSpecialization) 6382 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6383 << 2 6384 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6385 else if (NewVD->hasLocalStorage()) 6386 Diag(NewVD->getLocation(), diag::err_module_private_local) 6387 << 0 << NewVD->getDeclName() 6388 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6389 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6390 else { 6391 NewVD->setModulePrivate(); 6392 if (NewTemplate) 6393 NewTemplate->setModulePrivate(); 6394 for (auto *B : Bindings) 6395 B->setModulePrivate(); 6396 } 6397 } 6398 6399 // Handle attributes prior to checking for duplicates in MergeVarDecl 6400 ProcessDeclAttributes(S, NewVD, D); 6401 6402 if (getLangOpts().CUDA) { 6403 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6404 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6405 diag::err_thread_unsupported); 6406 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6407 // storage [duration]." 6408 if (SC == SC_None && S->getFnParent() != nullptr && 6409 (NewVD->hasAttr<CUDASharedAttr>() || 6410 NewVD->hasAttr<CUDAConstantAttr>())) { 6411 NewVD->setStorageClass(SC_Static); 6412 } 6413 } 6414 6415 // Ensure that dllimport globals without explicit storage class are treated as 6416 // extern. The storage class is set above using parsed attributes. Now we can 6417 // check the VarDecl itself. 6418 assert(!NewVD->hasAttr<DLLImportAttr>() || 6419 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6420 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6421 6422 // In auto-retain/release, infer strong retension for variables of 6423 // retainable type. 6424 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6425 NewVD->setInvalidDecl(); 6426 6427 // Handle GNU asm-label extension (encoded as an attribute). 6428 if (Expr *E = (Expr*)D.getAsmLabel()) { 6429 // The parser guarantees this is a string. 6430 StringLiteral *SE = cast<StringLiteral>(E); 6431 StringRef Label = SE->getString(); 6432 if (S->getFnParent() != nullptr) { 6433 switch (SC) { 6434 case SC_None: 6435 case SC_Auto: 6436 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6437 break; 6438 case SC_Register: 6439 // Local Named register 6440 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6441 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6442 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6443 break; 6444 case SC_Static: 6445 case SC_Extern: 6446 case SC_PrivateExtern: 6447 break; 6448 } 6449 } else if (SC == SC_Register) { 6450 // Global Named register 6451 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6452 const auto &TI = Context.getTargetInfo(); 6453 bool HasSizeMismatch; 6454 6455 if (!TI.isValidGCCRegisterName(Label)) 6456 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6457 else if (!TI.validateGlobalRegisterVariable(Label, 6458 Context.getTypeSize(R), 6459 HasSizeMismatch)) 6460 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6461 else if (HasSizeMismatch) 6462 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6463 } 6464 6465 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6466 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6467 NewVD->setInvalidDecl(true); 6468 } 6469 } 6470 6471 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6472 Context, Label, 0)); 6473 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6474 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6475 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6476 if (I != ExtnameUndeclaredIdentifiers.end()) { 6477 if (isDeclExternC(NewVD)) { 6478 NewVD->addAttr(I->second); 6479 ExtnameUndeclaredIdentifiers.erase(I); 6480 } else 6481 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6482 << /*Variable*/1 << NewVD; 6483 } 6484 } 6485 6486 // Find the shadowed declaration before filtering for scope. 6487 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6488 ? getShadowedDeclaration(NewVD, Previous) 6489 : nullptr; 6490 6491 // Don't consider existing declarations that are in a different 6492 // scope and are out-of-semantic-context declarations (if the new 6493 // declaration has linkage). 6494 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6495 D.getCXXScopeSpec().isNotEmpty() || 6496 IsExplicitSpecialization || 6497 IsVariableTemplateSpecialization); 6498 6499 // Check whether the previous declaration is in the same block scope. This 6500 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6501 if (getLangOpts().CPlusPlus && 6502 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6503 NewVD->setPreviousDeclInSameBlockScope( 6504 Previous.isSingleResult() && !Previous.isShadowed() && 6505 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6506 6507 if (!getLangOpts().CPlusPlus) { 6508 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6509 } else { 6510 // If this is an explicit specialization of a static data member, check it. 6511 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6512 CheckMemberSpecialization(NewVD, Previous)) 6513 NewVD->setInvalidDecl(); 6514 6515 // Merge the decl with the existing one if appropriate. 6516 if (!Previous.empty()) { 6517 if (Previous.isSingleResult() && 6518 isa<FieldDecl>(Previous.getFoundDecl()) && 6519 D.getCXXScopeSpec().isSet()) { 6520 // The user tried to define a non-static data member 6521 // out-of-line (C++ [dcl.meaning]p1). 6522 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6523 << D.getCXXScopeSpec().getRange(); 6524 Previous.clear(); 6525 NewVD->setInvalidDecl(); 6526 } 6527 } else if (D.getCXXScopeSpec().isSet()) { 6528 // No previous declaration in the qualifying scope. 6529 Diag(D.getIdentifierLoc(), diag::err_no_member) 6530 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6531 << D.getCXXScopeSpec().getRange(); 6532 NewVD->setInvalidDecl(); 6533 } 6534 6535 if (!IsVariableTemplateSpecialization) 6536 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6537 6538 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6539 // an explicit specialization (14.8.3) or a partial specialization of a 6540 // concept definition. 6541 if (IsVariableTemplateSpecialization && 6542 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6543 Previous.isSingleResult()) { 6544 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6545 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6546 if (VarTmpl->isConcept()) { 6547 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6548 << 1 /*variable*/ 6549 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6550 : 1 /*explicitly specialized*/); 6551 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6552 NewVD->setInvalidDecl(); 6553 } 6554 } 6555 } 6556 6557 if (NewTemplate) { 6558 VarTemplateDecl *PrevVarTemplate = 6559 NewVD->getPreviousDecl() 6560 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6561 : nullptr; 6562 6563 // Check the template parameter list of this declaration, possibly 6564 // merging in the template parameter list from the previous variable 6565 // template declaration. 6566 if (CheckTemplateParameterList( 6567 TemplateParams, 6568 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6569 : nullptr, 6570 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6571 DC->isDependentContext()) 6572 ? TPC_ClassTemplateMember 6573 : TPC_VarTemplate)) 6574 NewVD->setInvalidDecl(); 6575 6576 // If we are providing an explicit specialization of a static variable 6577 // template, make a note of that. 6578 if (PrevVarTemplate && 6579 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6580 PrevVarTemplate->setMemberSpecialization(); 6581 } 6582 } 6583 6584 // Diagnose shadowed variables iff this isn't a redeclaration. 6585 if (ShadowedDecl && !D.isRedeclaration()) 6586 CheckShadow(NewVD, ShadowedDecl, Previous); 6587 6588 ProcessPragmaWeak(S, NewVD); 6589 6590 // If this is the first declaration of an extern C variable, update 6591 // the map of such variables. 6592 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6593 isIncompleteDeclExternC(*this, NewVD)) 6594 RegisterLocallyScopedExternCDecl(NewVD, S); 6595 6596 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6597 Decl *ManglingContextDecl; 6598 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6599 NewVD->getDeclContext(), ManglingContextDecl)) { 6600 Context.setManglingNumber( 6601 NewVD, MCtx->getManglingNumber( 6602 NewVD, getMSManglingNumber(getLangOpts(), S))); 6603 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6604 } 6605 } 6606 6607 // Special handling of variable named 'main'. 6608 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6609 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6610 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6611 6612 // C++ [basic.start.main]p3 6613 // A program that declares a variable main at global scope is ill-formed. 6614 if (getLangOpts().CPlusPlus) 6615 Diag(D.getLocStart(), diag::err_main_global_variable); 6616 6617 // In C, and external-linkage variable named main results in undefined 6618 // behavior. 6619 else if (NewVD->hasExternalFormalLinkage()) 6620 Diag(D.getLocStart(), diag::warn_main_redefined); 6621 } 6622 6623 if (D.isRedeclaration() && !Previous.empty()) { 6624 checkDLLAttributeRedeclaration( 6625 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6626 IsExplicitSpecialization, D.isFunctionDefinition()); 6627 } 6628 6629 if (NewTemplate) { 6630 if (NewVD->isInvalidDecl()) 6631 NewTemplate->setInvalidDecl(); 6632 ActOnDocumentableDecl(NewTemplate); 6633 return NewTemplate; 6634 } 6635 6636 return NewVD; 6637 } 6638 6639 /// Enum describing the %select options in diag::warn_decl_shadow. 6640 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6641 6642 /// Determine what kind of declaration we're shadowing. 6643 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6644 const DeclContext *OldDC) { 6645 if (isa<RecordDecl>(OldDC)) 6646 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6647 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6648 } 6649 6650 /// Return the location of the capture if the given lambda captures the given 6651 /// variable \p VD, or an invalid source location otherwise. 6652 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6653 const VarDecl *VD) { 6654 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6655 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6656 return Capture.getLocation(); 6657 } 6658 return SourceLocation(); 6659 } 6660 6661 /// \brief Return the declaration shadowed by the given variable \p D, or null 6662 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6663 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6664 const LookupResult &R) { 6665 // Return if warning is ignored. 6666 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6667 return nullptr; 6668 6669 // Don't diagnose declarations at file scope. 6670 if (D->hasGlobalStorage()) 6671 return nullptr; 6672 6673 // Only diagnose if we're shadowing an unambiguous field or variable. 6674 if (R.getResultKind() != LookupResult::Found) 6675 return nullptr; 6676 6677 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6678 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6679 ? ShadowedDecl 6680 : nullptr; 6681 } 6682 6683 /// \brief Diagnose variable or built-in function shadowing. Implements 6684 /// -Wshadow. 6685 /// 6686 /// This method is called whenever a VarDecl is added to a "useful" 6687 /// scope. 6688 /// 6689 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6690 /// \param R the lookup of the name 6691 /// 6692 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl, 6693 const LookupResult &R) { 6694 DeclContext *NewDC = D->getDeclContext(); 6695 6696 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6697 // Fields are not shadowed by variables in C++ static methods. 6698 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6699 if (MD->isStatic()) 6700 return; 6701 6702 // Fields shadowed by constructor parameters are a special case. Usually 6703 // the constructor initializes the field with the parameter. 6704 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6705 // Remember that this was shadowed so we can either warn about its 6706 // modification or its existence depending on warning settings. 6707 D = D->getCanonicalDecl(); 6708 ShadowingDecls.insert({D, FD}); 6709 return; 6710 } 6711 } 6712 6713 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6714 if (shadowedVar->isExternC()) { 6715 // For shadowing external vars, make sure that we point to the global 6716 // declaration, not a locally scoped extern declaration. 6717 for (auto I : shadowedVar->redecls()) 6718 if (I->isFileVarDecl()) { 6719 ShadowedDecl = I; 6720 break; 6721 } 6722 } 6723 6724 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6725 6726 unsigned WarningDiag = diag::warn_decl_shadow; 6727 SourceLocation CaptureLoc; 6728 if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) { 6729 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6730 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6731 if (RD->getLambdaCaptureDefault() == LCD_None) { 6732 // Try to avoid warnings for lambdas with an explicit capture list. 6733 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6734 // Warn only when the lambda captures the shadowed decl explicitly. 6735 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6736 if (CaptureLoc.isInvalid()) 6737 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6738 } else { 6739 // Remember that this was shadowed so we can avoid the warning if the 6740 // shadowed decl isn't captured and the warning settings allow it. 6741 cast<LambdaScopeInfo>(getCurFunction()) 6742 ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)}); 6743 return; 6744 } 6745 } 6746 } 6747 } 6748 6749 // Only warn about certain kinds of shadowing for class members. 6750 if (NewDC && NewDC->isRecord()) { 6751 // In particular, don't warn about shadowing non-class members. 6752 if (!OldDC->isRecord()) 6753 return; 6754 6755 // TODO: should we warn about static data members shadowing 6756 // static data members from base classes? 6757 6758 // TODO: don't diagnose for inaccessible shadowed members. 6759 // This is hard to do perfectly because we might friend the 6760 // shadowing context, but that's just a false negative. 6761 } 6762 6763 6764 DeclarationName Name = R.getLookupName(); 6765 6766 // Emit warning and note. 6767 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6768 return; 6769 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6770 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6771 if (!CaptureLoc.isInvalid()) 6772 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6773 << Name << /*explicitly*/ 1; 6774 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6775 } 6776 6777 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6778 /// when these variables are captured by the lambda. 6779 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6780 for (const auto &Shadow : LSI->ShadowingDecls) { 6781 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 6782 // Try to avoid the warning when the shadowed decl isn't captured. 6783 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 6784 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6785 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 6786 ? diag::warn_decl_shadow_uncaptured_local 6787 : diag::warn_decl_shadow) 6788 << Shadow.VD->getDeclName() 6789 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 6790 if (!CaptureLoc.isInvalid()) 6791 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6792 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 6793 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6794 } 6795 } 6796 6797 /// \brief Check -Wshadow without the advantage of a previous lookup. 6798 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6799 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6800 return; 6801 6802 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6803 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6804 LookupName(R, S); 6805 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 6806 CheckShadow(D, ShadowedDecl, R); 6807 } 6808 6809 /// Check if 'E', which is an expression that is about to be modified, refers 6810 /// to a constructor parameter that shadows a field. 6811 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6812 // Quickly ignore expressions that can't be shadowing ctor parameters. 6813 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6814 return; 6815 E = E->IgnoreParenImpCasts(); 6816 auto *DRE = dyn_cast<DeclRefExpr>(E); 6817 if (!DRE) 6818 return; 6819 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6820 auto I = ShadowingDecls.find(D); 6821 if (I == ShadowingDecls.end()) 6822 return; 6823 const NamedDecl *ShadowedDecl = I->second; 6824 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6825 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6826 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6827 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6828 6829 // Avoid issuing multiple warnings about the same decl. 6830 ShadowingDecls.erase(I); 6831 } 6832 6833 /// Check for conflict between this global or extern "C" declaration and 6834 /// previous global or extern "C" declarations. This is only used in C++. 6835 template<typename T> 6836 static bool checkGlobalOrExternCConflict( 6837 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6838 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6839 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6840 6841 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6842 // The common case: this global doesn't conflict with any extern "C" 6843 // declaration. 6844 return false; 6845 } 6846 6847 if (Prev) { 6848 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6849 // Both the old and new declarations have C language linkage. This is a 6850 // redeclaration. 6851 Previous.clear(); 6852 Previous.addDecl(Prev); 6853 return true; 6854 } 6855 6856 // This is a global, non-extern "C" declaration, and there is a previous 6857 // non-global extern "C" declaration. Diagnose if this is a variable 6858 // declaration. 6859 if (!isa<VarDecl>(ND)) 6860 return false; 6861 } else { 6862 // The declaration is extern "C". Check for any declaration in the 6863 // translation unit which might conflict. 6864 if (IsGlobal) { 6865 // We have already performed the lookup into the translation unit. 6866 IsGlobal = false; 6867 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6868 I != E; ++I) { 6869 if (isa<VarDecl>(*I)) { 6870 Prev = *I; 6871 break; 6872 } 6873 } 6874 } else { 6875 DeclContext::lookup_result R = 6876 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6877 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6878 I != E; ++I) { 6879 if (isa<VarDecl>(*I)) { 6880 Prev = *I; 6881 break; 6882 } 6883 // FIXME: If we have any other entity with this name in global scope, 6884 // the declaration is ill-formed, but that is a defect: it breaks the 6885 // 'stat' hack, for instance. Only variables can have mangled name 6886 // clashes with extern "C" declarations, so only they deserve a 6887 // diagnostic. 6888 } 6889 } 6890 6891 if (!Prev) 6892 return false; 6893 } 6894 6895 // Use the first declaration's location to ensure we point at something which 6896 // is lexically inside an extern "C" linkage-spec. 6897 assert(Prev && "should have found a previous declaration to diagnose"); 6898 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6899 Prev = FD->getFirstDecl(); 6900 else 6901 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6902 6903 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6904 << IsGlobal << ND; 6905 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6906 << IsGlobal; 6907 return false; 6908 } 6909 6910 /// Apply special rules for handling extern "C" declarations. Returns \c true 6911 /// if we have found that this is a redeclaration of some prior entity. 6912 /// 6913 /// Per C++ [dcl.link]p6: 6914 /// Two declarations [for a function or variable] with C language linkage 6915 /// with the same name that appear in different scopes refer to the same 6916 /// [entity]. An entity with C language linkage shall not be declared with 6917 /// the same name as an entity in global scope. 6918 template<typename T> 6919 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6920 LookupResult &Previous) { 6921 if (!S.getLangOpts().CPlusPlus) { 6922 // In C, when declaring a global variable, look for a corresponding 'extern' 6923 // variable declared in function scope. We don't need this in C++, because 6924 // we find local extern decls in the surrounding file-scope DeclContext. 6925 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6926 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6927 Previous.clear(); 6928 Previous.addDecl(Prev); 6929 return true; 6930 } 6931 } 6932 return false; 6933 } 6934 6935 // A declaration in the translation unit can conflict with an extern "C" 6936 // declaration. 6937 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6938 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6939 6940 // An extern "C" declaration can conflict with a declaration in the 6941 // translation unit or can be a redeclaration of an extern "C" declaration 6942 // in another scope. 6943 if (isIncompleteDeclExternC(S,ND)) 6944 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6945 6946 // Neither global nor extern "C": nothing to do. 6947 return false; 6948 } 6949 6950 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6951 // If the decl is already known invalid, don't check it. 6952 if (NewVD->isInvalidDecl()) 6953 return; 6954 6955 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6956 QualType T = TInfo->getType(); 6957 6958 // Defer checking an 'auto' type until its initializer is attached. 6959 if (T->isUndeducedType()) 6960 return; 6961 6962 if (NewVD->hasAttrs()) 6963 CheckAlignasUnderalignment(NewVD); 6964 6965 if (T->isObjCObjectType()) { 6966 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6967 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6968 T = Context.getObjCObjectPointerType(T); 6969 NewVD->setType(T); 6970 } 6971 6972 // Emit an error if an address space was applied to decl with local storage. 6973 // This includes arrays of objects with address space qualifiers, but not 6974 // automatic variables that point to other address spaces. 6975 // ISO/IEC TR 18037 S5.1.2 6976 if (!getLangOpts().OpenCL 6977 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6978 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6979 NewVD->setInvalidDecl(); 6980 return; 6981 } 6982 6983 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6984 // scope. 6985 if (getLangOpts().OpenCLVersion == 120 && 6986 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 6987 NewVD->isStaticLocal()) { 6988 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6989 NewVD->setInvalidDecl(); 6990 return; 6991 } 6992 6993 if (getLangOpts().OpenCL) { 6994 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6995 if (NewVD->hasAttr<BlocksAttr>()) { 6996 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6997 return; 6998 } 6999 7000 if (T->isBlockPointerType()) { 7001 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7002 // can't use 'extern' storage class. 7003 if (!T.isConstQualified()) { 7004 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7005 << 0 /*const*/; 7006 NewVD->setInvalidDecl(); 7007 return; 7008 } 7009 if (NewVD->hasExternalStorage()) { 7010 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7011 NewVD->setInvalidDecl(); 7012 return; 7013 } 7014 } 7015 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7016 // __constant address space. 7017 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7018 // variables inside a function can also be declared in the global 7019 // address space. 7020 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7021 NewVD->hasExternalStorage()) { 7022 if (!T->isSamplerT() && 7023 !(T.getAddressSpace() == LangAS::opencl_constant || 7024 (T.getAddressSpace() == LangAS::opencl_global && 7025 getLangOpts().OpenCLVersion == 200))) { 7026 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7027 if (getLangOpts().OpenCLVersion == 200) 7028 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7029 << Scope << "global or constant"; 7030 else 7031 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7032 << Scope << "constant"; 7033 NewVD->setInvalidDecl(); 7034 return; 7035 } 7036 } else { 7037 if (T.getAddressSpace() == LangAS::opencl_global) { 7038 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7039 << 1 /*is any function*/ << "global"; 7040 NewVD->setInvalidDecl(); 7041 return; 7042 } 7043 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7044 // in functions. 7045 if (T.getAddressSpace() == LangAS::opencl_constant || 7046 T.getAddressSpace() == LangAS::opencl_local) { 7047 FunctionDecl *FD = getCurFunctionDecl(); 7048 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7049 if (T.getAddressSpace() == LangAS::opencl_constant) 7050 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7051 << 0 /*non-kernel only*/ << "constant"; 7052 else 7053 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7054 << 0 /*non-kernel only*/ << "local"; 7055 NewVD->setInvalidDecl(); 7056 return; 7057 } 7058 } 7059 } 7060 } 7061 7062 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7063 && !NewVD->hasAttr<BlocksAttr>()) { 7064 if (getLangOpts().getGC() != LangOptions::NonGC) 7065 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7066 else { 7067 assert(!getLangOpts().ObjCAutoRefCount); 7068 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7069 } 7070 } 7071 7072 bool isVM = T->isVariablyModifiedType(); 7073 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7074 NewVD->hasAttr<BlocksAttr>()) 7075 getCurFunction()->setHasBranchProtectedScope(); 7076 7077 if ((isVM && NewVD->hasLinkage()) || 7078 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7079 bool SizeIsNegative; 7080 llvm::APSInt Oversized; 7081 TypeSourceInfo *FixedTInfo = 7082 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7083 SizeIsNegative, Oversized); 7084 if (!FixedTInfo && T->isVariableArrayType()) { 7085 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7086 // FIXME: This won't give the correct result for 7087 // int a[10][n]; 7088 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7089 7090 if (NewVD->isFileVarDecl()) 7091 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7092 << SizeRange; 7093 else if (NewVD->isStaticLocal()) 7094 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7095 << SizeRange; 7096 else 7097 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7098 << SizeRange; 7099 NewVD->setInvalidDecl(); 7100 return; 7101 } 7102 7103 if (!FixedTInfo) { 7104 if (NewVD->isFileVarDecl()) 7105 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7106 else 7107 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7108 NewVD->setInvalidDecl(); 7109 return; 7110 } 7111 7112 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7113 NewVD->setType(FixedTInfo->getType()); 7114 NewVD->setTypeSourceInfo(FixedTInfo); 7115 } 7116 7117 if (T->isVoidType()) { 7118 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7119 // of objects and functions. 7120 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7121 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7122 << T; 7123 NewVD->setInvalidDecl(); 7124 return; 7125 } 7126 } 7127 7128 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7129 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7130 NewVD->setInvalidDecl(); 7131 return; 7132 } 7133 7134 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7135 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7136 NewVD->setInvalidDecl(); 7137 return; 7138 } 7139 7140 if (NewVD->isConstexpr() && !T->isDependentType() && 7141 RequireLiteralType(NewVD->getLocation(), T, 7142 diag::err_constexpr_var_non_literal)) { 7143 NewVD->setInvalidDecl(); 7144 return; 7145 } 7146 } 7147 7148 /// \brief Perform semantic checking on a newly-created variable 7149 /// declaration. 7150 /// 7151 /// This routine performs all of the type-checking required for a 7152 /// variable declaration once it has been built. It is used both to 7153 /// check variables after they have been parsed and their declarators 7154 /// have been translated into a declaration, and to check variables 7155 /// that have been instantiated from a template. 7156 /// 7157 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7158 /// 7159 /// Returns true if the variable declaration is a redeclaration. 7160 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7161 CheckVariableDeclarationType(NewVD); 7162 7163 // If the decl is already known invalid, don't check it. 7164 if (NewVD->isInvalidDecl()) 7165 return false; 7166 7167 // If we did not find anything by this name, look for a non-visible 7168 // extern "C" declaration with the same name. 7169 if (Previous.empty() && 7170 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7171 Previous.setShadowed(); 7172 7173 if (!Previous.empty()) { 7174 MergeVarDecl(NewVD, Previous); 7175 return true; 7176 } 7177 return false; 7178 } 7179 7180 namespace { 7181 struct FindOverriddenMethod { 7182 Sema *S; 7183 CXXMethodDecl *Method; 7184 7185 /// Member lookup function that determines whether a given C++ 7186 /// method overrides a method in a base class, to be used with 7187 /// CXXRecordDecl::lookupInBases(). 7188 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7189 RecordDecl *BaseRecord = 7190 Specifier->getType()->getAs<RecordType>()->getDecl(); 7191 7192 DeclarationName Name = Method->getDeclName(); 7193 7194 // FIXME: Do we care about other names here too? 7195 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7196 // We really want to find the base class destructor here. 7197 QualType T = S->Context.getTypeDeclType(BaseRecord); 7198 CanQualType CT = S->Context.getCanonicalType(T); 7199 7200 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7201 } 7202 7203 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7204 Path.Decls = Path.Decls.slice(1)) { 7205 NamedDecl *D = Path.Decls.front(); 7206 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7207 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7208 return true; 7209 } 7210 } 7211 7212 return false; 7213 } 7214 }; 7215 7216 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7217 } // end anonymous namespace 7218 7219 /// \brief Report an error regarding overriding, along with any relevant 7220 /// overriden methods. 7221 /// 7222 /// \param DiagID the primary error to report. 7223 /// \param MD the overriding method. 7224 /// \param OEK which overrides to include as notes. 7225 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7226 OverrideErrorKind OEK = OEK_All) { 7227 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7228 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7229 E = MD->end_overridden_methods(); 7230 I != E; ++I) { 7231 // This check (& the OEK parameter) could be replaced by a predicate, but 7232 // without lambdas that would be overkill. This is still nicer than writing 7233 // out the diag loop 3 times. 7234 if ((OEK == OEK_All) || 7235 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7236 (OEK == OEK_Deleted && (*I)->isDeleted())) 7237 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7238 } 7239 } 7240 7241 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7242 /// and if so, check that it's a valid override and remember it. 7243 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7244 // Look for methods in base classes that this method might override. 7245 CXXBasePaths Paths; 7246 FindOverriddenMethod FOM; 7247 FOM.Method = MD; 7248 FOM.S = this; 7249 bool hasDeletedOverridenMethods = false; 7250 bool hasNonDeletedOverridenMethods = false; 7251 bool AddedAny = false; 7252 if (DC->lookupInBases(FOM, Paths)) { 7253 for (auto *I : Paths.found_decls()) { 7254 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7255 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7256 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7257 !CheckOverridingFunctionAttributes(MD, OldMD) && 7258 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7259 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7260 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7261 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7262 AddedAny = true; 7263 } 7264 } 7265 } 7266 } 7267 7268 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7269 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7270 } 7271 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7272 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7273 } 7274 7275 return AddedAny; 7276 } 7277 7278 namespace { 7279 // Struct for holding all of the extra arguments needed by 7280 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7281 struct ActOnFDArgs { 7282 Scope *S; 7283 Declarator &D; 7284 MultiTemplateParamsArg TemplateParamLists; 7285 bool AddToScope; 7286 }; 7287 } // end anonymous namespace 7288 7289 namespace { 7290 7291 // Callback to only accept typo corrections that have a non-zero edit distance. 7292 // Also only accept corrections that have the same parent decl. 7293 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7294 public: 7295 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7296 CXXRecordDecl *Parent) 7297 : Context(Context), OriginalFD(TypoFD), 7298 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7299 7300 bool ValidateCandidate(const TypoCorrection &candidate) override { 7301 if (candidate.getEditDistance() == 0) 7302 return false; 7303 7304 SmallVector<unsigned, 1> MismatchedParams; 7305 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7306 CDeclEnd = candidate.end(); 7307 CDecl != CDeclEnd; ++CDecl) { 7308 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7309 7310 if (FD && !FD->hasBody() && 7311 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7312 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7313 CXXRecordDecl *Parent = MD->getParent(); 7314 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7315 return true; 7316 } else if (!ExpectedParent) { 7317 return true; 7318 } 7319 } 7320 } 7321 7322 return false; 7323 } 7324 7325 private: 7326 ASTContext &Context; 7327 FunctionDecl *OriginalFD; 7328 CXXRecordDecl *ExpectedParent; 7329 }; 7330 7331 } // end anonymous namespace 7332 7333 /// \brief Generate diagnostics for an invalid function redeclaration. 7334 /// 7335 /// This routine handles generating the diagnostic messages for an invalid 7336 /// function redeclaration, including finding possible similar declarations 7337 /// or performing typo correction if there are no previous declarations with 7338 /// the same name. 7339 /// 7340 /// Returns a NamedDecl iff typo correction was performed and substituting in 7341 /// the new declaration name does not cause new errors. 7342 static NamedDecl *DiagnoseInvalidRedeclaration( 7343 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7344 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7345 DeclarationName Name = NewFD->getDeclName(); 7346 DeclContext *NewDC = NewFD->getDeclContext(); 7347 SmallVector<unsigned, 1> MismatchedParams; 7348 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7349 TypoCorrection Correction; 7350 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7351 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7352 : diag::err_member_decl_does_not_match; 7353 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7354 IsLocalFriend ? Sema::LookupLocalFriendName 7355 : Sema::LookupOrdinaryName, 7356 Sema::ForRedeclaration); 7357 7358 NewFD->setInvalidDecl(); 7359 if (IsLocalFriend) 7360 SemaRef.LookupName(Prev, S); 7361 else 7362 SemaRef.LookupQualifiedName(Prev, NewDC); 7363 assert(!Prev.isAmbiguous() && 7364 "Cannot have an ambiguity in previous-declaration lookup"); 7365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7366 if (!Prev.empty()) { 7367 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7368 Func != FuncEnd; ++Func) { 7369 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7370 if (FD && 7371 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7372 // Add 1 to the index so that 0 can mean the mismatch didn't 7373 // involve a parameter 7374 unsigned ParamNum = 7375 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7376 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7377 } 7378 } 7379 // If the qualified name lookup yielded nothing, try typo correction 7380 } else if ((Correction = SemaRef.CorrectTypo( 7381 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7382 &ExtraArgs.D.getCXXScopeSpec(), 7383 llvm::make_unique<DifferentNameValidatorCCC>( 7384 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7385 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7386 // Set up everything for the call to ActOnFunctionDeclarator 7387 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7388 ExtraArgs.D.getIdentifierLoc()); 7389 Previous.clear(); 7390 Previous.setLookupName(Correction.getCorrection()); 7391 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7392 CDeclEnd = Correction.end(); 7393 CDecl != CDeclEnd; ++CDecl) { 7394 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7395 if (FD && !FD->hasBody() && 7396 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7397 Previous.addDecl(FD); 7398 } 7399 } 7400 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7401 7402 NamedDecl *Result; 7403 // Retry building the function declaration with the new previous 7404 // declarations, and with errors suppressed. 7405 { 7406 // Trap errors. 7407 Sema::SFINAETrap Trap(SemaRef); 7408 7409 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7410 // pieces need to verify the typo-corrected C++ declaration and hopefully 7411 // eliminate the need for the parameter pack ExtraArgs. 7412 Result = SemaRef.ActOnFunctionDeclarator( 7413 ExtraArgs.S, ExtraArgs.D, 7414 Correction.getCorrectionDecl()->getDeclContext(), 7415 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7416 ExtraArgs.AddToScope); 7417 7418 if (Trap.hasErrorOccurred()) 7419 Result = nullptr; 7420 } 7421 7422 if (Result) { 7423 // Determine which correction we picked. 7424 Decl *Canonical = Result->getCanonicalDecl(); 7425 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7426 I != E; ++I) 7427 if ((*I)->getCanonicalDecl() == Canonical) 7428 Correction.setCorrectionDecl(*I); 7429 7430 SemaRef.diagnoseTypo( 7431 Correction, 7432 SemaRef.PDiag(IsLocalFriend 7433 ? diag::err_no_matching_local_friend_suggest 7434 : diag::err_member_decl_does_not_match_suggest) 7435 << Name << NewDC << IsDefinition); 7436 return Result; 7437 } 7438 7439 // Pretend the typo correction never occurred 7440 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7441 ExtraArgs.D.getIdentifierLoc()); 7442 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7443 Previous.clear(); 7444 Previous.setLookupName(Name); 7445 } 7446 7447 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7448 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7449 7450 bool NewFDisConst = false; 7451 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7452 NewFDisConst = NewMD->isConst(); 7453 7454 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7455 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7456 NearMatch != NearMatchEnd; ++NearMatch) { 7457 FunctionDecl *FD = NearMatch->first; 7458 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7459 bool FDisConst = MD && MD->isConst(); 7460 bool IsMember = MD || !IsLocalFriend; 7461 7462 // FIXME: These notes are poorly worded for the local friend case. 7463 if (unsigned Idx = NearMatch->second) { 7464 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7465 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7466 if (Loc.isInvalid()) Loc = FD->getLocation(); 7467 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7468 : diag::note_local_decl_close_param_match) 7469 << Idx << FDParam->getType() 7470 << NewFD->getParamDecl(Idx - 1)->getType(); 7471 } else if (FDisConst != NewFDisConst) { 7472 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7473 << NewFDisConst << FD->getSourceRange().getEnd(); 7474 } else 7475 SemaRef.Diag(FD->getLocation(), 7476 IsMember ? diag::note_member_def_close_match 7477 : diag::note_local_decl_close_match); 7478 } 7479 return nullptr; 7480 } 7481 7482 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7483 switch (D.getDeclSpec().getStorageClassSpec()) { 7484 default: llvm_unreachable("Unknown storage class!"); 7485 case DeclSpec::SCS_auto: 7486 case DeclSpec::SCS_register: 7487 case DeclSpec::SCS_mutable: 7488 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7489 diag::err_typecheck_sclass_func); 7490 D.setInvalidType(); 7491 break; 7492 case DeclSpec::SCS_unspecified: break; 7493 case DeclSpec::SCS_extern: 7494 if (D.getDeclSpec().isExternInLinkageSpec()) 7495 return SC_None; 7496 return SC_Extern; 7497 case DeclSpec::SCS_static: { 7498 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7499 // C99 6.7.1p5: 7500 // The declaration of an identifier for a function that has 7501 // block scope shall have no explicit storage-class specifier 7502 // other than extern 7503 // See also (C++ [dcl.stc]p4). 7504 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7505 diag::err_static_block_func); 7506 break; 7507 } else 7508 return SC_Static; 7509 } 7510 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7511 } 7512 7513 // No explicit storage class has already been returned 7514 return SC_None; 7515 } 7516 7517 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7518 DeclContext *DC, QualType &R, 7519 TypeSourceInfo *TInfo, 7520 StorageClass SC, 7521 bool &IsVirtualOkay) { 7522 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7523 DeclarationName Name = NameInfo.getName(); 7524 7525 FunctionDecl *NewFD = nullptr; 7526 bool isInline = D.getDeclSpec().isInlineSpecified(); 7527 7528 if (!SemaRef.getLangOpts().CPlusPlus) { 7529 // Determine whether the function was written with a 7530 // prototype. This true when: 7531 // - there is a prototype in the declarator, or 7532 // - the type R of the function is some kind of typedef or other reference 7533 // to a type name (which eventually refers to a function type). 7534 bool HasPrototype = 7535 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7536 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7537 7538 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7539 D.getLocStart(), NameInfo, R, 7540 TInfo, SC, isInline, 7541 HasPrototype, false); 7542 if (D.isInvalidType()) 7543 NewFD->setInvalidDecl(); 7544 7545 return NewFD; 7546 } 7547 7548 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7549 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7550 7551 // Check that the return type is not an abstract class type. 7552 // For record types, this is done by the AbstractClassUsageDiagnoser once 7553 // the class has been completely parsed. 7554 if (!DC->isRecord() && 7555 SemaRef.RequireNonAbstractType( 7556 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7557 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7558 D.setInvalidType(); 7559 7560 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7561 // This is a C++ constructor declaration. 7562 assert(DC->isRecord() && 7563 "Constructors can only be declared in a member context"); 7564 7565 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7566 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7567 D.getLocStart(), NameInfo, 7568 R, TInfo, isExplicit, isInline, 7569 /*isImplicitlyDeclared=*/false, 7570 isConstexpr); 7571 7572 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7573 // This is a C++ destructor declaration. 7574 if (DC->isRecord()) { 7575 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7576 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7577 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7578 SemaRef.Context, Record, 7579 D.getLocStart(), 7580 NameInfo, R, TInfo, isInline, 7581 /*isImplicitlyDeclared=*/false); 7582 7583 // If the class is complete, then we now create the implicit exception 7584 // specification. If the class is incomplete or dependent, we can't do 7585 // it yet. 7586 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7587 Record->getDefinition() && !Record->isBeingDefined() && 7588 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7589 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7590 } 7591 7592 IsVirtualOkay = true; 7593 return NewDD; 7594 7595 } else { 7596 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7597 D.setInvalidType(); 7598 7599 // Create a FunctionDecl to satisfy the function definition parsing 7600 // code path. 7601 return FunctionDecl::Create(SemaRef.Context, DC, 7602 D.getLocStart(), 7603 D.getIdentifierLoc(), Name, R, TInfo, 7604 SC, isInline, 7605 /*hasPrototype=*/true, isConstexpr); 7606 } 7607 7608 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7609 if (!DC->isRecord()) { 7610 SemaRef.Diag(D.getIdentifierLoc(), 7611 diag::err_conv_function_not_member); 7612 return nullptr; 7613 } 7614 7615 SemaRef.CheckConversionDeclarator(D, R, SC); 7616 IsVirtualOkay = true; 7617 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7618 D.getLocStart(), NameInfo, 7619 R, TInfo, isInline, isExplicit, 7620 isConstexpr, SourceLocation()); 7621 7622 } else if (DC->isRecord()) { 7623 // If the name of the function is the same as the name of the record, 7624 // then this must be an invalid constructor that has a return type. 7625 // (The parser checks for a return type and makes the declarator a 7626 // constructor if it has no return type). 7627 if (Name.getAsIdentifierInfo() && 7628 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7629 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7630 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7631 << SourceRange(D.getIdentifierLoc()); 7632 return nullptr; 7633 } 7634 7635 // This is a C++ method declaration. 7636 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7637 cast<CXXRecordDecl>(DC), 7638 D.getLocStart(), NameInfo, R, 7639 TInfo, SC, isInline, 7640 isConstexpr, SourceLocation()); 7641 IsVirtualOkay = !Ret->isStatic(); 7642 return Ret; 7643 } else { 7644 bool isFriend = 7645 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7646 if (!isFriend && SemaRef.CurContext->isRecord()) 7647 return nullptr; 7648 7649 // Determine whether the function was written with a 7650 // prototype. This true when: 7651 // - we're in C++ (where every function has a prototype), 7652 return FunctionDecl::Create(SemaRef.Context, DC, 7653 D.getLocStart(), 7654 NameInfo, R, TInfo, SC, isInline, 7655 true/*HasPrototype*/, isConstexpr); 7656 } 7657 } 7658 7659 enum OpenCLParamType { 7660 ValidKernelParam, 7661 PtrPtrKernelParam, 7662 PtrKernelParam, 7663 InvalidAddrSpacePtrKernelParam, 7664 InvalidKernelParam, 7665 RecordKernelParam 7666 }; 7667 7668 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7669 if (PT->isPointerType()) { 7670 QualType PointeeType = PT->getPointeeType(); 7671 if (PointeeType->isPointerType()) 7672 return PtrPtrKernelParam; 7673 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7674 PointeeType.getAddressSpace() == 0) 7675 return InvalidAddrSpacePtrKernelParam; 7676 return PtrKernelParam; 7677 } 7678 7679 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7680 // be used as builtin types. 7681 7682 if (PT->isImageType()) 7683 return PtrKernelParam; 7684 7685 if (PT->isBooleanType()) 7686 return InvalidKernelParam; 7687 7688 if (PT->isEventT()) 7689 return InvalidKernelParam; 7690 7691 // OpenCL extension spec v1.2 s9.5: 7692 // This extension adds support for half scalar and vector types as built-in 7693 // types that can be used for arithmetic operations, conversions etc. 7694 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7695 return InvalidKernelParam; 7696 7697 if (PT->isRecordType()) 7698 return RecordKernelParam; 7699 7700 return ValidKernelParam; 7701 } 7702 7703 static void checkIsValidOpenCLKernelParameter( 7704 Sema &S, 7705 Declarator &D, 7706 ParmVarDecl *Param, 7707 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7708 QualType PT = Param->getType(); 7709 7710 // Cache the valid types we encounter to avoid rechecking structs that are 7711 // used again 7712 if (ValidTypes.count(PT.getTypePtr())) 7713 return; 7714 7715 switch (getOpenCLKernelParameterType(S, PT)) { 7716 case PtrPtrKernelParam: 7717 // OpenCL v1.2 s6.9.a: 7718 // A kernel function argument cannot be declared as a 7719 // pointer to a pointer type. 7720 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7721 D.setInvalidType(); 7722 return; 7723 7724 case InvalidAddrSpacePtrKernelParam: 7725 // OpenCL v1.0 s6.5: 7726 // __kernel function arguments declared to be a pointer of a type can point 7727 // to one of the following address spaces only : __global, __local or 7728 // __constant. 7729 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7730 D.setInvalidType(); 7731 return; 7732 7733 // OpenCL v1.2 s6.9.k: 7734 // Arguments to kernel functions in a program cannot be declared with the 7735 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7736 // uintptr_t or a struct and/or union that contain fields declared to be 7737 // one of these built-in scalar types. 7738 7739 case InvalidKernelParam: 7740 // OpenCL v1.2 s6.8 n: 7741 // A kernel function argument cannot be declared 7742 // of event_t type. 7743 // Do not diagnose half type since it is diagnosed as invalid argument 7744 // type for any function elsewhere. 7745 if (!PT->isHalfType()) 7746 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7747 D.setInvalidType(); 7748 return; 7749 7750 case PtrKernelParam: 7751 case ValidKernelParam: 7752 ValidTypes.insert(PT.getTypePtr()); 7753 return; 7754 7755 case RecordKernelParam: 7756 break; 7757 } 7758 7759 // Track nested structs we will inspect 7760 SmallVector<const Decl *, 4> VisitStack; 7761 7762 // Track where we are in the nested structs. Items will migrate from 7763 // VisitStack to HistoryStack as we do the DFS for bad field. 7764 SmallVector<const FieldDecl *, 4> HistoryStack; 7765 HistoryStack.push_back(nullptr); 7766 7767 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7768 VisitStack.push_back(PD); 7769 7770 assert(VisitStack.back() && "First decl null?"); 7771 7772 do { 7773 const Decl *Next = VisitStack.pop_back_val(); 7774 if (!Next) { 7775 assert(!HistoryStack.empty()); 7776 // Found a marker, we have gone up a level 7777 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7778 ValidTypes.insert(Hist->getType().getTypePtr()); 7779 7780 continue; 7781 } 7782 7783 // Adds everything except the original parameter declaration (which is not a 7784 // field itself) to the history stack. 7785 const RecordDecl *RD; 7786 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7787 HistoryStack.push_back(Field); 7788 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7789 } else { 7790 RD = cast<RecordDecl>(Next); 7791 } 7792 7793 // Add a null marker so we know when we've gone back up a level 7794 VisitStack.push_back(nullptr); 7795 7796 for (const auto *FD : RD->fields()) { 7797 QualType QT = FD->getType(); 7798 7799 if (ValidTypes.count(QT.getTypePtr())) 7800 continue; 7801 7802 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7803 if (ParamType == ValidKernelParam) 7804 continue; 7805 7806 if (ParamType == RecordKernelParam) { 7807 VisitStack.push_back(FD); 7808 continue; 7809 } 7810 7811 // OpenCL v1.2 s6.9.p: 7812 // Arguments to kernel functions that are declared to be a struct or union 7813 // do not allow OpenCL objects to be passed as elements of the struct or 7814 // union. 7815 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7816 ParamType == InvalidAddrSpacePtrKernelParam) { 7817 S.Diag(Param->getLocation(), 7818 diag::err_record_with_pointers_kernel_param) 7819 << PT->isUnionType() 7820 << PT; 7821 } else { 7822 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7823 } 7824 7825 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7826 << PD->getDeclName(); 7827 7828 // We have an error, now let's go back up through history and show where 7829 // the offending field came from 7830 for (ArrayRef<const FieldDecl *>::const_iterator 7831 I = HistoryStack.begin() + 1, 7832 E = HistoryStack.end(); 7833 I != E; ++I) { 7834 const FieldDecl *OuterField = *I; 7835 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7836 << OuterField->getType(); 7837 } 7838 7839 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7840 << QT->isPointerType() 7841 << QT; 7842 D.setInvalidType(); 7843 return; 7844 } 7845 } while (!VisitStack.empty()); 7846 } 7847 7848 /// Find the DeclContext in which a tag is implicitly declared if we see an 7849 /// elaborated type specifier in the specified context, and lookup finds 7850 /// nothing. 7851 static DeclContext *getTagInjectionContext(DeclContext *DC) { 7852 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 7853 DC = DC->getParent(); 7854 return DC; 7855 } 7856 7857 /// Find the Scope in which a tag is implicitly declared if we see an 7858 /// elaborated type specifier in the specified context, and lookup finds 7859 /// nothing. 7860 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 7861 while (S->isClassScope() || 7862 (LangOpts.CPlusPlus && 7863 S->isFunctionPrototypeScope()) || 7864 ((S->getFlags() & Scope::DeclScope) == 0) || 7865 (S->getEntity() && S->getEntity()->isTransparentContext())) 7866 S = S->getParent(); 7867 return S; 7868 } 7869 7870 NamedDecl* 7871 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7872 TypeSourceInfo *TInfo, LookupResult &Previous, 7873 MultiTemplateParamsArg TemplateParamLists, 7874 bool &AddToScope) { 7875 QualType R = TInfo->getType(); 7876 7877 assert(R.getTypePtr()->isFunctionType()); 7878 7879 // TODO: consider using NameInfo for diagnostic. 7880 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7881 DeclarationName Name = NameInfo.getName(); 7882 StorageClass SC = getFunctionStorageClass(*this, D); 7883 7884 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7885 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7886 diag::err_invalid_thread) 7887 << DeclSpec::getSpecifierName(TSCS); 7888 7889 if (D.isFirstDeclarationOfMember()) 7890 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7891 D.getIdentifierLoc()); 7892 7893 bool isFriend = false; 7894 FunctionTemplateDecl *FunctionTemplate = nullptr; 7895 bool isExplicitSpecialization = false; 7896 bool isFunctionTemplateSpecialization = false; 7897 7898 bool isDependentClassScopeExplicitSpecialization = false; 7899 bool HasExplicitTemplateArgs = false; 7900 TemplateArgumentListInfo TemplateArgs; 7901 7902 bool isVirtualOkay = false; 7903 7904 DeclContext *OriginalDC = DC; 7905 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7906 7907 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7908 isVirtualOkay); 7909 if (!NewFD) return nullptr; 7910 7911 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7912 NewFD->setTopLevelDeclInObjCContainer(); 7913 7914 // Set the lexical context. If this is a function-scope declaration, or has a 7915 // C++ scope specifier, or is the object of a friend declaration, the lexical 7916 // context will be different from the semantic context. 7917 NewFD->setLexicalDeclContext(CurContext); 7918 7919 if (IsLocalExternDecl) 7920 NewFD->setLocalExternDecl(); 7921 7922 if (getLangOpts().CPlusPlus) { 7923 bool isInline = D.getDeclSpec().isInlineSpecified(); 7924 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7925 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7926 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7927 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7928 isFriend = D.getDeclSpec().isFriendSpecified(); 7929 if (isFriend && !isInline && D.isFunctionDefinition()) { 7930 // C++ [class.friend]p5 7931 // A function can be defined in a friend declaration of a 7932 // class . . . . Such a function is implicitly inline. 7933 NewFD->setImplicitlyInline(); 7934 } 7935 7936 // If this is a method defined in an __interface, and is not a constructor 7937 // or an overloaded operator, then set the pure flag (isVirtual will already 7938 // return true). 7939 if (const CXXRecordDecl *Parent = 7940 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7941 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7942 NewFD->setPure(true); 7943 7944 // C++ [class.union]p2 7945 // A union can have member functions, but not virtual functions. 7946 if (isVirtual && Parent->isUnion()) 7947 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7948 } 7949 7950 SetNestedNameSpecifier(NewFD, D); 7951 isExplicitSpecialization = false; 7952 isFunctionTemplateSpecialization = false; 7953 if (D.isInvalidType()) 7954 NewFD->setInvalidDecl(); 7955 7956 // Match up the template parameter lists with the scope specifier, then 7957 // determine whether we have a template or a template specialization. 7958 bool Invalid = false; 7959 if (TemplateParameterList *TemplateParams = 7960 MatchTemplateParametersToScopeSpecifier( 7961 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7962 D.getCXXScopeSpec(), 7963 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7964 ? D.getName().TemplateId 7965 : nullptr, 7966 TemplateParamLists, isFriend, isExplicitSpecialization, 7967 Invalid)) { 7968 if (TemplateParams->size() > 0) { 7969 // This is a function template 7970 7971 // Check that we can declare a template here. 7972 if (CheckTemplateDeclScope(S, TemplateParams)) 7973 NewFD->setInvalidDecl(); 7974 7975 // A destructor cannot be a template. 7976 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7977 Diag(NewFD->getLocation(), diag::err_destructor_template); 7978 NewFD->setInvalidDecl(); 7979 } 7980 7981 // If we're adding a template to a dependent context, we may need to 7982 // rebuilding some of the types used within the template parameter list, 7983 // now that we know what the current instantiation is. 7984 if (DC->isDependentContext()) { 7985 ContextRAII SavedContext(*this, DC); 7986 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7987 Invalid = true; 7988 } 7989 7990 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7991 NewFD->getLocation(), 7992 Name, TemplateParams, 7993 NewFD); 7994 FunctionTemplate->setLexicalDeclContext(CurContext); 7995 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7996 7997 // For source fidelity, store the other template param lists. 7998 if (TemplateParamLists.size() > 1) { 7999 NewFD->setTemplateParameterListsInfo(Context, 8000 TemplateParamLists.drop_back(1)); 8001 } 8002 } else { 8003 // This is a function template specialization. 8004 isFunctionTemplateSpecialization = true; 8005 // For source fidelity, store all the template param lists. 8006 if (TemplateParamLists.size() > 0) 8007 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8008 8009 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8010 if (isFriend) { 8011 // We want to remove the "template<>", found here. 8012 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8013 8014 // If we remove the template<> and the name is not a 8015 // template-id, we're actually silently creating a problem: 8016 // the friend declaration will refer to an untemplated decl, 8017 // and clearly the user wants a template specialization. So 8018 // we need to insert '<>' after the name. 8019 SourceLocation InsertLoc; 8020 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8021 InsertLoc = D.getName().getSourceRange().getEnd(); 8022 InsertLoc = getLocForEndOfToken(InsertLoc); 8023 } 8024 8025 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8026 << Name << RemoveRange 8027 << FixItHint::CreateRemoval(RemoveRange) 8028 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8029 } 8030 } 8031 } 8032 else { 8033 // All template param lists were matched against the scope specifier: 8034 // this is NOT (an explicit specialization of) a template. 8035 if (TemplateParamLists.size() > 0) 8036 // For source fidelity, store all the template param lists. 8037 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8038 } 8039 8040 if (Invalid) { 8041 NewFD->setInvalidDecl(); 8042 if (FunctionTemplate) 8043 FunctionTemplate->setInvalidDecl(); 8044 } 8045 8046 // C++ [dcl.fct.spec]p5: 8047 // The virtual specifier shall only be used in declarations of 8048 // nonstatic class member functions that appear within a 8049 // member-specification of a class declaration; see 10.3. 8050 // 8051 if (isVirtual && !NewFD->isInvalidDecl()) { 8052 if (!isVirtualOkay) { 8053 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8054 diag::err_virtual_non_function); 8055 } else if (!CurContext->isRecord()) { 8056 // 'virtual' was specified outside of the class. 8057 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8058 diag::err_virtual_out_of_class) 8059 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8060 } else if (NewFD->getDescribedFunctionTemplate()) { 8061 // C++ [temp.mem]p3: 8062 // A member function template shall not be virtual. 8063 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8064 diag::err_virtual_member_function_template) 8065 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8066 } else { 8067 // Okay: Add virtual to the method. 8068 NewFD->setVirtualAsWritten(true); 8069 } 8070 8071 if (getLangOpts().CPlusPlus14 && 8072 NewFD->getReturnType()->isUndeducedType()) 8073 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8074 } 8075 8076 if (getLangOpts().CPlusPlus14 && 8077 (NewFD->isDependentContext() || 8078 (isFriend && CurContext->isDependentContext())) && 8079 NewFD->getReturnType()->isUndeducedType()) { 8080 // If the function template is referenced directly (for instance, as a 8081 // member of the current instantiation), pretend it has a dependent type. 8082 // This is not really justified by the standard, but is the only sane 8083 // thing to do. 8084 // FIXME: For a friend function, we have not marked the function as being 8085 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8086 const FunctionProtoType *FPT = 8087 NewFD->getType()->castAs<FunctionProtoType>(); 8088 QualType Result = 8089 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8090 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8091 FPT->getExtProtoInfo())); 8092 } 8093 8094 // C++ [dcl.fct.spec]p3: 8095 // The inline specifier shall not appear on a block scope function 8096 // declaration. 8097 if (isInline && !NewFD->isInvalidDecl()) { 8098 if (CurContext->isFunctionOrMethod()) { 8099 // 'inline' is not allowed on block scope function declaration. 8100 Diag(D.getDeclSpec().getInlineSpecLoc(), 8101 diag::err_inline_declaration_block_scope) << Name 8102 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8103 } 8104 } 8105 8106 // C++ [dcl.fct.spec]p6: 8107 // The explicit specifier shall be used only in the declaration of a 8108 // constructor or conversion function within its class definition; 8109 // see 12.3.1 and 12.3.2. 8110 if (isExplicit && !NewFD->isInvalidDecl()) { 8111 if (!CurContext->isRecord()) { 8112 // 'explicit' was specified outside of the class. 8113 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8114 diag::err_explicit_out_of_class) 8115 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8116 } else if (!isa<CXXConstructorDecl>(NewFD) && 8117 !isa<CXXConversionDecl>(NewFD)) { 8118 // 'explicit' was specified on a function that wasn't a constructor 8119 // or conversion function. 8120 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8121 diag::err_explicit_non_ctor_or_conv_function) 8122 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8123 } 8124 } 8125 8126 if (isConstexpr) { 8127 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8128 // are implicitly inline. 8129 NewFD->setImplicitlyInline(); 8130 8131 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8132 // be either constructors or to return a literal type. Therefore, 8133 // destructors cannot be declared constexpr. 8134 if (isa<CXXDestructorDecl>(NewFD)) 8135 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8136 } 8137 8138 if (isConcept) { 8139 // This is a function concept. 8140 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8141 FTD->setConcept(); 8142 8143 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8144 // applied only to the definition of a function template [...] 8145 if (!D.isFunctionDefinition()) { 8146 Diag(D.getDeclSpec().getConceptSpecLoc(), 8147 diag::err_function_concept_not_defined); 8148 NewFD->setInvalidDecl(); 8149 } 8150 8151 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8152 // have no exception-specification and is treated as if it were specified 8153 // with noexcept(true) (15.4). [...] 8154 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8155 if (FPT->hasExceptionSpec()) { 8156 SourceRange Range; 8157 if (D.isFunctionDeclarator()) 8158 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8159 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8160 << FixItHint::CreateRemoval(Range); 8161 NewFD->setInvalidDecl(); 8162 } else { 8163 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8164 } 8165 8166 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8167 // following restrictions: 8168 // - The declared return type shall have the type bool. 8169 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8170 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8171 NewFD->setInvalidDecl(); 8172 } 8173 8174 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8175 // following restrictions: 8176 // - The declaration's parameter list shall be equivalent to an empty 8177 // parameter list. 8178 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8179 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8180 } 8181 8182 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8183 // implicity defined to be a constexpr declaration (implicitly inline) 8184 NewFD->setImplicitlyInline(); 8185 8186 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8187 // be declared with the thread_local, inline, friend, or constexpr 8188 // specifiers, [...] 8189 if (isInline) { 8190 Diag(D.getDeclSpec().getInlineSpecLoc(), 8191 diag::err_concept_decl_invalid_specifiers) 8192 << 1 << 1; 8193 NewFD->setInvalidDecl(true); 8194 } 8195 8196 if (isFriend) { 8197 Diag(D.getDeclSpec().getFriendSpecLoc(), 8198 diag::err_concept_decl_invalid_specifiers) 8199 << 1 << 2; 8200 NewFD->setInvalidDecl(true); 8201 } 8202 8203 if (isConstexpr) { 8204 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8205 diag::err_concept_decl_invalid_specifiers) 8206 << 1 << 3; 8207 NewFD->setInvalidDecl(true); 8208 } 8209 8210 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8211 // applied only to the definition of a function template or variable 8212 // template, declared in namespace scope. 8213 if (isFunctionTemplateSpecialization) { 8214 Diag(D.getDeclSpec().getConceptSpecLoc(), 8215 diag::err_concept_specified_specialization) << 1; 8216 NewFD->setInvalidDecl(true); 8217 return NewFD; 8218 } 8219 } 8220 8221 // If __module_private__ was specified, mark the function accordingly. 8222 if (D.getDeclSpec().isModulePrivateSpecified()) { 8223 if (isFunctionTemplateSpecialization) { 8224 SourceLocation ModulePrivateLoc 8225 = D.getDeclSpec().getModulePrivateSpecLoc(); 8226 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8227 << 0 8228 << FixItHint::CreateRemoval(ModulePrivateLoc); 8229 } else { 8230 NewFD->setModulePrivate(); 8231 if (FunctionTemplate) 8232 FunctionTemplate->setModulePrivate(); 8233 } 8234 } 8235 8236 if (isFriend) { 8237 if (FunctionTemplate) { 8238 FunctionTemplate->setObjectOfFriendDecl(); 8239 FunctionTemplate->setAccess(AS_public); 8240 } 8241 NewFD->setObjectOfFriendDecl(); 8242 NewFD->setAccess(AS_public); 8243 } 8244 8245 // If a function is defined as defaulted or deleted, mark it as such now. 8246 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8247 // definition kind to FDK_Definition. 8248 switch (D.getFunctionDefinitionKind()) { 8249 case FDK_Declaration: 8250 case FDK_Definition: 8251 break; 8252 8253 case FDK_Defaulted: 8254 NewFD->setDefaulted(); 8255 break; 8256 8257 case FDK_Deleted: 8258 NewFD->setDeletedAsWritten(); 8259 break; 8260 } 8261 8262 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8263 D.isFunctionDefinition()) { 8264 // C++ [class.mfct]p2: 8265 // A member function may be defined (8.4) in its class definition, in 8266 // which case it is an inline member function (7.1.2) 8267 NewFD->setImplicitlyInline(); 8268 } 8269 8270 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8271 !CurContext->isRecord()) { 8272 // C++ [class.static]p1: 8273 // A data or function member of a class may be declared static 8274 // in a class definition, in which case it is a static member of 8275 // the class. 8276 8277 // Complain about the 'static' specifier if it's on an out-of-line 8278 // member function definition. 8279 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8280 diag::err_static_out_of_line) 8281 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8282 } 8283 8284 // C++11 [except.spec]p15: 8285 // A deallocation function with no exception-specification is treated 8286 // as if it were specified with noexcept(true). 8287 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8288 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8289 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8290 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8291 NewFD->setType(Context.getFunctionType( 8292 FPT->getReturnType(), FPT->getParamTypes(), 8293 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8294 } 8295 8296 // Filter out previous declarations that don't match the scope. 8297 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8298 D.getCXXScopeSpec().isNotEmpty() || 8299 isExplicitSpecialization || 8300 isFunctionTemplateSpecialization); 8301 8302 // Handle GNU asm-label extension (encoded as an attribute). 8303 if (Expr *E = (Expr*) D.getAsmLabel()) { 8304 // The parser guarantees this is a string. 8305 StringLiteral *SE = cast<StringLiteral>(E); 8306 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8307 SE->getString(), 0)); 8308 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8309 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8310 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8311 if (I != ExtnameUndeclaredIdentifiers.end()) { 8312 if (isDeclExternC(NewFD)) { 8313 NewFD->addAttr(I->second); 8314 ExtnameUndeclaredIdentifiers.erase(I); 8315 } else 8316 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8317 << /*Variable*/0 << NewFD; 8318 } 8319 } 8320 8321 // Copy the parameter declarations from the declarator D to the function 8322 // declaration NewFD, if they are available. First scavenge them into Params. 8323 SmallVector<ParmVarDecl*, 16> Params; 8324 unsigned FTIIdx; 8325 if (D.isFunctionDeclarator(FTIIdx)) { 8326 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8327 8328 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8329 // function that takes no arguments, not a function that takes a 8330 // single void argument. 8331 // We let through "const void" here because Sema::GetTypeForDeclarator 8332 // already checks for that case. 8333 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8334 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8335 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8336 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8337 Param->setDeclContext(NewFD); 8338 Params.push_back(Param); 8339 8340 if (Param->isInvalidDecl()) 8341 NewFD->setInvalidDecl(); 8342 } 8343 } 8344 8345 if (!getLangOpts().CPlusPlus) { 8346 // In C, find all the tag declarations from the prototype and move them 8347 // into the function DeclContext. Remove them from the surrounding tag 8348 // injection context of the function, which is typically but not always 8349 // the TU. 8350 DeclContext *PrototypeTagContext = 8351 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8352 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8353 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8354 8355 // We don't want to reparent enumerators. Look at their parent enum 8356 // instead. 8357 if (!TD) { 8358 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8359 TD = cast<EnumDecl>(ECD->getDeclContext()); 8360 } 8361 if (!TD) 8362 continue; 8363 DeclContext *TagDC = TD->getLexicalDeclContext(); 8364 if (!TagDC->containsDecl(TD)) 8365 continue; 8366 TagDC->removeDecl(TD); 8367 TD->setDeclContext(NewFD); 8368 NewFD->addDecl(TD); 8369 8370 // Preserve the lexical DeclContext if it is not the surrounding tag 8371 // injection context of the FD. In this example, the semantic context of 8372 // E will be f and the lexical context will be S, while both the 8373 // semantic and lexical contexts of S will be f: 8374 // void f(struct S { enum E { a } f; } s); 8375 if (TagDC != PrototypeTagContext) 8376 TD->setLexicalDeclContext(TagDC); 8377 } 8378 } 8379 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8380 // When we're declaring a function with a typedef, typeof, etc as in the 8381 // following example, we'll need to synthesize (unnamed) 8382 // parameters for use in the declaration. 8383 // 8384 // @code 8385 // typedef void fn(int); 8386 // fn f; 8387 // @endcode 8388 8389 // Synthesize a parameter for each argument type. 8390 for (const auto &AI : FT->param_types()) { 8391 ParmVarDecl *Param = 8392 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8393 Param->setScopeInfo(0, Params.size()); 8394 Params.push_back(Param); 8395 } 8396 } else { 8397 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8398 "Should not need args for typedef of non-prototype fn"); 8399 } 8400 8401 // Finally, we know we have the right number of parameters, install them. 8402 NewFD->setParams(Params); 8403 8404 if (D.getDeclSpec().isNoreturnSpecified()) 8405 NewFD->addAttr( 8406 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8407 Context, 0)); 8408 8409 // Functions returning a variably modified type violate C99 6.7.5.2p2 8410 // because all functions have linkage. 8411 if (!NewFD->isInvalidDecl() && 8412 NewFD->getReturnType()->isVariablyModifiedType()) { 8413 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8414 NewFD->setInvalidDecl(); 8415 } 8416 8417 // Apply an implicit SectionAttr if #pragma code_seg is active. 8418 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8419 !NewFD->hasAttr<SectionAttr>()) { 8420 NewFD->addAttr( 8421 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8422 CodeSegStack.CurrentValue->getString(), 8423 CodeSegStack.CurrentPragmaLocation)); 8424 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8425 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8426 ASTContext::PSF_Read, 8427 NewFD)) 8428 NewFD->dropAttr<SectionAttr>(); 8429 } 8430 8431 // Handle attributes. 8432 ProcessDeclAttributes(S, NewFD, D); 8433 8434 if (getLangOpts().OpenCL) { 8435 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8436 // type declaration will generate a compilation error. 8437 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8438 if (AddressSpace == LangAS::opencl_local || 8439 AddressSpace == LangAS::opencl_global || 8440 AddressSpace == LangAS::opencl_constant) { 8441 Diag(NewFD->getLocation(), 8442 diag::err_opencl_return_value_with_address_space); 8443 NewFD->setInvalidDecl(); 8444 } 8445 } 8446 8447 if (!getLangOpts().CPlusPlus) { 8448 // Perform semantic checking on the function declaration. 8449 bool isExplicitSpecialization=false; 8450 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8451 CheckMain(NewFD, D.getDeclSpec()); 8452 8453 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8454 CheckMSVCRTEntryPoint(NewFD); 8455 8456 if (!NewFD->isInvalidDecl()) 8457 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8458 isExplicitSpecialization)); 8459 else if (!Previous.empty()) 8460 // Recover gracefully from an invalid redeclaration. 8461 D.setRedeclaration(true); 8462 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8463 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8464 "previous declaration set still overloaded"); 8465 8466 // Diagnose no-prototype function declarations with calling conventions that 8467 // don't support variadic calls. Only do this in C and do it after merging 8468 // possibly prototyped redeclarations. 8469 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8470 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8471 CallingConv CC = FT->getExtInfo().getCC(); 8472 if (!supportsVariadicCall(CC)) { 8473 // Windows system headers sometimes accidentally use stdcall without 8474 // (void) parameters, so we relax this to a warning. 8475 int DiagID = 8476 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8477 Diag(NewFD->getLocation(), DiagID) 8478 << FunctionType::getNameForCallConv(CC); 8479 } 8480 } 8481 } else { 8482 // C++11 [replacement.functions]p3: 8483 // The program's definitions shall not be specified as inline. 8484 // 8485 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8486 // 8487 // Suppress the diagnostic if the function is __attribute__((used)), since 8488 // that forces an external definition to be emitted. 8489 if (D.getDeclSpec().isInlineSpecified() && 8490 NewFD->isReplaceableGlobalAllocationFunction() && 8491 !NewFD->hasAttr<UsedAttr>()) 8492 Diag(D.getDeclSpec().getInlineSpecLoc(), 8493 diag::ext_operator_new_delete_declared_inline) 8494 << NewFD->getDeclName(); 8495 8496 // If the declarator is a template-id, translate the parser's template 8497 // argument list into our AST format. 8498 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8499 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8500 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8501 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8502 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8503 TemplateId->NumArgs); 8504 translateTemplateArguments(TemplateArgsPtr, 8505 TemplateArgs); 8506 8507 HasExplicitTemplateArgs = true; 8508 8509 if (NewFD->isInvalidDecl()) { 8510 HasExplicitTemplateArgs = false; 8511 } else if (FunctionTemplate) { 8512 // Function template with explicit template arguments. 8513 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8514 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8515 8516 HasExplicitTemplateArgs = false; 8517 } else { 8518 assert((isFunctionTemplateSpecialization || 8519 D.getDeclSpec().isFriendSpecified()) && 8520 "should have a 'template<>' for this decl"); 8521 // "friend void foo<>(int);" is an implicit specialization decl. 8522 isFunctionTemplateSpecialization = true; 8523 } 8524 } else if (isFriend && isFunctionTemplateSpecialization) { 8525 // This combination is only possible in a recovery case; the user 8526 // wrote something like: 8527 // template <> friend void foo(int); 8528 // which we're recovering from as if the user had written: 8529 // friend void foo<>(int); 8530 // Go ahead and fake up a template id. 8531 HasExplicitTemplateArgs = true; 8532 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8533 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8534 } 8535 8536 // We do not add HD attributes to specializations here because 8537 // they may have different constexpr-ness compared to their 8538 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8539 // may end up with different effective targets. Instead, a 8540 // specialization inherits its target attributes from its template 8541 // in the CheckFunctionTemplateSpecialization() call below. 8542 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8543 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8544 8545 // If it's a friend (and only if it's a friend), it's possible 8546 // that either the specialized function type or the specialized 8547 // template is dependent, and therefore matching will fail. In 8548 // this case, don't check the specialization yet. 8549 bool InstantiationDependent = false; 8550 if (isFunctionTemplateSpecialization && isFriend && 8551 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8552 TemplateSpecializationType::anyDependentTemplateArguments( 8553 TemplateArgs, 8554 InstantiationDependent))) { 8555 assert(HasExplicitTemplateArgs && 8556 "friend function specialization without template args"); 8557 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8558 Previous)) 8559 NewFD->setInvalidDecl(); 8560 } else if (isFunctionTemplateSpecialization) { 8561 if (CurContext->isDependentContext() && CurContext->isRecord() 8562 && !isFriend) { 8563 isDependentClassScopeExplicitSpecialization = true; 8564 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8565 diag::ext_function_specialization_in_class : 8566 diag::err_function_specialization_in_class) 8567 << NewFD->getDeclName(); 8568 } else if (CheckFunctionTemplateSpecialization(NewFD, 8569 (HasExplicitTemplateArgs ? &TemplateArgs 8570 : nullptr), 8571 Previous)) 8572 NewFD->setInvalidDecl(); 8573 8574 // C++ [dcl.stc]p1: 8575 // A storage-class-specifier shall not be specified in an explicit 8576 // specialization (14.7.3) 8577 FunctionTemplateSpecializationInfo *Info = 8578 NewFD->getTemplateSpecializationInfo(); 8579 if (Info && SC != SC_None) { 8580 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8581 Diag(NewFD->getLocation(), 8582 diag::err_explicit_specialization_inconsistent_storage_class) 8583 << SC 8584 << FixItHint::CreateRemoval( 8585 D.getDeclSpec().getStorageClassSpecLoc()); 8586 8587 else 8588 Diag(NewFD->getLocation(), 8589 diag::ext_explicit_specialization_storage_class) 8590 << FixItHint::CreateRemoval( 8591 D.getDeclSpec().getStorageClassSpecLoc()); 8592 } 8593 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8594 if (CheckMemberSpecialization(NewFD, Previous)) 8595 NewFD->setInvalidDecl(); 8596 } 8597 8598 // Perform semantic checking on the function declaration. 8599 if (!isDependentClassScopeExplicitSpecialization) { 8600 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8601 CheckMain(NewFD, D.getDeclSpec()); 8602 8603 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8604 CheckMSVCRTEntryPoint(NewFD); 8605 8606 if (!NewFD->isInvalidDecl()) 8607 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8608 isExplicitSpecialization)); 8609 else if (!Previous.empty()) 8610 // Recover gracefully from an invalid redeclaration. 8611 D.setRedeclaration(true); 8612 } 8613 8614 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8615 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8616 "previous declaration set still overloaded"); 8617 8618 NamedDecl *PrincipalDecl = (FunctionTemplate 8619 ? cast<NamedDecl>(FunctionTemplate) 8620 : NewFD); 8621 8622 if (isFriend && NewFD->getPreviousDecl()) { 8623 AccessSpecifier Access = AS_public; 8624 if (!NewFD->isInvalidDecl()) 8625 Access = NewFD->getPreviousDecl()->getAccess(); 8626 8627 NewFD->setAccess(Access); 8628 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8629 } 8630 8631 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8632 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8633 PrincipalDecl->setNonMemberOperator(); 8634 8635 // If we have a function template, check the template parameter 8636 // list. This will check and merge default template arguments. 8637 if (FunctionTemplate) { 8638 FunctionTemplateDecl *PrevTemplate = 8639 FunctionTemplate->getPreviousDecl(); 8640 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8641 PrevTemplate ? PrevTemplate->getTemplateParameters() 8642 : nullptr, 8643 D.getDeclSpec().isFriendSpecified() 8644 ? (D.isFunctionDefinition() 8645 ? TPC_FriendFunctionTemplateDefinition 8646 : TPC_FriendFunctionTemplate) 8647 : (D.getCXXScopeSpec().isSet() && 8648 DC && DC->isRecord() && 8649 DC->isDependentContext()) 8650 ? TPC_ClassTemplateMember 8651 : TPC_FunctionTemplate); 8652 } 8653 8654 if (NewFD->isInvalidDecl()) { 8655 // Ignore all the rest of this. 8656 } else if (!D.isRedeclaration()) { 8657 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8658 AddToScope }; 8659 // Fake up an access specifier if it's supposed to be a class member. 8660 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8661 NewFD->setAccess(AS_public); 8662 8663 // Qualified decls generally require a previous declaration. 8664 if (D.getCXXScopeSpec().isSet()) { 8665 // ...with the major exception of templated-scope or 8666 // dependent-scope friend declarations. 8667 8668 // TODO: we currently also suppress this check in dependent 8669 // contexts because (1) the parameter depth will be off when 8670 // matching friend templates and (2) we might actually be 8671 // selecting a friend based on a dependent factor. But there 8672 // are situations where these conditions don't apply and we 8673 // can actually do this check immediately. 8674 if (isFriend && 8675 (TemplateParamLists.size() || 8676 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8677 CurContext->isDependentContext())) { 8678 // ignore these 8679 } else { 8680 // The user tried to provide an out-of-line definition for a 8681 // function that is a member of a class or namespace, but there 8682 // was no such member function declared (C++ [class.mfct]p2, 8683 // C++ [namespace.memdef]p2). For example: 8684 // 8685 // class X { 8686 // void f() const; 8687 // }; 8688 // 8689 // void X::f() { } // ill-formed 8690 // 8691 // Complain about this problem, and attempt to suggest close 8692 // matches (e.g., those that differ only in cv-qualifiers and 8693 // whether the parameter types are references). 8694 8695 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8696 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8697 AddToScope = ExtraArgs.AddToScope; 8698 return Result; 8699 } 8700 } 8701 8702 // Unqualified local friend declarations are required to resolve 8703 // to something. 8704 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8705 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8706 *this, Previous, NewFD, ExtraArgs, true, S)) { 8707 AddToScope = ExtraArgs.AddToScope; 8708 return Result; 8709 } 8710 } 8711 } else if (!D.isFunctionDefinition() && 8712 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8713 !isFriend && !isFunctionTemplateSpecialization && 8714 !isExplicitSpecialization) { 8715 // An out-of-line member function declaration must also be a 8716 // definition (C++ [class.mfct]p2). 8717 // Note that this is not the case for explicit specializations of 8718 // function templates or member functions of class templates, per 8719 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8720 // extension for compatibility with old SWIG code which likes to 8721 // generate them. 8722 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8723 << D.getCXXScopeSpec().getRange(); 8724 } 8725 } 8726 8727 ProcessPragmaWeak(S, NewFD); 8728 checkAttributesAfterMerging(*this, *NewFD); 8729 8730 AddKnownFunctionAttributes(NewFD); 8731 8732 if (NewFD->hasAttr<OverloadableAttr>() && 8733 !NewFD->getType()->getAs<FunctionProtoType>()) { 8734 Diag(NewFD->getLocation(), 8735 diag::err_attribute_overloadable_no_prototype) 8736 << NewFD; 8737 8738 // Turn this into a variadic function with no parameters. 8739 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8740 FunctionProtoType::ExtProtoInfo EPI( 8741 Context.getDefaultCallingConvention(true, false)); 8742 EPI.Variadic = true; 8743 EPI.ExtInfo = FT->getExtInfo(); 8744 8745 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8746 NewFD->setType(R); 8747 } 8748 8749 // If there's a #pragma GCC visibility in scope, and this isn't a class 8750 // member, set the visibility of this function. 8751 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8752 AddPushedVisibilityAttribute(NewFD); 8753 8754 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8755 // marking the function. 8756 AddCFAuditedAttribute(NewFD); 8757 8758 // If this is a function definition, check if we have to apply optnone due to 8759 // a pragma. 8760 if(D.isFunctionDefinition()) 8761 AddRangeBasedOptnone(NewFD); 8762 8763 // If this is the first declaration of an extern C variable, update 8764 // the map of such variables. 8765 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8766 isIncompleteDeclExternC(*this, NewFD)) 8767 RegisterLocallyScopedExternCDecl(NewFD, S); 8768 8769 // Set this FunctionDecl's range up to the right paren. 8770 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8771 8772 if (D.isRedeclaration() && !Previous.empty()) { 8773 checkDLLAttributeRedeclaration( 8774 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8775 isExplicitSpecialization || isFunctionTemplateSpecialization, 8776 D.isFunctionDefinition()); 8777 } 8778 8779 if (getLangOpts().CUDA) { 8780 IdentifierInfo *II = NewFD->getIdentifier(); 8781 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8782 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8783 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8784 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8785 8786 Context.setcudaConfigureCallDecl(NewFD); 8787 } 8788 8789 // Variadic functions, other than a *declaration* of printf, are not allowed 8790 // in device-side CUDA code, unless someone passed 8791 // -fcuda-allow-variadic-functions. 8792 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8793 (NewFD->hasAttr<CUDADeviceAttr>() || 8794 NewFD->hasAttr<CUDAGlobalAttr>()) && 8795 !(II && II->isStr("printf") && NewFD->isExternC() && 8796 !D.isFunctionDefinition())) { 8797 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8798 } 8799 } 8800 8801 if (getLangOpts().CPlusPlus) { 8802 if (FunctionTemplate) { 8803 if (NewFD->isInvalidDecl()) 8804 FunctionTemplate->setInvalidDecl(); 8805 return FunctionTemplate; 8806 } 8807 } 8808 8809 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8810 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8811 if ((getLangOpts().OpenCLVersion >= 120) 8812 && (SC == SC_Static)) { 8813 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8814 D.setInvalidType(); 8815 } 8816 8817 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8818 if (!NewFD->getReturnType()->isVoidType()) { 8819 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8820 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8821 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8822 : FixItHint()); 8823 D.setInvalidType(); 8824 } 8825 8826 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8827 for (auto Param : NewFD->parameters()) 8828 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8829 } 8830 for (const ParmVarDecl *Param : NewFD->parameters()) { 8831 QualType PT = Param->getType(); 8832 8833 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8834 // types. 8835 if (getLangOpts().OpenCLVersion >= 200) { 8836 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8837 QualType ElemTy = PipeTy->getElementType(); 8838 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8839 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8840 D.setInvalidType(); 8841 } 8842 } 8843 } 8844 } 8845 8846 MarkUnusedFileScopedDecl(NewFD); 8847 8848 // Here we have an function template explicit specialization at class scope. 8849 // The actually specialization will be postponed to template instatiation 8850 // time via the ClassScopeFunctionSpecializationDecl node. 8851 if (isDependentClassScopeExplicitSpecialization) { 8852 ClassScopeFunctionSpecializationDecl *NewSpec = 8853 ClassScopeFunctionSpecializationDecl::Create( 8854 Context, CurContext, SourceLocation(), 8855 cast<CXXMethodDecl>(NewFD), 8856 HasExplicitTemplateArgs, TemplateArgs); 8857 CurContext->addDecl(NewSpec); 8858 AddToScope = false; 8859 } 8860 8861 return NewFD; 8862 } 8863 8864 /// \brief Checks if the new declaration declared in dependent context must be 8865 /// put in the same redeclaration chain as the specified declaration. 8866 /// 8867 /// \param D Declaration that is checked. 8868 /// \param PrevDecl Previous declaration found with proper lookup method for the 8869 /// same declaration name. 8870 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8871 /// belongs to. 8872 /// 8873 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8874 // Any declarations should be put into redeclaration chains except for 8875 // friend declaration in a dependent context that names a function in 8876 // namespace scope. 8877 // 8878 // This allows to compile code like: 8879 // 8880 // void func(); 8881 // template<typename T> class C1 { friend void func() { } }; 8882 // template<typename T> class C2 { friend void func() { } }; 8883 // 8884 // This code snippet is a valid code unless both templates are instantiated. 8885 return !(D->getLexicalDeclContext()->isDependentContext() && 8886 D->getDeclContext()->isFileContext() && 8887 D->getFriendObjectKind() != Decl::FOK_None); 8888 } 8889 8890 /// \brief Perform semantic checking of a new function declaration. 8891 /// 8892 /// Performs semantic analysis of the new function declaration 8893 /// NewFD. This routine performs all semantic checking that does not 8894 /// require the actual declarator involved in the declaration, and is 8895 /// used both for the declaration of functions as they are parsed 8896 /// (called via ActOnDeclarator) and for the declaration of functions 8897 /// that have been instantiated via C++ template instantiation (called 8898 /// via InstantiateDecl). 8899 /// 8900 /// \param IsExplicitSpecialization whether this new function declaration is 8901 /// an explicit specialization of the previous declaration. 8902 /// 8903 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8904 /// 8905 /// \returns true if the function declaration is a redeclaration. 8906 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8907 LookupResult &Previous, 8908 bool IsExplicitSpecialization) { 8909 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8910 "Variably modified return types are not handled here"); 8911 8912 // Determine whether the type of this function should be merged with 8913 // a previous visible declaration. This never happens for functions in C++, 8914 // and always happens in C if the previous declaration was visible. 8915 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8916 !Previous.isShadowed(); 8917 8918 bool Redeclaration = false; 8919 NamedDecl *OldDecl = nullptr; 8920 8921 // Merge or overload the declaration with an existing declaration of 8922 // the same name, if appropriate. 8923 if (!Previous.empty()) { 8924 // Determine whether NewFD is an overload of PrevDecl or 8925 // a declaration that requires merging. If it's an overload, 8926 // there's no more work to do here; we'll just add the new 8927 // function to the scope. 8928 if (!AllowOverloadingOfFunction(Previous, Context)) { 8929 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8930 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8931 Redeclaration = true; 8932 OldDecl = Candidate; 8933 } 8934 } else { 8935 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8936 /*NewIsUsingDecl*/ false)) { 8937 case Ovl_Match: 8938 Redeclaration = true; 8939 break; 8940 8941 case Ovl_NonFunction: 8942 Redeclaration = true; 8943 break; 8944 8945 case Ovl_Overload: 8946 Redeclaration = false; 8947 break; 8948 } 8949 8950 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8951 // If a function name is overloadable in C, then every function 8952 // with that name must be marked "overloadable". 8953 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8954 << Redeclaration << NewFD; 8955 NamedDecl *OverloadedDecl = nullptr; 8956 if (Redeclaration) 8957 OverloadedDecl = OldDecl; 8958 else if (!Previous.empty()) 8959 OverloadedDecl = Previous.getRepresentativeDecl(); 8960 if (OverloadedDecl) 8961 Diag(OverloadedDecl->getLocation(), 8962 diag::note_attribute_overloadable_prev_overload); 8963 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8964 } 8965 } 8966 } 8967 8968 // Check for a previous extern "C" declaration with this name. 8969 if (!Redeclaration && 8970 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8971 if (!Previous.empty()) { 8972 // This is an extern "C" declaration with the same name as a previous 8973 // declaration, and thus redeclares that entity... 8974 Redeclaration = true; 8975 OldDecl = Previous.getFoundDecl(); 8976 MergeTypeWithPrevious = false; 8977 8978 // ... except in the presence of __attribute__((overloadable)). 8979 if (OldDecl->hasAttr<OverloadableAttr>()) { 8980 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8981 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8982 << Redeclaration << NewFD; 8983 Diag(Previous.getFoundDecl()->getLocation(), 8984 diag::note_attribute_overloadable_prev_overload); 8985 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8986 } 8987 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8988 Redeclaration = false; 8989 OldDecl = nullptr; 8990 } 8991 } 8992 } 8993 } 8994 8995 // C++11 [dcl.constexpr]p8: 8996 // A constexpr specifier for a non-static member function that is not 8997 // a constructor declares that member function to be const. 8998 // 8999 // This needs to be delayed until we know whether this is an out-of-line 9000 // definition of a static member function. 9001 // 9002 // This rule is not present in C++1y, so we produce a backwards 9003 // compatibility warning whenever it happens in C++11. 9004 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9005 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9006 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9007 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9008 CXXMethodDecl *OldMD = nullptr; 9009 if (OldDecl) 9010 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9011 if (!OldMD || !OldMD->isStatic()) { 9012 const FunctionProtoType *FPT = 9013 MD->getType()->castAs<FunctionProtoType>(); 9014 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9015 EPI.TypeQuals |= Qualifiers::Const; 9016 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9017 FPT->getParamTypes(), EPI)); 9018 9019 // Warn that we did this, if we're not performing template instantiation. 9020 // In that case, we'll have warned already when the template was defined. 9021 if (ActiveTemplateInstantiations.empty()) { 9022 SourceLocation AddConstLoc; 9023 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9024 .IgnoreParens().getAs<FunctionTypeLoc>()) 9025 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9026 9027 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9028 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9029 } 9030 } 9031 } 9032 9033 if (Redeclaration) { 9034 // NewFD and OldDecl represent declarations that need to be 9035 // merged. 9036 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9037 NewFD->setInvalidDecl(); 9038 return Redeclaration; 9039 } 9040 9041 Previous.clear(); 9042 Previous.addDecl(OldDecl); 9043 9044 if (FunctionTemplateDecl *OldTemplateDecl 9045 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9046 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9047 FunctionTemplateDecl *NewTemplateDecl 9048 = NewFD->getDescribedFunctionTemplate(); 9049 assert(NewTemplateDecl && "Template/non-template mismatch"); 9050 if (CXXMethodDecl *Method 9051 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9052 Method->setAccess(OldTemplateDecl->getAccess()); 9053 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9054 } 9055 9056 // If this is an explicit specialization of a member that is a function 9057 // template, mark it as a member specialization. 9058 if (IsExplicitSpecialization && 9059 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9060 NewTemplateDecl->setMemberSpecialization(); 9061 assert(OldTemplateDecl->isMemberSpecialization()); 9062 // Explicit specializations of a member template do not inherit deleted 9063 // status from the parent member template that they are specializing. 9064 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9065 FunctionDecl *const OldTemplatedDecl = 9066 OldTemplateDecl->getTemplatedDecl(); 9067 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9068 OldTemplatedDecl->setDeletedAsWritten(false); 9069 } 9070 } 9071 9072 } else { 9073 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9074 // This needs to happen first so that 'inline' propagates. 9075 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9076 if (isa<CXXMethodDecl>(NewFD)) 9077 NewFD->setAccess(OldDecl->getAccess()); 9078 } 9079 } 9080 } 9081 9082 // Semantic checking for this function declaration (in isolation). 9083 9084 if (getLangOpts().CPlusPlus) { 9085 // C++-specific checks. 9086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9087 CheckConstructor(Constructor); 9088 } else if (CXXDestructorDecl *Destructor = 9089 dyn_cast<CXXDestructorDecl>(NewFD)) { 9090 CXXRecordDecl *Record = Destructor->getParent(); 9091 QualType ClassType = Context.getTypeDeclType(Record); 9092 9093 // FIXME: Shouldn't we be able to perform this check even when the class 9094 // type is dependent? Both gcc and edg can handle that. 9095 if (!ClassType->isDependentType()) { 9096 DeclarationName Name 9097 = Context.DeclarationNames.getCXXDestructorName( 9098 Context.getCanonicalType(ClassType)); 9099 if (NewFD->getDeclName() != Name) { 9100 Diag(NewFD->getLocation(), diag::err_destructor_name); 9101 NewFD->setInvalidDecl(); 9102 return Redeclaration; 9103 } 9104 } 9105 } else if (CXXConversionDecl *Conversion 9106 = dyn_cast<CXXConversionDecl>(NewFD)) { 9107 ActOnConversionDeclarator(Conversion); 9108 } 9109 9110 // Find any virtual functions that this function overrides. 9111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9112 if (!Method->isFunctionTemplateSpecialization() && 9113 !Method->getDescribedFunctionTemplate() && 9114 Method->isCanonicalDecl()) { 9115 if (AddOverriddenMethods(Method->getParent(), Method)) { 9116 // If the function was marked as "static", we have a problem. 9117 if (NewFD->getStorageClass() == SC_Static) { 9118 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9119 } 9120 } 9121 } 9122 9123 if (Method->isStatic()) 9124 checkThisInStaticMemberFunctionType(Method); 9125 } 9126 9127 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9128 if (NewFD->isOverloadedOperator() && 9129 CheckOverloadedOperatorDeclaration(NewFD)) { 9130 NewFD->setInvalidDecl(); 9131 return Redeclaration; 9132 } 9133 9134 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9135 if (NewFD->getLiteralIdentifier() && 9136 CheckLiteralOperatorDeclaration(NewFD)) { 9137 NewFD->setInvalidDecl(); 9138 return Redeclaration; 9139 } 9140 9141 // In C++, check default arguments now that we have merged decls. Unless 9142 // the lexical context is the class, because in this case this is done 9143 // during delayed parsing anyway. 9144 if (!CurContext->isRecord()) 9145 CheckCXXDefaultArguments(NewFD); 9146 9147 // If this function declares a builtin function, check the type of this 9148 // declaration against the expected type for the builtin. 9149 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9150 ASTContext::GetBuiltinTypeError Error; 9151 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9152 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9153 // If the type of the builtin differs only in its exception 9154 // specification, that's OK. 9155 // FIXME: If the types do differ in this way, it would be better to 9156 // retain the 'noexcept' form of the type. 9157 if (!T.isNull() && 9158 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9159 NewFD->getType())) 9160 // The type of this function differs from the type of the builtin, 9161 // so forget about the builtin entirely. 9162 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9163 } 9164 9165 // If this function is declared as being extern "C", then check to see if 9166 // the function returns a UDT (class, struct, or union type) that is not C 9167 // compatible, and if it does, warn the user. 9168 // But, issue any diagnostic on the first declaration only. 9169 if (Previous.empty() && NewFD->isExternC()) { 9170 QualType R = NewFD->getReturnType(); 9171 if (R->isIncompleteType() && !R->isVoidType()) 9172 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9173 << NewFD << R; 9174 else if (!R.isPODType(Context) && !R->isVoidType() && 9175 !R->isObjCObjectPointerType()) 9176 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9177 } 9178 9179 // C++1z [dcl.fct]p6: 9180 // [...] whether the function has a non-throwing exception-specification 9181 // [is] part of the function type 9182 // 9183 // This results in an ABI break between C++14 and C++17 for functions whose 9184 // declared type includes an exception-specification in a parameter or 9185 // return type. (Exception specifications on the function itself are OK in 9186 // most cases, and exception specifications are not permitted in most other 9187 // contexts where they could make it into a mangling.) 9188 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9189 auto HasNoexcept = [&](QualType T) -> bool { 9190 // Strip off declarator chunks that could be between us and a function 9191 // type. We don't need to look far, exception specifications are very 9192 // restricted prior to C++17. 9193 if (auto *RT = T->getAs<ReferenceType>()) 9194 T = RT->getPointeeType(); 9195 else if (T->isAnyPointerType()) 9196 T = T->getPointeeType(); 9197 else if (auto *MPT = T->getAs<MemberPointerType>()) 9198 T = MPT->getPointeeType(); 9199 if (auto *FPT = T->getAs<FunctionProtoType>()) 9200 if (FPT->isNothrow(Context)) 9201 return true; 9202 return false; 9203 }; 9204 9205 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9206 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9207 for (QualType T : FPT->param_types()) 9208 AnyNoexcept |= HasNoexcept(T); 9209 if (AnyNoexcept) 9210 Diag(NewFD->getLocation(), 9211 diag::warn_cxx1z_compat_exception_spec_in_signature) 9212 << NewFD; 9213 } 9214 9215 if (!Redeclaration && LangOpts.CUDA) 9216 checkCUDATargetOverload(NewFD, Previous); 9217 } 9218 return Redeclaration; 9219 } 9220 9221 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9222 // C++11 [basic.start.main]p3: 9223 // A program that [...] declares main to be inline, static or 9224 // constexpr is ill-formed. 9225 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9226 // appear in a declaration of main. 9227 // static main is not an error under C99, but we should warn about it. 9228 // We accept _Noreturn main as an extension. 9229 if (FD->getStorageClass() == SC_Static) 9230 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9231 ? diag::err_static_main : diag::warn_static_main) 9232 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9233 if (FD->isInlineSpecified()) 9234 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9235 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9236 if (DS.isNoreturnSpecified()) { 9237 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9238 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9239 Diag(NoreturnLoc, diag::ext_noreturn_main); 9240 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9241 << FixItHint::CreateRemoval(NoreturnRange); 9242 } 9243 if (FD->isConstexpr()) { 9244 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9245 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9246 FD->setConstexpr(false); 9247 } 9248 9249 if (getLangOpts().OpenCL) { 9250 Diag(FD->getLocation(), diag::err_opencl_no_main) 9251 << FD->hasAttr<OpenCLKernelAttr>(); 9252 FD->setInvalidDecl(); 9253 return; 9254 } 9255 9256 QualType T = FD->getType(); 9257 assert(T->isFunctionType() && "function decl is not of function type"); 9258 const FunctionType* FT = T->castAs<FunctionType>(); 9259 9260 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9261 // In C with GNU extensions we allow main() to have non-integer return 9262 // type, but we should warn about the extension, and we disable the 9263 // implicit-return-zero rule. 9264 9265 // GCC in C mode accepts qualified 'int'. 9266 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9267 FD->setHasImplicitReturnZero(true); 9268 else { 9269 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9270 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9271 if (RTRange.isValid()) 9272 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9273 << FixItHint::CreateReplacement(RTRange, "int"); 9274 } 9275 } else { 9276 // In C and C++, main magically returns 0 if you fall off the end; 9277 // set the flag which tells us that. 9278 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9279 9280 // All the standards say that main() should return 'int'. 9281 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9282 FD->setHasImplicitReturnZero(true); 9283 else { 9284 // Otherwise, this is just a flat-out error. 9285 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9286 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9287 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9288 : FixItHint()); 9289 FD->setInvalidDecl(true); 9290 } 9291 } 9292 9293 // Treat protoless main() as nullary. 9294 if (isa<FunctionNoProtoType>(FT)) return; 9295 9296 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9297 unsigned nparams = FTP->getNumParams(); 9298 assert(FD->getNumParams() == nparams); 9299 9300 bool HasExtraParameters = (nparams > 3); 9301 9302 if (FTP->isVariadic()) { 9303 Diag(FD->getLocation(), diag::ext_variadic_main); 9304 // FIXME: if we had information about the location of the ellipsis, we 9305 // could add a FixIt hint to remove it as a parameter. 9306 } 9307 9308 // Darwin passes an undocumented fourth argument of type char**. If 9309 // other platforms start sprouting these, the logic below will start 9310 // getting shifty. 9311 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9312 HasExtraParameters = false; 9313 9314 if (HasExtraParameters) { 9315 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9316 FD->setInvalidDecl(true); 9317 nparams = 3; 9318 } 9319 9320 // FIXME: a lot of the following diagnostics would be improved 9321 // if we had some location information about types. 9322 9323 QualType CharPP = 9324 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9325 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9326 9327 for (unsigned i = 0; i < nparams; ++i) { 9328 QualType AT = FTP->getParamType(i); 9329 9330 bool mismatch = true; 9331 9332 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9333 mismatch = false; 9334 else if (Expected[i] == CharPP) { 9335 // As an extension, the following forms are okay: 9336 // char const ** 9337 // char const * const * 9338 // char * const * 9339 9340 QualifierCollector qs; 9341 const PointerType* PT; 9342 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9343 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9344 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9345 Context.CharTy)) { 9346 qs.removeConst(); 9347 mismatch = !qs.empty(); 9348 } 9349 } 9350 9351 if (mismatch) { 9352 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9353 // TODO: suggest replacing given type with expected type 9354 FD->setInvalidDecl(true); 9355 } 9356 } 9357 9358 if (nparams == 1 && !FD->isInvalidDecl()) { 9359 Diag(FD->getLocation(), diag::warn_main_one_arg); 9360 } 9361 9362 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9363 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9364 FD->setInvalidDecl(); 9365 } 9366 } 9367 9368 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9369 QualType T = FD->getType(); 9370 assert(T->isFunctionType() && "function decl is not of function type"); 9371 const FunctionType *FT = T->castAs<FunctionType>(); 9372 9373 // Set an implicit return of 'zero' if the function can return some integral, 9374 // enumeration, pointer or nullptr type. 9375 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9376 FT->getReturnType()->isAnyPointerType() || 9377 FT->getReturnType()->isNullPtrType()) 9378 // DllMain is exempt because a return value of zero means it failed. 9379 if (FD->getName() != "DllMain") 9380 FD->setHasImplicitReturnZero(true); 9381 9382 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9383 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9384 FD->setInvalidDecl(); 9385 } 9386 } 9387 9388 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9389 // FIXME: Need strict checking. In C89, we need to check for 9390 // any assignment, increment, decrement, function-calls, or 9391 // commas outside of a sizeof. In C99, it's the same list, 9392 // except that the aforementioned are allowed in unevaluated 9393 // expressions. Everything else falls under the 9394 // "may accept other forms of constant expressions" exception. 9395 // (We never end up here for C++, so the constant expression 9396 // rules there don't matter.) 9397 const Expr *Culprit; 9398 if (Init->isConstantInitializer(Context, false, &Culprit)) 9399 return false; 9400 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9401 << Culprit->getSourceRange(); 9402 return true; 9403 } 9404 9405 namespace { 9406 // Visits an initialization expression to see if OrigDecl is evaluated in 9407 // its own initialization and throws a warning if it does. 9408 class SelfReferenceChecker 9409 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9410 Sema &S; 9411 Decl *OrigDecl; 9412 bool isRecordType; 9413 bool isPODType; 9414 bool isReferenceType; 9415 9416 bool isInitList; 9417 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9418 9419 public: 9420 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9421 9422 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9423 S(S), OrigDecl(OrigDecl) { 9424 isPODType = false; 9425 isRecordType = false; 9426 isReferenceType = false; 9427 isInitList = false; 9428 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9429 isPODType = VD->getType().isPODType(S.Context); 9430 isRecordType = VD->getType()->isRecordType(); 9431 isReferenceType = VD->getType()->isReferenceType(); 9432 } 9433 } 9434 9435 // For most expressions, just call the visitor. For initializer lists, 9436 // track the index of the field being initialized since fields are 9437 // initialized in order allowing use of previously initialized fields. 9438 void CheckExpr(Expr *E) { 9439 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9440 if (!InitList) { 9441 Visit(E); 9442 return; 9443 } 9444 9445 // Track and increment the index here. 9446 isInitList = true; 9447 InitFieldIndex.push_back(0); 9448 for (auto Child : InitList->children()) { 9449 CheckExpr(cast<Expr>(Child)); 9450 ++InitFieldIndex.back(); 9451 } 9452 InitFieldIndex.pop_back(); 9453 } 9454 9455 // Returns true if MemberExpr is checked and no futher checking is needed. 9456 // Returns false if additional checking is required. 9457 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9458 llvm::SmallVector<FieldDecl*, 4> Fields; 9459 Expr *Base = E; 9460 bool ReferenceField = false; 9461 9462 // Get the field memebers used. 9463 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9464 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9465 if (!FD) 9466 return false; 9467 Fields.push_back(FD); 9468 if (FD->getType()->isReferenceType()) 9469 ReferenceField = true; 9470 Base = ME->getBase()->IgnoreParenImpCasts(); 9471 } 9472 9473 // Keep checking only if the base Decl is the same. 9474 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9475 if (!DRE || DRE->getDecl() != OrigDecl) 9476 return false; 9477 9478 // A reference field can be bound to an unininitialized field. 9479 if (CheckReference && !ReferenceField) 9480 return true; 9481 9482 // Convert FieldDecls to their index number. 9483 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9484 for (const FieldDecl *I : llvm::reverse(Fields)) 9485 UsedFieldIndex.push_back(I->getFieldIndex()); 9486 9487 // See if a warning is needed by checking the first difference in index 9488 // numbers. If field being used has index less than the field being 9489 // initialized, then the use is safe. 9490 for (auto UsedIter = UsedFieldIndex.begin(), 9491 UsedEnd = UsedFieldIndex.end(), 9492 OrigIter = InitFieldIndex.begin(), 9493 OrigEnd = InitFieldIndex.end(); 9494 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9495 if (*UsedIter < *OrigIter) 9496 return true; 9497 if (*UsedIter > *OrigIter) 9498 break; 9499 } 9500 9501 // TODO: Add a different warning which will print the field names. 9502 HandleDeclRefExpr(DRE); 9503 return true; 9504 } 9505 9506 // For most expressions, the cast is directly above the DeclRefExpr. 9507 // For conditional operators, the cast can be outside the conditional 9508 // operator if both expressions are DeclRefExpr's. 9509 void HandleValue(Expr *E) { 9510 E = E->IgnoreParens(); 9511 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9512 HandleDeclRefExpr(DRE); 9513 return; 9514 } 9515 9516 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9517 Visit(CO->getCond()); 9518 HandleValue(CO->getTrueExpr()); 9519 HandleValue(CO->getFalseExpr()); 9520 return; 9521 } 9522 9523 if (BinaryConditionalOperator *BCO = 9524 dyn_cast<BinaryConditionalOperator>(E)) { 9525 Visit(BCO->getCond()); 9526 HandleValue(BCO->getFalseExpr()); 9527 return; 9528 } 9529 9530 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9531 HandleValue(OVE->getSourceExpr()); 9532 return; 9533 } 9534 9535 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9536 if (BO->getOpcode() == BO_Comma) { 9537 Visit(BO->getLHS()); 9538 HandleValue(BO->getRHS()); 9539 return; 9540 } 9541 } 9542 9543 if (isa<MemberExpr>(E)) { 9544 if (isInitList) { 9545 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9546 false /*CheckReference*/)) 9547 return; 9548 } 9549 9550 Expr *Base = E->IgnoreParenImpCasts(); 9551 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9552 // Check for static member variables and don't warn on them. 9553 if (!isa<FieldDecl>(ME->getMemberDecl())) 9554 return; 9555 Base = ME->getBase()->IgnoreParenImpCasts(); 9556 } 9557 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9558 HandleDeclRefExpr(DRE); 9559 return; 9560 } 9561 9562 Visit(E); 9563 } 9564 9565 // Reference types not handled in HandleValue are handled here since all 9566 // uses of references are bad, not just r-value uses. 9567 void VisitDeclRefExpr(DeclRefExpr *E) { 9568 if (isReferenceType) 9569 HandleDeclRefExpr(E); 9570 } 9571 9572 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9573 if (E->getCastKind() == CK_LValueToRValue) { 9574 HandleValue(E->getSubExpr()); 9575 return; 9576 } 9577 9578 Inherited::VisitImplicitCastExpr(E); 9579 } 9580 9581 void VisitMemberExpr(MemberExpr *E) { 9582 if (isInitList) { 9583 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9584 return; 9585 } 9586 9587 // Don't warn on arrays since they can be treated as pointers. 9588 if (E->getType()->canDecayToPointerType()) return; 9589 9590 // Warn when a non-static method call is followed by non-static member 9591 // field accesses, which is followed by a DeclRefExpr. 9592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9593 bool Warn = (MD && !MD->isStatic()); 9594 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9595 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9596 if (!isa<FieldDecl>(ME->getMemberDecl())) 9597 Warn = false; 9598 Base = ME->getBase()->IgnoreParenImpCasts(); 9599 } 9600 9601 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9602 if (Warn) 9603 HandleDeclRefExpr(DRE); 9604 return; 9605 } 9606 9607 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9608 // Visit that expression. 9609 Visit(Base); 9610 } 9611 9612 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9613 Expr *Callee = E->getCallee(); 9614 9615 if (isa<UnresolvedLookupExpr>(Callee)) 9616 return Inherited::VisitCXXOperatorCallExpr(E); 9617 9618 Visit(Callee); 9619 for (auto Arg: E->arguments()) 9620 HandleValue(Arg->IgnoreParenImpCasts()); 9621 } 9622 9623 void VisitUnaryOperator(UnaryOperator *E) { 9624 // For POD record types, addresses of its own members are well-defined. 9625 if (E->getOpcode() == UO_AddrOf && isRecordType && 9626 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9627 if (!isPODType) 9628 HandleValue(E->getSubExpr()); 9629 return; 9630 } 9631 9632 if (E->isIncrementDecrementOp()) { 9633 HandleValue(E->getSubExpr()); 9634 return; 9635 } 9636 9637 Inherited::VisitUnaryOperator(E); 9638 } 9639 9640 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9641 9642 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9643 if (E->getConstructor()->isCopyConstructor()) { 9644 Expr *ArgExpr = E->getArg(0); 9645 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9646 if (ILE->getNumInits() == 1) 9647 ArgExpr = ILE->getInit(0); 9648 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9649 if (ICE->getCastKind() == CK_NoOp) 9650 ArgExpr = ICE->getSubExpr(); 9651 HandleValue(ArgExpr); 9652 return; 9653 } 9654 Inherited::VisitCXXConstructExpr(E); 9655 } 9656 9657 void VisitCallExpr(CallExpr *E) { 9658 // Treat std::move as a use. 9659 if (E->getNumArgs() == 1) { 9660 if (FunctionDecl *FD = E->getDirectCallee()) { 9661 if (FD->isInStdNamespace() && FD->getIdentifier() && 9662 FD->getIdentifier()->isStr("move")) { 9663 HandleValue(E->getArg(0)); 9664 return; 9665 } 9666 } 9667 } 9668 9669 Inherited::VisitCallExpr(E); 9670 } 9671 9672 void VisitBinaryOperator(BinaryOperator *E) { 9673 if (E->isCompoundAssignmentOp()) { 9674 HandleValue(E->getLHS()); 9675 Visit(E->getRHS()); 9676 return; 9677 } 9678 9679 Inherited::VisitBinaryOperator(E); 9680 } 9681 9682 // A custom visitor for BinaryConditionalOperator is needed because the 9683 // regular visitor would check the condition and true expression separately 9684 // but both point to the same place giving duplicate diagnostics. 9685 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9686 Visit(E->getCond()); 9687 Visit(E->getFalseExpr()); 9688 } 9689 9690 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9691 Decl* ReferenceDecl = DRE->getDecl(); 9692 if (OrigDecl != ReferenceDecl) return; 9693 unsigned diag; 9694 if (isReferenceType) { 9695 diag = diag::warn_uninit_self_reference_in_reference_init; 9696 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9697 diag = diag::warn_static_self_reference_in_init; 9698 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9699 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9700 DRE->getDecl()->getType()->isRecordType()) { 9701 diag = diag::warn_uninit_self_reference_in_init; 9702 } else { 9703 // Local variables will be handled by the CFG analysis. 9704 return; 9705 } 9706 9707 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9708 S.PDiag(diag) 9709 << DRE->getNameInfo().getName() 9710 << OrigDecl->getLocation() 9711 << DRE->getSourceRange()); 9712 } 9713 }; 9714 9715 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9716 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9717 bool DirectInit) { 9718 // Parameters arguments are occassionially constructed with itself, 9719 // for instance, in recursive functions. Skip them. 9720 if (isa<ParmVarDecl>(OrigDecl)) 9721 return; 9722 9723 E = E->IgnoreParens(); 9724 9725 // Skip checking T a = a where T is not a record or reference type. 9726 // Doing so is a way to silence uninitialized warnings. 9727 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9728 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9729 if (ICE->getCastKind() == CK_LValueToRValue) 9730 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9731 if (DRE->getDecl() == OrigDecl) 9732 return; 9733 9734 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9735 } 9736 } // end anonymous namespace 9737 9738 namespace { 9739 // Simple wrapper to add the name of a variable or (if no variable is 9740 // available) a DeclarationName into a diagnostic. 9741 struct VarDeclOrName { 9742 VarDecl *VDecl; 9743 DeclarationName Name; 9744 9745 friend const Sema::SemaDiagnosticBuilder & 9746 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9747 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9748 } 9749 }; 9750 } // end anonymous namespace 9751 9752 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9753 DeclarationName Name, QualType Type, 9754 TypeSourceInfo *TSI, 9755 SourceRange Range, bool DirectInit, 9756 Expr *Init) { 9757 bool IsInitCapture = !VDecl; 9758 assert((!VDecl || !VDecl->isInitCapture()) && 9759 "init captures are expected to be deduced prior to initialization"); 9760 9761 VarDeclOrName VN{VDecl, Name}; 9762 9763 DeducedType *Deduced = Type->getContainedDeducedType(); 9764 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 9765 9766 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 9767 Diag(Init->getLocStart(), diag::err_deduced_class_template_not_supported); 9768 return QualType(); 9769 } 9770 9771 ArrayRef<Expr *> DeduceInits = Init; 9772 if (DirectInit) { 9773 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9774 DeduceInits = PL->exprs(); 9775 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9776 DeduceInits = IL->inits(); 9777 } 9778 9779 // Deduction only works if we have exactly one source expression. 9780 if (DeduceInits.empty()) { 9781 // It isn't possible to write this directly, but it is possible to 9782 // end up in this situation with "auto x(some_pack...);" 9783 Diag(Init->getLocStart(), IsInitCapture 9784 ? diag::err_init_capture_no_expression 9785 : diag::err_auto_var_init_no_expression) 9786 << VN << Type << Range; 9787 return QualType(); 9788 } 9789 9790 if (DeduceInits.size() > 1) { 9791 Diag(DeduceInits[1]->getLocStart(), 9792 IsInitCapture ? diag::err_init_capture_multiple_expressions 9793 : diag::err_auto_var_init_multiple_expressions) 9794 << VN << Type << Range; 9795 return QualType(); 9796 } 9797 9798 Expr *DeduceInit = DeduceInits[0]; 9799 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9800 Diag(Init->getLocStart(), IsInitCapture 9801 ? diag::err_init_capture_paren_braces 9802 : diag::err_auto_var_init_paren_braces) 9803 << isa<InitListExpr>(Init) << VN << Type << Range; 9804 return QualType(); 9805 } 9806 9807 // Expressions default to 'id' when we're in a debugger. 9808 bool DefaultedAnyToId = false; 9809 if (getLangOpts().DebuggerCastResultToId && 9810 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9811 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9812 if (Result.isInvalid()) { 9813 return QualType(); 9814 } 9815 Init = Result.get(); 9816 DefaultedAnyToId = true; 9817 } 9818 9819 // C++ [dcl.decomp]p1: 9820 // If the assignment-expression [...] has array type A and no ref-qualifier 9821 // is present, e has type cv A 9822 if (VDecl && isa<DecompositionDecl>(VDecl) && 9823 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 9824 DeduceInit->getType()->isConstantArrayType()) 9825 return Context.getQualifiedType(DeduceInit->getType(), 9826 Type.getQualifiers()); 9827 9828 QualType DeducedType; 9829 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9830 if (!IsInitCapture) 9831 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9832 else if (isa<InitListExpr>(Init)) 9833 Diag(Range.getBegin(), 9834 diag::err_init_capture_deduction_failure_from_init_list) 9835 << VN 9836 << (DeduceInit->getType().isNull() ? TSI->getType() 9837 : DeduceInit->getType()) 9838 << DeduceInit->getSourceRange(); 9839 else 9840 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9841 << VN << TSI->getType() 9842 << (DeduceInit->getType().isNull() ? TSI->getType() 9843 : DeduceInit->getType()) 9844 << DeduceInit->getSourceRange(); 9845 } 9846 9847 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9848 // 'id' instead of a specific object type prevents most of our usual 9849 // checks. 9850 // We only want to warn outside of template instantiations, though: 9851 // inside a template, the 'id' could have come from a parameter. 9852 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9853 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9854 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9855 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 9856 } 9857 9858 return DeducedType; 9859 } 9860 9861 /// AddInitializerToDecl - Adds the initializer Init to the 9862 /// declaration dcl. If DirectInit is true, this is C++ direct 9863 /// initialization rather than copy initialization. 9864 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 9865 // If there is no declaration, there was an error parsing it. Just ignore 9866 // the initializer. 9867 if (!RealDecl || RealDecl->isInvalidDecl()) { 9868 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9869 return; 9870 } 9871 9872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9873 // Pure-specifiers are handled in ActOnPureSpecifier. 9874 Diag(Method->getLocation(), diag::err_member_function_initialization) 9875 << Method->getDeclName() << Init->getSourceRange(); 9876 Method->setInvalidDecl(); 9877 return; 9878 } 9879 9880 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9881 if (!VDecl) { 9882 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9883 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9884 RealDecl->setInvalidDecl(); 9885 return; 9886 } 9887 9888 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9889 if (VDecl->getType()->isUndeducedType()) { 9890 // Attempt typo correction early so that the type of the init expression can 9891 // be deduced based on the chosen correction if the original init contains a 9892 // TypoExpr. 9893 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9894 if (!Res.isUsable()) { 9895 RealDecl->setInvalidDecl(); 9896 return; 9897 } 9898 Init = Res.get(); 9899 9900 QualType DeducedType = deduceVarTypeFromInitializer( 9901 VDecl, VDecl->getDeclName(), VDecl->getType(), 9902 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9903 if (DeducedType.isNull()) { 9904 RealDecl->setInvalidDecl(); 9905 return; 9906 } 9907 9908 VDecl->setType(DeducedType); 9909 assert(VDecl->isLinkageValid()); 9910 9911 // In ARC, infer lifetime. 9912 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9913 VDecl->setInvalidDecl(); 9914 9915 // If this is a redeclaration, check that the type we just deduced matches 9916 // the previously declared type. 9917 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9918 // We never need to merge the type, because we cannot form an incomplete 9919 // array of auto, nor deduce such a type. 9920 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9921 } 9922 9923 // Check the deduced type is valid for a variable declaration. 9924 CheckVariableDeclarationType(VDecl); 9925 if (VDecl->isInvalidDecl()) 9926 return; 9927 } 9928 9929 // dllimport cannot be used on variable definitions. 9930 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9931 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9932 VDecl->setInvalidDecl(); 9933 return; 9934 } 9935 9936 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9937 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9938 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9939 VDecl->setInvalidDecl(); 9940 return; 9941 } 9942 9943 if (!VDecl->getType()->isDependentType()) { 9944 // A definition must end up with a complete type, which means it must be 9945 // complete with the restriction that an array type might be completed by 9946 // the initializer; note that later code assumes this restriction. 9947 QualType BaseDeclType = VDecl->getType(); 9948 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9949 BaseDeclType = Array->getElementType(); 9950 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9951 diag::err_typecheck_decl_incomplete_type)) { 9952 RealDecl->setInvalidDecl(); 9953 return; 9954 } 9955 9956 // The variable can not have an abstract class type. 9957 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9958 diag::err_abstract_type_in_decl, 9959 AbstractVariableType)) 9960 VDecl->setInvalidDecl(); 9961 } 9962 9963 // If adding the initializer will turn this declaration into a definition, 9964 // and we already have a definition for this variable, diagnose or otherwise 9965 // handle the situation. 9966 VarDecl *Def; 9967 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9968 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 9969 !VDecl->isThisDeclarationADemotedDefinition() && 9970 checkVarDeclRedefinition(Def, VDecl)) 9971 return; 9972 9973 if (getLangOpts().CPlusPlus) { 9974 // C++ [class.static.data]p4 9975 // If a static data member is of const integral or const 9976 // enumeration type, its declaration in the class definition can 9977 // specify a constant-initializer which shall be an integral 9978 // constant expression (5.19). In that case, the member can appear 9979 // in integral constant expressions. The member shall still be 9980 // defined in a namespace scope if it is used in the program and the 9981 // namespace scope definition shall not contain an initializer. 9982 // 9983 // We already performed a redefinition check above, but for static 9984 // data members we also need to check whether there was an in-class 9985 // declaration with an initializer. 9986 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9987 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9988 << VDecl->getDeclName(); 9989 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9990 diag::note_previous_initializer) 9991 << 0; 9992 return; 9993 } 9994 9995 if (VDecl->hasLocalStorage()) 9996 getCurFunction()->setHasBranchProtectedScope(); 9997 9998 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9999 VDecl->setInvalidDecl(); 10000 return; 10001 } 10002 } 10003 10004 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10005 // a kernel function cannot be initialized." 10006 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10007 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10008 VDecl->setInvalidDecl(); 10009 return; 10010 } 10011 10012 // Get the decls type and save a reference for later, since 10013 // CheckInitializerTypes may change it. 10014 QualType DclT = VDecl->getType(), SavT = DclT; 10015 10016 // Expressions default to 'id' when we're in a debugger 10017 // and we are assigning it to a variable of Objective-C pointer type. 10018 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10019 Init->getType() == Context.UnknownAnyTy) { 10020 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10021 if (Result.isInvalid()) { 10022 VDecl->setInvalidDecl(); 10023 return; 10024 } 10025 Init = Result.get(); 10026 } 10027 10028 // Perform the initialization. 10029 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10030 if (!VDecl->isInvalidDecl()) { 10031 // Handle errors like: int a({0}) 10032 if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 && 10033 !canInitializeWithParenthesizedList(VDecl->getType())) 10034 if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) { 10035 Diag(VDecl->getLocation(), diag::err_list_init_in_parens) 10036 << VDecl->getType() << CXXDirectInit->getSourceRange() 10037 << FixItHint::CreateRemoval(CXXDirectInit->getLocStart()) 10038 << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd()); 10039 Init = IList; 10040 CXXDirectInit = nullptr; 10041 } 10042 10043 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10044 InitializationKind Kind = 10045 DirectInit 10046 ? CXXDirectInit 10047 ? InitializationKind::CreateDirect(VDecl->getLocation(), 10048 Init->getLocStart(), 10049 Init->getLocEnd()) 10050 : InitializationKind::CreateDirectList(VDecl->getLocation()) 10051 : InitializationKind::CreateCopy(VDecl->getLocation(), 10052 Init->getLocStart()); 10053 10054 MultiExprArg Args = Init; 10055 if (CXXDirectInit) 10056 Args = MultiExprArg(CXXDirectInit->getExprs(), 10057 CXXDirectInit->getNumExprs()); 10058 10059 // Try to correct any TypoExprs in the initialization arguments. 10060 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10061 ExprResult Res = CorrectDelayedTyposInExpr( 10062 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10063 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10064 return Init.Failed() ? ExprError() : E; 10065 }); 10066 if (Res.isInvalid()) { 10067 VDecl->setInvalidDecl(); 10068 } else if (Res.get() != Args[Idx]) { 10069 Args[Idx] = Res.get(); 10070 } 10071 } 10072 if (VDecl->isInvalidDecl()) 10073 return; 10074 10075 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10076 /*TopLevelOfInitList=*/false, 10077 /*TreatUnavailableAsInvalid=*/false); 10078 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10079 if (Result.isInvalid()) { 10080 VDecl->setInvalidDecl(); 10081 return; 10082 } 10083 10084 Init = Result.getAs<Expr>(); 10085 } 10086 10087 // Check for self-references within variable initializers. 10088 // Variables declared within a function/method body (except for references) 10089 // are handled by a dataflow analysis. 10090 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10091 VDecl->getType()->isReferenceType()) { 10092 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10093 } 10094 10095 // If the type changed, it means we had an incomplete type that was 10096 // completed by the initializer. For example: 10097 // int ary[] = { 1, 3, 5 }; 10098 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10099 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10100 VDecl->setType(DclT); 10101 10102 if (!VDecl->isInvalidDecl()) { 10103 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10104 10105 if (VDecl->hasAttr<BlocksAttr>()) 10106 checkRetainCycles(VDecl, Init); 10107 10108 // It is safe to assign a weak reference into a strong variable. 10109 // Although this code can still have problems: 10110 // id x = self.weakProp; 10111 // id y = self.weakProp; 10112 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10113 // paths through the function. This should be revisited if 10114 // -Wrepeated-use-of-weak is made flow-sensitive. 10115 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 10116 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10117 Init->getLocStart())) 10118 getCurFunction()->markSafeWeakUse(Init); 10119 } 10120 10121 // The initialization is usually a full-expression. 10122 // 10123 // FIXME: If this is a braced initialization of an aggregate, it is not 10124 // an expression, and each individual field initializer is a separate 10125 // full-expression. For instance, in: 10126 // 10127 // struct Temp { ~Temp(); }; 10128 // struct S { S(Temp); }; 10129 // struct T { S a, b; } t = { Temp(), Temp() } 10130 // 10131 // we should destroy the first Temp before constructing the second. 10132 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10133 false, 10134 VDecl->isConstexpr()); 10135 if (Result.isInvalid()) { 10136 VDecl->setInvalidDecl(); 10137 return; 10138 } 10139 Init = Result.get(); 10140 10141 // Attach the initializer to the decl. 10142 VDecl->setInit(Init); 10143 10144 if (VDecl->isLocalVarDecl()) { 10145 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10146 // static storage duration shall be constant expressions or string literals. 10147 // C++ does not have this restriction. 10148 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 10149 const Expr *Culprit; 10150 if (VDecl->getStorageClass() == SC_Static) 10151 CheckForConstantInitializer(Init, DclT); 10152 // C89 is stricter than C99 for non-static aggregate types. 10153 // C89 6.5.7p3: All the expressions [...] in an initializer list 10154 // for an object that has aggregate or union type shall be 10155 // constant expressions. 10156 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10157 isa<InitListExpr>(Init) && 10158 !Init->isConstantInitializer(Context, false, &Culprit)) 10159 Diag(Culprit->getExprLoc(), 10160 diag::ext_aggregate_init_not_constant) 10161 << Culprit->getSourceRange(); 10162 } 10163 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10164 VDecl->getLexicalDeclContext()->isRecord()) { 10165 // This is an in-class initialization for a static data member, e.g., 10166 // 10167 // struct S { 10168 // static const int value = 17; 10169 // }; 10170 10171 // C++ [class.mem]p4: 10172 // A member-declarator can contain a constant-initializer only 10173 // if it declares a static member (9.4) of const integral or 10174 // const enumeration type, see 9.4.2. 10175 // 10176 // C++11 [class.static.data]p3: 10177 // If a non-volatile non-inline const static data member is of integral 10178 // or enumeration type, its declaration in the class definition can 10179 // specify a brace-or-equal-initializer in which every initalizer-clause 10180 // that is an assignment-expression is a constant expression. A static 10181 // data member of literal type can be declared in the class definition 10182 // with the constexpr specifier; if so, its declaration shall specify a 10183 // brace-or-equal-initializer in which every initializer-clause that is 10184 // an assignment-expression is a constant expression. 10185 10186 // Do nothing on dependent types. 10187 if (DclT->isDependentType()) { 10188 10189 // Allow any 'static constexpr' members, whether or not they are of literal 10190 // type. We separately check that every constexpr variable is of literal 10191 // type. 10192 } else if (VDecl->isConstexpr()) { 10193 10194 // Require constness. 10195 } else if (!DclT.isConstQualified()) { 10196 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10197 << Init->getSourceRange(); 10198 VDecl->setInvalidDecl(); 10199 10200 // We allow integer constant expressions in all cases. 10201 } else if (DclT->isIntegralOrEnumerationType()) { 10202 // Check whether the expression is a constant expression. 10203 SourceLocation Loc; 10204 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10205 // In C++11, a non-constexpr const static data member with an 10206 // in-class initializer cannot be volatile. 10207 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10208 else if (Init->isValueDependent()) 10209 ; // Nothing to check. 10210 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10211 ; // Ok, it's an ICE! 10212 else if (Init->isEvaluatable(Context)) { 10213 // If we can constant fold the initializer through heroics, accept it, 10214 // but report this as a use of an extension for -pedantic. 10215 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10216 << Init->getSourceRange(); 10217 } else { 10218 // Otherwise, this is some crazy unknown case. Report the issue at the 10219 // location provided by the isIntegerConstantExpr failed check. 10220 Diag(Loc, diag::err_in_class_initializer_non_constant) 10221 << Init->getSourceRange(); 10222 VDecl->setInvalidDecl(); 10223 } 10224 10225 // We allow foldable floating-point constants as an extension. 10226 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10227 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10228 // it anyway and provide a fixit to add the 'constexpr'. 10229 if (getLangOpts().CPlusPlus11) { 10230 Diag(VDecl->getLocation(), 10231 diag::ext_in_class_initializer_float_type_cxx11) 10232 << DclT << Init->getSourceRange(); 10233 Diag(VDecl->getLocStart(), 10234 diag::note_in_class_initializer_float_type_cxx11) 10235 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10236 } else { 10237 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10238 << DclT << Init->getSourceRange(); 10239 10240 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10241 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10242 << Init->getSourceRange(); 10243 VDecl->setInvalidDecl(); 10244 } 10245 } 10246 10247 // Suggest adding 'constexpr' in C++11 for literal types. 10248 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10249 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10250 << DclT << Init->getSourceRange() 10251 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10252 VDecl->setConstexpr(true); 10253 10254 } else { 10255 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10256 << DclT << Init->getSourceRange(); 10257 VDecl->setInvalidDecl(); 10258 } 10259 } else if (VDecl->isFileVarDecl()) { 10260 // In C, extern is typically used to avoid tentative definitions when 10261 // declaring variables in headers, but adding an intializer makes it a 10262 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10263 // In C++, extern is often used to give implictly static const variables 10264 // external linkage, so don't warn in that case. If selectany is present, 10265 // this might be header code intended for C and C++ inclusion, so apply the 10266 // C++ rules. 10267 if (VDecl->getStorageClass() == SC_Extern && 10268 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10269 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10270 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10271 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10272 Diag(VDecl->getLocation(), diag::warn_extern_init); 10273 10274 // C99 6.7.8p4. All file scoped initializers need to be constant. 10275 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10276 CheckForConstantInitializer(Init, DclT); 10277 } 10278 10279 // We will represent direct-initialization similarly to copy-initialization: 10280 // int x(1); -as-> int x = 1; 10281 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10282 // 10283 // Clients that want to distinguish between the two forms, can check for 10284 // direct initializer using VarDecl::getInitStyle(). 10285 // A major benefit is that clients that don't particularly care about which 10286 // exactly form was it (like the CodeGen) can handle both cases without 10287 // special case code. 10288 10289 // C++ 8.5p11: 10290 // The form of initialization (using parentheses or '=') is generally 10291 // insignificant, but does matter when the entity being initialized has a 10292 // class type. 10293 if (CXXDirectInit) { 10294 assert(DirectInit && "Call-style initializer must be direct init."); 10295 VDecl->setInitStyle(VarDecl::CallInit); 10296 } else if (DirectInit) { 10297 // This must be list-initialization. No other way is direct-initialization. 10298 VDecl->setInitStyle(VarDecl::ListInit); 10299 } 10300 10301 CheckCompleteVariableDeclaration(VDecl); 10302 } 10303 10304 /// ActOnInitializerError - Given that there was an error parsing an 10305 /// initializer for the given declaration, try to return to some form 10306 /// of sanity. 10307 void Sema::ActOnInitializerError(Decl *D) { 10308 // Our main concern here is re-establishing invariants like "a 10309 // variable's type is either dependent or complete". 10310 if (!D || D->isInvalidDecl()) return; 10311 10312 VarDecl *VD = dyn_cast<VarDecl>(D); 10313 if (!VD) return; 10314 10315 // Bindings are not usable if we can't make sense of the initializer. 10316 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10317 for (auto *BD : DD->bindings()) 10318 BD->setInvalidDecl(); 10319 10320 // Auto types are meaningless if we can't make sense of the initializer. 10321 if (ParsingInitForAutoVars.count(D)) { 10322 D->setInvalidDecl(); 10323 return; 10324 } 10325 10326 QualType Ty = VD->getType(); 10327 if (Ty->isDependentType()) return; 10328 10329 // Require a complete type. 10330 if (RequireCompleteType(VD->getLocation(), 10331 Context.getBaseElementType(Ty), 10332 diag::err_typecheck_decl_incomplete_type)) { 10333 VD->setInvalidDecl(); 10334 return; 10335 } 10336 10337 // Require a non-abstract type. 10338 if (RequireNonAbstractType(VD->getLocation(), Ty, 10339 diag::err_abstract_type_in_decl, 10340 AbstractVariableType)) { 10341 VD->setInvalidDecl(); 10342 return; 10343 } 10344 10345 // Don't bother complaining about constructors or destructors, 10346 // though. 10347 } 10348 10349 /// Checks if an object of the given type can be initialized with parenthesized 10350 /// init-list. 10351 /// 10352 /// \param TargetType Type of object being initialized. 10353 /// 10354 /// The function is used to detect wrong initializations, such as 'int({0})'. 10355 /// 10356 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) { 10357 return TargetType->isDependentType() || TargetType->isRecordType() || 10358 TargetType->getContainedAutoType(); 10359 } 10360 10361 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10362 // If there is no declaration, there was an error parsing it. Just ignore it. 10363 if (!RealDecl) 10364 return; 10365 10366 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10367 QualType Type = Var->getType(); 10368 10369 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10370 if (isa<DecompositionDecl>(RealDecl)) { 10371 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10372 Var->setInvalidDecl(); 10373 return; 10374 } 10375 10376 // C++11 [dcl.spec.auto]p3 10377 if (Type->isUndeducedType()) { 10378 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10379 << Var->getDeclName() << Type; 10380 Var->setInvalidDecl(); 10381 return; 10382 } 10383 10384 // C++11 [class.static.data]p3: A static data member can be declared with 10385 // the constexpr specifier; if so, its declaration shall specify 10386 // a brace-or-equal-initializer. 10387 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10388 // the definition of a variable [...] or the declaration of a static data 10389 // member. 10390 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10391 !Var->isThisDeclarationADemotedDefinition()) { 10392 if (Var->isStaticDataMember()) { 10393 // C++1z removes the relevant rule; the in-class declaration is always 10394 // a definition there. 10395 if (!getLangOpts().CPlusPlus1z) { 10396 Diag(Var->getLocation(), 10397 diag::err_constexpr_static_mem_var_requires_init) 10398 << Var->getDeclName(); 10399 Var->setInvalidDecl(); 10400 return; 10401 } 10402 } else { 10403 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10404 Var->setInvalidDecl(); 10405 return; 10406 } 10407 } 10408 10409 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10410 // definition having the concept specifier is called a variable concept. A 10411 // concept definition refers to [...] a variable concept and its initializer. 10412 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10413 if (VTD->isConcept()) { 10414 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10415 Var->setInvalidDecl(); 10416 return; 10417 } 10418 } 10419 10420 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10421 // be initialized. 10422 if (!Var->isInvalidDecl() && 10423 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10424 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10425 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10426 Var->setInvalidDecl(); 10427 return; 10428 } 10429 10430 switch (Var->isThisDeclarationADefinition()) { 10431 case VarDecl::Definition: 10432 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10433 break; 10434 10435 // We have an out-of-line definition of a static data member 10436 // that has an in-class initializer, so we type-check this like 10437 // a declaration. 10438 // 10439 // Fall through 10440 10441 case VarDecl::DeclarationOnly: 10442 // It's only a declaration. 10443 10444 // Block scope. C99 6.7p7: If an identifier for an object is 10445 // declared with no linkage (C99 6.2.2p6), the type for the 10446 // object shall be complete. 10447 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10448 !Var->hasLinkage() && !Var->isInvalidDecl() && 10449 RequireCompleteType(Var->getLocation(), Type, 10450 diag::err_typecheck_decl_incomplete_type)) 10451 Var->setInvalidDecl(); 10452 10453 // Make sure that the type is not abstract. 10454 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10455 RequireNonAbstractType(Var->getLocation(), Type, 10456 diag::err_abstract_type_in_decl, 10457 AbstractVariableType)) 10458 Var->setInvalidDecl(); 10459 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10460 Var->getStorageClass() == SC_PrivateExtern) { 10461 Diag(Var->getLocation(), diag::warn_private_extern); 10462 Diag(Var->getLocation(), diag::note_private_extern); 10463 } 10464 10465 return; 10466 10467 case VarDecl::TentativeDefinition: 10468 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10469 // object that has file scope without an initializer, and without a 10470 // storage-class specifier or with the storage-class specifier "static", 10471 // constitutes a tentative definition. Note: A tentative definition with 10472 // external linkage is valid (C99 6.2.2p5). 10473 if (!Var->isInvalidDecl()) { 10474 if (const IncompleteArrayType *ArrayT 10475 = Context.getAsIncompleteArrayType(Type)) { 10476 if (RequireCompleteType(Var->getLocation(), 10477 ArrayT->getElementType(), 10478 diag::err_illegal_decl_array_incomplete_type)) 10479 Var->setInvalidDecl(); 10480 } else if (Var->getStorageClass() == SC_Static) { 10481 // C99 6.9.2p3: If the declaration of an identifier for an object is 10482 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10483 // declared type shall not be an incomplete type. 10484 // NOTE: code such as the following 10485 // static struct s; 10486 // struct s { int a; }; 10487 // is accepted by gcc. Hence here we issue a warning instead of 10488 // an error and we do not invalidate the static declaration. 10489 // NOTE: to avoid multiple warnings, only check the first declaration. 10490 if (Var->isFirstDecl()) 10491 RequireCompleteType(Var->getLocation(), Type, 10492 diag::ext_typecheck_decl_incomplete_type); 10493 } 10494 } 10495 10496 // Record the tentative definition; we're done. 10497 if (!Var->isInvalidDecl()) 10498 TentativeDefinitions.push_back(Var); 10499 return; 10500 } 10501 10502 // Provide a specific diagnostic for uninitialized variable 10503 // definitions with incomplete array type. 10504 if (Type->isIncompleteArrayType()) { 10505 Diag(Var->getLocation(), 10506 diag::err_typecheck_incomplete_array_needs_initializer); 10507 Var->setInvalidDecl(); 10508 return; 10509 } 10510 10511 // Provide a specific diagnostic for uninitialized variable 10512 // definitions with reference type. 10513 if (Type->isReferenceType()) { 10514 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10515 << Var->getDeclName() 10516 << SourceRange(Var->getLocation(), Var->getLocation()); 10517 Var->setInvalidDecl(); 10518 return; 10519 } 10520 10521 // Do not attempt to type-check the default initializer for a 10522 // variable with dependent type. 10523 if (Type->isDependentType()) 10524 return; 10525 10526 if (Var->isInvalidDecl()) 10527 return; 10528 10529 if (!Var->hasAttr<AliasAttr>()) { 10530 if (RequireCompleteType(Var->getLocation(), 10531 Context.getBaseElementType(Type), 10532 diag::err_typecheck_decl_incomplete_type)) { 10533 Var->setInvalidDecl(); 10534 return; 10535 } 10536 } else { 10537 return; 10538 } 10539 10540 // The variable can not have an abstract class type. 10541 if (RequireNonAbstractType(Var->getLocation(), Type, 10542 diag::err_abstract_type_in_decl, 10543 AbstractVariableType)) { 10544 Var->setInvalidDecl(); 10545 return; 10546 } 10547 10548 // Check for jumps past the implicit initializer. C++0x 10549 // clarifies that this applies to a "variable with automatic 10550 // storage duration", not a "local variable". 10551 // C++11 [stmt.dcl]p3 10552 // A program that jumps from a point where a variable with automatic 10553 // storage duration is not in scope to a point where it is in scope is 10554 // ill-formed unless the variable has scalar type, class type with a 10555 // trivial default constructor and a trivial destructor, a cv-qualified 10556 // version of one of these types, or an array of one of the preceding 10557 // types and is declared without an initializer. 10558 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10559 if (const RecordType *Record 10560 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10561 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10562 // Mark the function for further checking even if the looser rules of 10563 // C++11 do not require such checks, so that we can diagnose 10564 // incompatibilities with C++98. 10565 if (!CXXRecord->isPOD()) 10566 getCurFunction()->setHasBranchProtectedScope(); 10567 } 10568 } 10569 10570 // C++03 [dcl.init]p9: 10571 // If no initializer is specified for an object, and the 10572 // object is of (possibly cv-qualified) non-POD class type (or 10573 // array thereof), the object shall be default-initialized; if 10574 // the object is of const-qualified type, the underlying class 10575 // type shall have a user-declared default 10576 // constructor. Otherwise, if no initializer is specified for 10577 // a non- static object, the object and its subobjects, if 10578 // any, have an indeterminate initial value); if the object 10579 // or any of its subobjects are of const-qualified type, the 10580 // program is ill-formed. 10581 // C++0x [dcl.init]p11: 10582 // If no initializer is specified for an object, the object is 10583 // default-initialized; [...]. 10584 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10585 InitializationKind Kind 10586 = InitializationKind::CreateDefault(Var->getLocation()); 10587 10588 InitializationSequence InitSeq(*this, Entity, Kind, None); 10589 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10590 if (Init.isInvalid()) 10591 Var->setInvalidDecl(); 10592 else if (Init.get()) { 10593 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10594 // This is important for template substitution. 10595 Var->setInitStyle(VarDecl::CallInit); 10596 } 10597 10598 CheckCompleteVariableDeclaration(Var); 10599 } 10600 } 10601 10602 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10603 // If there is no declaration, there was an error parsing it. Ignore it. 10604 if (!D) 10605 return; 10606 10607 VarDecl *VD = dyn_cast<VarDecl>(D); 10608 if (!VD) { 10609 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10610 D->setInvalidDecl(); 10611 return; 10612 } 10613 10614 VD->setCXXForRangeDecl(true); 10615 10616 // for-range-declaration cannot be given a storage class specifier. 10617 int Error = -1; 10618 switch (VD->getStorageClass()) { 10619 case SC_None: 10620 break; 10621 case SC_Extern: 10622 Error = 0; 10623 break; 10624 case SC_Static: 10625 Error = 1; 10626 break; 10627 case SC_PrivateExtern: 10628 Error = 2; 10629 break; 10630 case SC_Auto: 10631 Error = 3; 10632 break; 10633 case SC_Register: 10634 Error = 4; 10635 break; 10636 } 10637 if (Error != -1) { 10638 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10639 << VD->getDeclName() << Error; 10640 D->setInvalidDecl(); 10641 } 10642 } 10643 10644 StmtResult 10645 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10646 IdentifierInfo *Ident, 10647 ParsedAttributes &Attrs, 10648 SourceLocation AttrEnd) { 10649 // C++1y [stmt.iter]p1: 10650 // A range-based for statement of the form 10651 // for ( for-range-identifier : for-range-initializer ) statement 10652 // is equivalent to 10653 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10654 DeclSpec DS(Attrs.getPool().getFactory()); 10655 10656 const char *PrevSpec; 10657 unsigned DiagID; 10658 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10659 getPrintingPolicy()); 10660 10661 Declarator D(DS, Declarator::ForContext); 10662 D.SetIdentifier(Ident, IdentLoc); 10663 D.takeAttributes(Attrs, AttrEnd); 10664 10665 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10666 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10667 EmptyAttrs, IdentLoc); 10668 Decl *Var = ActOnDeclarator(S, D); 10669 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10670 FinalizeDeclaration(Var); 10671 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10672 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10673 } 10674 10675 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10676 if (var->isInvalidDecl()) return; 10677 10678 if (getLangOpts().OpenCL) { 10679 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10680 // initialiser 10681 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10682 !var->hasInit()) { 10683 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10684 << 1 /*Init*/; 10685 var->setInvalidDecl(); 10686 return; 10687 } 10688 } 10689 10690 // In Objective-C, don't allow jumps past the implicit initialization of a 10691 // local retaining variable. 10692 if (getLangOpts().ObjC1 && 10693 var->hasLocalStorage()) { 10694 switch (var->getType().getObjCLifetime()) { 10695 case Qualifiers::OCL_None: 10696 case Qualifiers::OCL_ExplicitNone: 10697 case Qualifiers::OCL_Autoreleasing: 10698 break; 10699 10700 case Qualifiers::OCL_Weak: 10701 case Qualifiers::OCL_Strong: 10702 getCurFunction()->setHasBranchProtectedScope(); 10703 break; 10704 } 10705 } 10706 10707 // Warn about externally-visible variables being defined without a 10708 // prior declaration. We only want to do this for global 10709 // declarations, but we also specifically need to avoid doing it for 10710 // class members because the linkage of an anonymous class can 10711 // change if it's later given a typedef name. 10712 if (var->isThisDeclarationADefinition() && 10713 var->getDeclContext()->getRedeclContext()->isFileContext() && 10714 var->isExternallyVisible() && var->hasLinkage() && 10715 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10716 var->getLocation())) { 10717 // Find a previous declaration that's not a definition. 10718 VarDecl *prev = var->getPreviousDecl(); 10719 while (prev && prev->isThisDeclarationADefinition()) 10720 prev = prev->getPreviousDecl(); 10721 10722 if (!prev) 10723 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10724 } 10725 10726 // Cache the result of checking for constant initialization. 10727 Optional<bool> CacheHasConstInit; 10728 const Expr *CacheCulprit; 10729 auto checkConstInit = [&]() mutable { 10730 if (!CacheHasConstInit) 10731 CacheHasConstInit = var->getInit()->isConstantInitializer( 10732 Context, var->getType()->isReferenceType(), &CacheCulprit); 10733 return *CacheHasConstInit; 10734 }; 10735 10736 if (var->getTLSKind() == VarDecl::TLS_Static) { 10737 if (var->getType().isDestructedType()) { 10738 // GNU C++98 edits for __thread, [basic.start.term]p3: 10739 // The type of an object with thread storage duration shall not 10740 // have a non-trivial destructor. 10741 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10742 if (getLangOpts().CPlusPlus11) 10743 Diag(var->getLocation(), diag::note_use_thread_local); 10744 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10745 if (!checkConstInit()) { 10746 // GNU C++98 edits for __thread, [basic.start.init]p4: 10747 // An object of thread storage duration shall not require dynamic 10748 // initialization. 10749 // FIXME: Need strict checking here. 10750 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10751 << CacheCulprit->getSourceRange(); 10752 if (getLangOpts().CPlusPlus11) 10753 Diag(var->getLocation(), diag::note_use_thread_local); 10754 } 10755 } 10756 } 10757 10758 // Apply section attributes and pragmas to global variables. 10759 bool GlobalStorage = var->hasGlobalStorage(); 10760 if (GlobalStorage && var->isThisDeclarationADefinition() && 10761 ActiveTemplateInstantiations.empty()) { 10762 PragmaStack<StringLiteral *> *Stack = nullptr; 10763 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10764 if (var->getType().isConstQualified()) 10765 Stack = &ConstSegStack; 10766 else if (!var->getInit()) { 10767 Stack = &BSSSegStack; 10768 SectionFlags |= ASTContext::PSF_Write; 10769 } else { 10770 Stack = &DataSegStack; 10771 SectionFlags |= ASTContext::PSF_Write; 10772 } 10773 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10774 var->addAttr(SectionAttr::CreateImplicit( 10775 Context, SectionAttr::Declspec_allocate, 10776 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10777 } 10778 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10779 if (UnifySection(SA->getName(), SectionFlags, var)) 10780 var->dropAttr<SectionAttr>(); 10781 10782 // Apply the init_seg attribute if this has an initializer. If the 10783 // initializer turns out to not be dynamic, we'll end up ignoring this 10784 // attribute. 10785 if (CurInitSeg && var->getInit()) 10786 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10787 CurInitSegLoc)); 10788 } 10789 10790 // All the following checks are C++ only. 10791 if (!getLangOpts().CPlusPlus) { 10792 // If this variable must be emitted, add it as an initializer for the 10793 // current module. 10794 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10795 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10796 return; 10797 } 10798 10799 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10800 CheckCompleteDecompositionDeclaration(DD); 10801 10802 QualType type = var->getType(); 10803 if (type->isDependentType()) return; 10804 10805 // __block variables might require us to capture a copy-initializer. 10806 if (var->hasAttr<BlocksAttr>()) { 10807 // It's currently invalid to ever have a __block variable with an 10808 // array type; should we diagnose that here? 10809 10810 // Regardless, we don't want to ignore array nesting when 10811 // constructing this copy. 10812 if (type->isStructureOrClassType()) { 10813 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10814 SourceLocation poi = var->getLocation(); 10815 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10816 ExprResult result 10817 = PerformMoveOrCopyInitialization( 10818 InitializedEntity::InitializeBlock(poi, type, false), 10819 var, var->getType(), varRef, /*AllowNRVO=*/true); 10820 if (!result.isInvalid()) { 10821 result = MaybeCreateExprWithCleanups(result); 10822 Expr *init = result.getAs<Expr>(); 10823 Context.setBlockVarCopyInits(var, init); 10824 } 10825 } 10826 } 10827 10828 Expr *Init = var->getInit(); 10829 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10830 QualType baseType = Context.getBaseElementType(type); 10831 10832 if (!var->getDeclContext()->isDependentContext() && 10833 Init && !Init->isValueDependent()) { 10834 10835 if (var->isConstexpr()) { 10836 SmallVector<PartialDiagnosticAt, 8> Notes; 10837 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10838 SourceLocation DiagLoc = var->getLocation(); 10839 // If the note doesn't add any useful information other than a source 10840 // location, fold it into the primary diagnostic. 10841 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10842 diag::note_invalid_subexpr_in_const_expr) { 10843 DiagLoc = Notes[0].first; 10844 Notes.clear(); 10845 } 10846 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10847 << var << Init->getSourceRange(); 10848 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10849 Diag(Notes[I].first, Notes[I].second); 10850 } 10851 } else if (var->isUsableInConstantExpressions(Context)) { 10852 // Check whether the initializer of a const variable of integral or 10853 // enumeration type is an ICE now, since we can't tell whether it was 10854 // initialized by a constant expression if we check later. 10855 var->checkInitIsICE(); 10856 } 10857 10858 // Don't emit further diagnostics about constexpr globals since they 10859 // were just diagnosed. 10860 if (!var->isConstexpr() && GlobalStorage && 10861 var->hasAttr<RequireConstantInitAttr>()) { 10862 // FIXME: Need strict checking in C++03 here. 10863 bool DiagErr = getLangOpts().CPlusPlus11 10864 ? !var->checkInitIsICE() : !checkConstInit(); 10865 if (DiagErr) { 10866 auto attr = var->getAttr<RequireConstantInitAttr>(); 10867 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10868 << Init->getSourceRange(); 10869 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10870 << attr->getRange(); 10871 } 10872 } 10873 else if (!var->isConstexpr() && IsGlobal && 10874 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10875 var->getLocation())) { 10876 // Warn about globals which don't have a constant initializer. Don't 10877 // warn about globals with a non-trivial destructor because we already 10878 // warned about them. 10879 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10880 if (!(RD && !RD->hasTrivialDestructor())) { 10881 if (!checkConstInit()) 10882 Diag(var->getLocation(), diag::warn_global_constructor) 10883 << Init->getSourceRange(); 10884 } 10885 } 10886 } 10887 10888 // Require the destructor. 10889 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10890 FinalizeVarWithDestructor(var, recordType); 10891 10892 // If this variable must be emitted, add it as an initializer for the current 10893 // module. 10894 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10895 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10896 } 10897 10898 /// \brief Determines if a variable's alignment is dependent. 10899 static bool hasDependentAlignment(VarDecl *VD) { 10900 if (VD->getType()->isDependentType()) 10901 return true; 10902 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10903 if (I->isAlignmentDependent()) 10904 return true; 10905 return false; 10906 } 10907 10908 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10909 /// any semantic actions necessary after any initializer has been attached. 10910 void 10911 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10912 // Note that we are no longer parsing the initializer for this declaration. 10913 ParsingInitForAutoVars.erase(ThisDecl); 10914 10915 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10916 if (!VD) 10917 return; 10918 10919 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10920 for (auto *BD : DD->bindings()) { 10921 FinalizeDeclaration(BD); 10922 } 10923 } 10924 10925 checkAttributesAfterMerging(*this, *VD); 10926 10927 // Perform TLS alignment check here after attributes attached to the variable 10928 // which may affect the alignment have been processed. Only perform the check 10929 // if the target has a maximum TLS alignment (zero means no constraints). 10930 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10931 // Protect the check so that it's not performed on dependent types and 10932 // dependent alignments (we can't determine the alignment in that case). 10933 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10934 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10935 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10936 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10937 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10938 << (unsigned)MaxAlignChars.getQuantity(); 10939 } 10940 } 10941 } 10942 10943 if (VD->isStaticLocal()) { 10944 if (FunctionDecl *FD = 10945 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10946 // Static locals inherit dll attributes from their function. 10947 if (Attr *A = getDLLAttr(FD)) { 10948 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10949 NewAttr->setInherited(true); 10950 VD->addAttr(NewAttr); 10951 } 10952 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10953 // function, only __shared__ variables may be declared with 10954 // static storage class. 10955 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 10956 CUDADiagIfDeviceCode(VD->getLocation(), 10957 diag::err_device_static_local_var) 10958 << CurrentCUDATarget()) 10959 VD->setInvalidDecl(); 10960 } 10961 } 10962 10963 // Perform check for initializers of device-side global variables. 10964 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10965 // 7.5). We must also apply the same checks to all __shared__ 10966 // variables whether they are local or not. CUDA also allows 10967 // constant initializers for __constant__ and __device__ variables. 10968 if (getLangOpts().CUDA) { 10969 const Expr *Init = VD->getInit(); 10970 if (Init && VD->hasGlobalStorage()) { 10971 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10972 VD->hasAttr<CUDASharedAttr>()) { 10973 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 10974 bool AllowedInit = false; 10975 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10976 AllowedInit = 10977 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10978 // We'll allow constant initializers even if it's a non-empty 10979 // constructor according to CUDA rules. This deviates from NVCC, 10980 // but allows us to handle things like constexpr constructors. 10981 if (!AllowedInit && 10982 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10983 AllowedInit = VD->getInit()->isConstantInitializer( 10984 Context, VD->getType()->isReferenceType()); 10985 10986 // Also make sure that destructor, if there is one, is empty. 10987 if (AllowedInit) 10988 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10989 AllowedInit = 10990 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10991 10992 if (!AllowedInit) { 10993 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10994 ? diag::err_shared_var_init 10995 : diag::err_dynamic_var_init) 10996 << Init->getSourceRange(); 10997 VD->setInvalidDecl(); 10998 } 10999 } else { 11000 // This is a host-side global variable. Check that the initializer is 11001 // callable from the host side. 11002 const FunctionDecl *InitFn = nullptr; 11003 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11004 InitFn = CE->getConstructor(); 11005 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11006 InitFn = CE->getDirectCallee(); 11007 } 11008 if (InitFn) { 11009 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11010 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11011 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11012 << InitFnTarget << InitFn; 11013 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11014 VD->setInvalidDecl(); 11015 } 11016 } 11017 } 11018 } 11019 } 11020 11021 // Grab the dllimport or dllexport attribute off of the VarDecl. 11022 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11023 11024 // Imported static data members cannot be defined out-of-line. 11025 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11026 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11027 VD->isThisDeclarationADefinition()) { 11028 // We allow definitions of dllimport class template static data members 11029 // with a warning. 11030 CXXRecordDecl *Context = 11031 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11032 bool IsClassTemplateMember = 11033 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11034 Context->getDescribedClassTemplate(); 11035 11036 Diag(VD->getLocation(), 11037 IsClassTemplateMember 11038 ? diag::warn_attribute_dllimport_static_field_definition 11039 : diag::err_attribute_dllimport_static_field_definition); 11040 Diag(IA->getLocation(), diag::note_attribute); 11041 if (!IsClassTemplateMember) 11042 VD->setInvalidDecl(); 11043 } 11044 } 11045 11046 // dllimport/dllexport variables cannot be thread local, their TLS index 11047 // isn't exported with the variable. 11048 if (DLLAttr && VD->getTLSKind()) { 11049 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11050 if (F && getDLLAttr(F)) { 11051 assert(VD->isStaticLocal()); 11052 // But if this is a static local in a dlimport/dllexport function, the 11053 // function will never be inlined, which means the var would never be 11054 // imported, so having it marked import/export is safe. 11055 } else { 11056 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11057 << DLLAttr; 11058 VD->setInvalidDecl(); 11059 } 11060 } 11061 11062 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11063 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11064 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11065 VD->dropAttr<UsedAttr>(); 11066 } 11067 } 11068 11069 const DeclContext *DC = VD->getDeclContext(); 11070 // If there's a #pragma GCC visibility in scope, and this isn't a class 11071 // member, set the visibility of this variable. 11072 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11073 AddPushedVisibilityAttribute(VD); 11074 11075 // FIXME: Warn on unused templates. 11076 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 11077 !isa<VarTemplatePartialSpecializationDecl>(VD)) 11078 MarkUnusedFileScopedDecl(VD); 11079 11080 // Now we have parsed the initializer and can update the table of magic 11081 // tag values. 11082 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11083 !VD->getType()->isIntegralOrEnumerationType()) 11084 return; 11085 11086 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11087 const Expr *MagicValueExpr = VD->getInit(); 11088 if (!MagicValueExpr) { 11089 continue; 11090 } 11091 llvm::APSInt MagicValueInt; 11092 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11093 Diag(I->getRange().getBegin(), 11094 diag::err_type_tag_for_datatype_not_ice) 11095 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11096 continue; 11097 } 11098 if (MagicValueInt.getActiveBits() > 64) { 11099 Diag(I->getRange().getBegin(), 11100 diag::err_type_tag_for_datatype_too_large) 11101 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11102 continue; 11103 } 11104 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11105 RegisterTypeTagForDatatype(I->getArgumentKind(), 11106 MagicValue, 11107 I->getMatchingCType(), 11108 I->getLayoutCompatible(), 11109 I->getMustBeNull()); 11110 } 11111 } 11112 11113 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11114 auto *VD = dyn_cast<VarDecl>(DD); 11115 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11116 } 11117 11118 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11119 ArrayRef<Decl *> Group) { 11120 SmallVector<Decl*, 8> Decls; 11121 11122 if (DS.isTypeSpecOwned()) 11123 Decls.push_back(DS.getRepAsDecl()); 11124 11125 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11126 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11127 bool DiagnosedMultipleDecomps = false; 11128 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11129 bool DiagnosedNonDeducedAuto = false; 11130 11131 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11132 if (Decl *D = Group[i]) { 11133 // For declarators, there are some additional syntactic-ish checks we need 11134 // to perform. 11135 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11136 if (!FirstDeclaratorInGroup) 11137 FirstDeclaratorInGroup = DD; 11138 if (!FirstDecompDeclaratorInGroup) 11139 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11140 if (!FirstNonDeducedAutoInGroup && DS.containsPlaceholderType() && 11141 !hasDeducedAuto(DD)) 11142 FirstNonDeducedAutoInGroup = DD; 11143 11144 if (FirstDeclaratorInGroup != DD) { 11145 // A decomposition declaration cannot be combined with any other 11146 // declaration in the same group. 11147 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11148 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11149 diag::err_decomp_decl_not_alone) 11150 << FirstDeclaratorInGroup->getSourceRange() 11151 << DD->getSourceRange(); 11152 DiagnosedMultipleDecomps = true; 11153 } 11154 11155 // A declarator that uses 'auto' in any way other than to declare a 11156 // variable with a deduced type cannot be combined with any other 11157 // declarator in the same group. 11158 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11159 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11160 diag::err_auto_non_deduced_not_alone) 11161 << FirstNonDeducedAutoInGroup->getType() 11162 ->hasAutoForTrailingReturnType() 11163 << FirstDeclaratorInGroup->getSourceRange() 11164 << DD->getSourceRange(); 11165 DiagnosedNonDeducedAuto = true; 11166 } 11167 } 11168 } 11169 11170 Decls.push_back(D); 11171 } 11172 } 11173 11174 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11175 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11176 handleTagNumbering(Tag, S); 11177 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11178 getLangOpts().CPlusPlus) 11179 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11180 } 11181 } 11182 11183 return BuildDeclaratorGroup(Decls); 11184 } 11185 11186 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11187 /// group, performing any necessary semantic checking. 11188 Sema::DeclGroupPtrTy 11189 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11190 // C++14 [dcl.spec.auto]p7: (DR1347) 11191 // If the type that replaces the placeholder type is not the same in each 11192 // deduction, the program is ill-formed. 11193 if (Group.size() > 1) { 11194 QualType Deduced; 11195 VarDecl *DeducedDecl = nullptr; 11196 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11197 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11198 if (!D || D->isInvalidDecl()) 11199 break; 11200 AutoType *AT = D->getType()->getContainedAutoType(); 11201 if (!AT || AT->getDeducedType().isNull()) 11202 continue; 11203 if (Deduced.isNull()) { 11204 Deduced = AT->getDeducedType(); 11205 DeducedDecl = D; 11206 } else if (!Context.hasSameType(AT->getDeducedType(), Deduced)) { 11207 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11208 diag::err_auto_different_deductions) 11209 << (unsigned)AT->getKeyword() 11210 << Deduced << DeducedDecl->getDeclName() 11211 << AT->getDeducedType() << D->getDeclName() 11212 << DeducedDecl->getInit()->getSourceRange() 11213 << D->getInit()->getSourceRange(); 11214 D->setInvalidDecl(); 11215 break; 11216 } 11217 } 11218 } 11219 11220 ActOnDocumentableDecls(Group); 11221 11222 return DeclGroupPtrTy::make( 11223 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11224 } 11225 11226 void Sema::ActOnDocumentableDecl(Decl *D) { 11227 ActOnDocumentableDecls(D); 11228 } 11229 11230 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11231 // Don't parse the comment if Doxygen diagnostics are ignored. 11232 if (Group.empty() || !Group[0]) 11233 return; 11234 11235 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11236 Group[0]->getLocation()) && 11237 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11238 Group[0]->getLocation())) 11239 return; 11240 11241 if (Group.size() >= 2) { 11242 // This is a decl group. Normally it will contain only declarations 11243 // produced from declarator list. But in case we have any definitions or 11244 // additional declaration references: 11245 // 'typedef struct S {} S;' 11246 // 'typedef struct S *S;' 11247 // 'struct S *pS;' 11248 // FinalizeDeclaratorGroup adds these as separate declarations. 11249 Decl *MaybeTagDecl = Group[0]; 11250 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11251 Group = Group.slice(1); 11252 } 11253 } 11254 11255 // See if there are any new comments that are not attached to a decl. 11256 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11257 if (!Comments.empty() && 11258 !Comments.back()->isAttached()) { 11259 // There is at least one comment that not attached to a decl. 11260 // Maybe it should be attached to one of these decls? 11261 // 11262 // Note that this way we pick up not only comments that precede the 11263 // declaration, but also comments that *follow* the declaration -- thanks to 11264 // the lookahead in the lexer: we've consumed the semicolon and looked 11265 // ahead through comments. 11266 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11267 Context.getCommentForDecl(Group[i], &PP); 11268 } 11269 } 11270 11271 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11272 /// to introduce parameters into function prototype scope. 11273 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11274 const DeclSpec &DS = D.getDeclSpec(); 11275 11276 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11277 11278 // C++03 [dcl.stc]p2 also permits 'auto'. 11279 StorageClass SC = SC_None; 11280 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11281 SC = SC_Register; 11282 } else if (getLangOpts().CPlusPlus && 11283 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11284 SC = SC_Auto; 11285 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11286 Diag(DS.getStorageClassSpecLoc(), 11287 diag::err_invalid_storage_class_in_func_decl); 11288 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11289 } 11290 11291 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11292 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11293 << DeclSpec::getSpecifierName(TSCS); 11294 if (DS.isInlineSpecified()) 11295 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11296 << getLangOpts().CPlusPlus1z; 11297 if (DS.isConstexprSpecified()) 11298 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11299 << 0; 11300 if (DS.isConceptSpecified()) 11301 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11302 11303 DiagnoseFunctionSpecifiers(DS); 11304 11305 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11306 QualType parmDeclType = TInfo->getType(); 11307 11308 if (getLangOpts().CPlusPlus) { 11309 // Check that there are no default arguments inside the type of this 11310 // parameter. 11311 CheckExtraCXXDefaultArguments(D); 11312 11313 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11314 if (D.getCXXScopeSpec().isSet()) { 11315 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11316 << D.getCXXScopeSpec().getRange(); 11317 D.getCXXScopeSpec().clear(); 11318 } 11319 } 11320 11321 // Ensure we have a valid name 11322 IdentifierInfo *II = nullptr; 11323 if (D.hasName()) { 11324 II = D.getIdentifier(); 11325 if (!II) { 11326 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11327 << GetNameForDeclarator(D).getName(); 11328 D.setInvalidType(true); 11329 } 11330 } 11331 11332 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11333 if (II) { 11334 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11335 ForRedeclaration); 11336 LookupName(R, S); 11337 if (R.isSingleResult()) { 11338 NamedDecl *PrevDecl = R.getFoundDecl(); 11339 if (PrevDecl->isTemplateParameter()) { 11340 // Maybe we will complain about the shadowed template parameter. 11341 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11342 // Just pretend that we didn't see the previous declaration. 11343 PrevDecl = nullptr; 11344 } else if (S->isDeclScope(PrevDecl)) { 11345 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11346 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11347 11348 // Recover by removing the name 11349 II = nullptr; 11350 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11351 D.setInvalidType(true); 11352 } 11353 } 11354 } 11355 11356 // Temporarily put parameter variables in the translation unit, not 11357 // the enclosing context. This prevents them from accidentally 11358 // looking like class members in C++. 11359 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11360 D.getLocStart(), 11361 D.getIdentifierLoc(), II, 11362 parmDeclType, TInfo, 11363 SC); 11364 11365 if (D.isInvalidType()) 11366 New->setInvalidDecl(); 11367 11368 assert(S->isFunctionPrototypeScope()); 11369 assert(S->getFunctionPrototypeDepth() >= 1); 11370 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11371 S->getNextFunctionPrototypeIndex()); 11372 11373 // Add the parameter declaration into this scope. 11374 S->AddDecl(New); 11375 if (II) 11376 IdResolver.AddDecl(New); 11377 11378 ProcessDeclAttributes(S, New, D); 11379 11380 if (D.getDeclSpec().isModulePrivateSpecified()) 11381 Diag(New->getLocation(), diag::err_module_private_local) 11382 << 1 << New->getDeclName() 11383 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11384 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11385 11386 if (New->hasAttr<BlocksAttr>()) { 11387 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11388 } 11389 return New; 11390 } 11391 11392 /// \brief Synthesizes a variable for a parameter arising from a 11393 /// typedef. 11394 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11395 SourceLocation Loc, 11396 QualType T) { 11397 /* FIXME: setting StartLoc == Loc. 11398 Would it be worth to modify callers so as to provide proper source 11399 location for the unnamed parameters, embedding the parameter's type? */ 11400 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11401 T, Context.getTrivialTypeSourceInfo(T, Loc), 11402 SC_None, nullptr); 11403 Param->setImplicit(); 11404 return Param; 11405 } 11406 11407 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11408 // Don't diagnose unused-parameter errors in template instantiations; we 11409 // will already have done so in the template itself. 11410 if (!ActiveTemplateInstantiations.empty()) 11411 return; 11412 11413 for (const ParmVarDecl *Parameter : Parameters) { 11414 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11415 !Parameter->hasAttr<UnusedAttr>()) { 11416 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11417 << Parameter->getDeclName(); 11418 } 11419 } 11420 } 11421 11422 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11423 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11424 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11425 return; 11426 11427 // Warn if the return value is pass-by-value and larger than the specified 11428 // threshold. 11429 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11430 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11431 if (Size > LangOpts.NumLargeByValueCopy) 11432 Diag(D->getLocation(), diag::warn_return_value_size) 11433 << D->getDeclName() << Size; 11434 } 11435 11436 // Warn if any parameter is pass-by-value and larger than the specified 11437 // threshold. 11438 for (const ParmVarDecl *Parameter : Parameters) { 11439 QualType T = Parameter->getType(); 11440 if (T->isDependentType() || !T.isPODType(Context)) 11441 continue; 11442 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11443 if (Size > LangOpts.NumLargeByValueCopy) 11444 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11445 << Parameter->getDeclName() << Size; 11446 } 11447 } 11448 11449 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11450 SourceLocation NameLoc, IdentifierInfo *Name, 11451 QualType T, TypeSourceInfo *TSInfo, 11452 StorageClass SC) { 11453 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11454 if (getLangOpts().ObjCAutoRefCount && 11455 T.getObjCLifetime() == Qualifiers::OCL_None && 11456 T->isObjCLifetimeType()) { 11457 11458 Qualifiers::ObjCLifetime lifetime; 11459 11460 // Special cases for arrays: 11461 // - if it's const, use __unsafe_unretained 11462 // - otherwise, it's an error 11463 if (T->isArrayType()) { 11464 if (!T.isConstQualified()) { 11465 DelayedDiagnostics.add( 11466 sema::DelayedDiagnostic::makeForbiddenType( 11467 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11468 } 11469 lifetime = Qualifiers::OCL_ExplicitNone; 11470 } else { 11471 lifetime = T->getObjCARCImplicitLifetime(); 11472 } 11473 T = Context.getLifetimeQualifiedType(T, lifetime); 11474 } 11475 11476 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11477 Context.getAdjustedParameterType(T), 11478 TSInfo, SC, nullptr); 11479 11480 // Parameters can not be abstract class types. 11481 // For record types, this is done by the AbstractClassUsageDiagnoser once 11482 // the class has been completely parsed. 11483 if (!CurContext->isRecord() && 11484 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11485 AbstractParamType)) 11486 New->setInvalidDecl(); 11487 11488 // Parameter declarators cannot be interface types. All ObjC objects are 11489 // passed by reference. 11490 if (T->isObjCObjectType()) { 11491 SourceLocation TypeEndLoc = 11492 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11493 Diag(NameLoc, 11494 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11495 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11496 T = Context.getObjCObjectPointerType(T); 11497 New->setType(T); 11498 } 11499 11500 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11501 // duration shall not be qualified by an address-space qualifier." 11502 // Since all parameters have automatic store duration, they can not have 11503 // an address space. 11504 if (T.getAddressSpace() != 0) { 11505 // OpenCL allows function arguments declared to be an array of a type 11506 // to be qualified with an address space. 11507 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11508 Diag(NameLoc, diag::err_arg_with_address_space); 11509 New->setInvalidDecl(); 11510 } 11511 } 11512 11513 return New; 11514 } 11515 11516 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11517 SourceLocation LocAfterDecls) { 11518 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11519 11520 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11521 // for a K&R function. 11522 if (!FTI.hasPrototype) { 11523 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11524 --i; 11525 if (FTI.Params[i].Param == nullptr) { 11526 SmallString<256> Code; 11527 llvm::raw_svector_ostream(Code) 11528 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11529 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11530 << FTI.Params[i].Ident 11531 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11532 11533 // Implicitly declare the argument as type 'int' for lack of a better 11534 // type. 11535 AttributeFactory attrs; 11536 DeclSpec DS(attrs); 11537 const char* PrevSpec; // unused 11538 unsigned DiagID; // unused 11539 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11540 DiagID, Context.getPrintingPolicy()); 11541 // Use the identifier location for the type source range. 11542 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11543 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11544 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11545 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11546 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11547 } 11548 } 11549 } 11550 } 11551 11552 Decl * 11553 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11554 MultiTemplateParamsArg TemplateParameterLists, 11555 SkipBodyInfo *SkipBody) { 11556 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11557 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11558 Scope *ParentScope = FnBodyScope->getParent(); 11559 11560 D.setFunctionDefinitionKind(FDK_Definition); 11561 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11562 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11563 } 11564 11565 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11566 Consumer.HandleInlineFunctionDefinition(D); 11567 } 11568 11569 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11570 const FunctionDecl*& PossibleZeroParamPrototype) { 11571 // Don't warn about invalid declarations. 11572 if (FD->isInvalidDecl()) 11573 return false; 11574 11575 // Or declarations that aren't global. 11576 if (!FD->isGlobal()) 11577 return false; 11578 11579 // Don't warn about C++ member functions. 11580 if (isa<CXXMethodDecl>(FD)) 11581 return false; 11582 11583 // Don't warn about 'main'. 11584 if (FD->isMain()) 11585 return false; 11586 11587 // Don't warn about inline functions. 11588 if (FD->isInlined()) 11589 return false; 11590 11591 // Don't warn about function templates. 11592 if (FD->getDescribedFunctionTemplate()) 11593 return false; 11594 11595 // Don't warn about function template specializations. 11596 if (FD->isFunctionTemplateSpecialization()) 11597 return false; 11598 11599 // Don't warn for OpenCL kernels. 11600 if (FD->hasAttr<OpenCLKernelAttr>()) 11601 return false; 11602 11603 // Don't warn on explicitly deleted functions. 11604 if (FD->isDeleted()) 11605 return false; 11606 11607 bool MissingPrototype = true; 11608 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11609 Prev; Prev = Prev->getPreviousDecl()) { 11610 // Ignore any declarations that occur in function or method 11611 // scope, because they aren't visible from the header. 11612 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11613 continue; 11614 11615 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11616 if (FD->getNumParams() == 0) 11617 PossibleZeroParamPrototype = Prev; 11618 break; 11619 } 11620 11621 return MissingPrototype; 11622 } 11623 11624 void 11625 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11626 const FunctionDecl *EffectiveDefinition, 11627 SkipBodyInfo *SkipBody) { 11628 // Don't complain if we're in GNU89 mode and the previous definition 11629 // was an extern inline function. 11630 const FunctionDecl *Definition = EffectiveDefinition; 11631 if (!Definition) 11632 if (!FD->isDefined(Definition)) 11633 return; 11634 11635 if (canRedefineFunction(Definition, getLangOpts())) 11636 return; 11637 11638 // If we don't have a visible definition of the function, and it's inline or 11639 // a template, skip the new definition. 11640 if (SkipBody && !hasVisibleDefinition(Definition) && 11641 (Definition->getFormalLinkage() == InternalLinkage || 11642 Definition->isInlined() || 11643 Definition->getDescribedFunctionTemplate() || 11644 Definition->getNumTemplateParameterLists())) { 11645 SkipBody->ShouldSkip = true; 11646 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11647 makeMergedDefinitionVisible(TD, FD->getLocation()); 11648 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11649 FD->getLocation()); 11650 return; 11651 } 11652 11653 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11654 Definition->getStorageClass() == SC_Extern) 11655 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11656 << FD->getDeclName() << getLangOpts().CPlusPlus; 11657 else 11658 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11659 11660 Diag(Definition->getLocation(), diag::note_previous_definition); 11661 FD->setInvalidDecl(); 11662 } 11663 11664 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11665 Sema &S) { 11666 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11667 11668 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11669 LSI->CallOperator = CallOperator; 11670 LSI->Lambda = LambdaClass; 11671 LSI->ReturnType = CallOperator->getReturnType(); 11672 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11673 11674 if (LCD == LCD_None) 11675 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11676 else if (LCD == LCD_ByCopy) 11677 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11678 else if (LCD == LCD_ByRef) 11679 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11680 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11681 11682 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11683 LSI->Mutable = !CallOperator->isConst(); 11684 11685 // Add the captures to the LSI so they can be noted as already 11686 // captured within tryCaptureVar. 11687 auto I = LambdaClass->field_begin(); 11688 for (const auto &C : LambdaClass->captures()) { 11689 if (C.capturesVariable()) { 11690 VarDecl *VD = C.getCapturedVar(); 11691 if (VD->isInitCapture()) 11692 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11693 QualType CaptureType = VD->getType(); 11694 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11695 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11696 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11697 /*EllipsisLoc*/C.isPackExpansion() 11698 ? C.getEllipsisLoc() : SourceLocation(), 11699 CaptureType, /*Expr*/ nullptr); 11700 11701 } else if (C.capturesThis()) { 11702 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11703 /*Expr*/ nullptr, 11704 C.getCaptureKind() == LCK_StarThis); 11705 } else { 11706 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11707 } 11708 ++I; 11709 } 11710 } 11711 11712 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11713 SkipBodyInfo *SkipBody) { 11714 // Clear the last template instantiation error context. 11715 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11716 11717 if (!D) 11718 return D; 11719 FunctionDecl *FD = nullptr; 11720 11721 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11722 FD = FunTmpl->getTemplatedDecl(); 11723 else 11724 FD = cast<FunctionDecl>(D); 11725 11726 // See if this is a redefinition. 11727 if (!FD->isLateTemplateParsed()) { 11728 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11729 11730 // If we're skipping the body, we're done. Don't enter the scope. 11731 if (SkipBody && SkipBody->ShouldSkip) 11732 return D; 11733 } 11734 11735 // Mark this function as "will have a body eventually". This lets users to 11736 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11737 // this function. 11738 FD->setWillHaveBody(); 11739 11740 // If we are instantiating a generic lambda call operator, push 11741 // a LambdaScopeInfo onto the function stack. But use the information 11742 // that's already been calculated (ActOnLambdaExpr) to prime the current 11743 // LambdaScopeInfo. 11744 // When the template operator is being specialized, the LambdaScopeInfo, 11745 // has to be properly restored so that tryCaptureVariable doesn't try 11746 // and capture any new variables. In addition when calculating potential 11747 // captures during transformation of nested lambdas, it is necessary to 11748 // have the LSI properly restored. 11749 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11750 assert(ActiveTemplateInstantiations.size() && 11751 "There should be an active template instantiation on the stack " 11752 "when instantiating a generic lambda!"); 11753 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11754 } 11755 else 11756 // Enter a new function scope 11757 PushFunctionScope(); 11758 11759 // Builtin functions cannot be defined. 11760 if (unsigned BuiltinID = FD->getBuiltinID()) { 11761 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11762 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11763 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11764 FD->setInvalidDecl(); 11765 } 11766 } 11767 11768 // The return type of a function definition must be complete 11769 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11770 QualType ResultType = FD->getReturnType(); 11771 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11772 !FD->isInvalidDecl() && 11773 RequireCompleteType(FD->getLocation(), ResultType, 11774 diag::err_func_def_incomplete_result)) 11775 FD->setInvalidDecl(); 11776 11777 if (FnBodyScope) 11778 PushDeclContext(FnBodyScope, FD); 11779 11780 // Check the validity of our function parameters 11781 CheckParmsForFunctionDef(FD->parameters(), 11782 /*CheckParameterNames=*/true); 11783 11784 // Add non-parameter declarations already in the function to the current 11785 // scope. 11786 if (FnBodyScope) { 11787 for (Decl *NPD : FD->decls()) { 11788 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 11789 if (!NonParmDecl) 11790 continue; 11791 assert(!isa<ParmVarDecl>(NonParmDecl) && 11792 "parameters should not be in newly created FD yet"); 11793 11794 // If the decl has a name, make it accessible in the current scope. 11795 if (NonParmDecl->getDeclName()) 11796 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 11797 11798 // Similarly, dive into enums and fish their constants out, making them 11799 // accessible in this scope. 11800 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 11801 for (auto *EI : ED->enumerators()) 11802 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11803 } 11804 } 11805 } 11806 11807 // Introduce our parameters into the function scope 11808 for (auto Param : FD->parameters()) { 11809 Param->setOwningFunction(FD); 11810 11811 // If this has an identifier, add it to the scope stack. 11812 if (Param->getIdentifier() && FnBodyScope) { 11813 CheckShadow(FnBodyScope, Param); 11814 11815 PushOnScopeChains(Param, FnBodyScope); 11816 } 11817 } 11818 11819 // Ensure that the function's exception specification is instantiated. 11820 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11821 ResolveExceptionSpec(D->getLocation(), FPT); 11822 11823 // dllimport cannot be applied to non-inline function definitions. 11824 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11825 !FD->isTemplateInstantiation()) { 11826 assert(!FD->hasAttr<DLLExportAttr>()); 11827 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11828 FD->setInvalidDecl(); 11829 return D; 11830 } 11831 // We want to attach documentation to original Decl (which might be 11832 // a function template). 11833 ActOnDocumentableDecl(D); 11834 if (getCurLexicalContext()->isObjCContainer() && 11835 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11836 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11837 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11838 11839 return D; 11840 } 11841 11842 /// \brief Given the set of return statements within a function body, 11843 /// compute the variables that are subject to the named return value 11844 /// optimization. 11845 /// 11846 /// Each of the variables that is subject to the named return value 11847 /// optimization will be marked as NRVO variables in the AST, and any 11848 /// return statement that has a marked NRVO variable as its NRVO candidate can 11849 /// use the named return value optimization. 11850 /// 11851 /// This function applies a very simplistic algorithm for NRVO: if every return 11852 /// statement in the scope of a variable has the same NRVO candidate, that 11853 /// candidate is an NRVO variable. 11854 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11855 ReturnStmt **Returns = Scope->Returns.data(); 11856 11857 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11858 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11859 if (!NRVOCandidate->isNRVOVariable()) 11860 Returns[I]->setNRVOCandidate(nullptr); 11861 } 11862 } 11863 } 11864 11865 bool Sema::canDelayFunctionBody(const Declarator &D) { 11866 // We can't delay parsing the body of a constexpr function template (yet). 11867 if (D.getDeclSpec().isConstexprSpecified()) 11868 return false; 11869 11870 // We can't delay parsing the body of a function template with a deduced 11871 // return type (yet). 11872 if (D.getDeclSpec().containsPlaceholderType()) { 11873 // If the placeholder introduces a non-deduced trailing return type, 11874 // we can still delay parsing it. 11875 if (D.getNumTypeObjects()) { 11876 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11877 if (Outer.Kind == DeclaratorChunk::Function && 11878 Outer.Fun.hasTrailingReturnType()) { 11879 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11880 return Ty.isNull() || !Ty->isUndeducedType(); 11881 } 11882 } 11883 return false; 11884 } 11885 11886 return true; 11887 } 11888 11889 bool Sema::canSkipFunctionBody(Decl *D) { 11890 // We cannot skip the body of a function (or function template) which is 11891 // constexpr, since we may need to evaluate its body in order to parse the 11892 // rest of the file. 11893 // We cannot skip the body of a function with an undeduced return type, 11894 // because any callers of that function need to know the type. 11895 if (const FunctionDecl *FD = D->getAsFunction()) 11896 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11897 return false; 11898 return Consumer.shouldSkipFunctionBody(D); 11899 } 11900 11901 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11902 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11903 FD->setHasSkippedBody(); 11904 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11905 MD->setHasSkippedBody(); 11906 return Decl; 11907 } 11908 11909 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11910 return ActOnFinishFunctionBody(D, BodyArg, false); 11911 } 11912 11913 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11914 bool IsInstantiation) { 11915 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11916 11917 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11918 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11919 11920 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11921 CheckCompletedCoroutineBody(FD, Body); 11922 11923 if (FD) { 11924 FD->setBody(Body); 11925 11926 if (getLangOpts().CPlusPlus14) { 11927 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11928 FD->getReturnType()->isUndeducedType()) { 11929 // If the function has a deduced result type but contains no 'return' 11930 // statements, the result type as written must be exactly 'auto', and 11931 // the deduced result type is 'void'. 11932 if (!FD->getReturnType()->getAs<AutoType>()) { 11933 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11934 << FD->getReturnType(); 11935 FD->setInvalidDecl(); 11936 } else { 11937 // Substitute 'void' for the 'auto' in the type. 11938 TypeLoc ResultType = getReturnTypeLoc(FD); 11939 Context.adjustDeducedFunctionResultType( 11940 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11941 } 11942 } 11943 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11944 // In C++11, we don't use 'auto' deduction rules for lambda call 11945 // operators because we don't support return type deduction. 11946 auto *LSI = getCurLambda(); 11947 if (LSI->HasImplicitReturnType) { 11948 deduceClosureReturnType(*LSI); 11949 11950 // C++11 [expr.prim.lambda]p4: 11951 // [...] if there are no return statements in the compound-statement 11952 // [the deduced type is] the type void 11953 QualType RetType = 11954 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11955 11956 // Update the return type to the deduced type. 11957 const FunctionProtoType *Proto = 11958 FD->getType()->getAs<FunctionProtoType>(); 11959 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11960 Proto->getExtProtoInfo())); 11961 } 11962 } 11963 11964 // The only way to be included in UndefinedButUsed is if there is an 11965 // ODR use before the definition. Avoid the expensive map lookup if this 11966 // is the first declaration. 11967 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11968 if (!FD->isExternallyVisible()) 11969 UndefinedButUsed.erase(FD); 11970 else if (FD->isInlined() && 11971 !LangOpts.GNUInline && 11972 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11973 UndefinedButUsed.erase(FD); 11974 } 11975 11976 // If the function implicitly returns zero (like 'main') or is naked, 11977 // don't complain about missing return statements. 11978 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11979 WP.disableCheckFallThrough(); 11980 11981 // MSVC permits the use of pure specifier (=0) on function definition, 11982 // defined at class scope, warn about this non-standard construct. 11983 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11984 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11985 11986 if (!FD->isInvalidDecl()) { 11987 // Don't diagnose unused parameters of defaulted or deleted functions. 11988 if (!FD->isDeleted() && !FD->isDefaulted()) 11989 DiagnoseUnusedParameters(FD->parameters()); 11990 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11991 FD->getReturnType(), FD); 11992 11993 // If this is a structor, we need a vtable. 11994 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11995 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11996 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11997 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11998 11999 // Try to apply the named return value optimization. We have to check 12000 // if we can do this here because lambdas keep return statements around 12001 // to deduce an implicit return type. 12002 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12003 !FD->isDependentContext()) 12004 computeNRVO(Body, getCurFunction()); 12005 } 12006 12007 // GNU warning -Wmissing-prototypes: 12008 // Warn if a global function is defined without a previous 12009 // prototype declaration. This warning is issued even if the 12010 // definition itself provides a prototype. The aim is to detect 12011 // global functions that fail to be declared in header files. 12012 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12013 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12014 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12015 12016 if (PossibleZeroParamPrototype) { 12017 // We found a declaration that is not a prototype, 12018 // but that could be a zero-parameter prototype 12019 if (TypeSourceInfo *TI = 12020 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12021 TypeLoc TL = TI->getTypeLoc(); 12022 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12023 Diag(PossibleZeroParamPrototype->getLocation(), 12024 diag::note_declaration_not_a_prototype) 12025 << PossibleZeroParamPrototype 12026 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12027 } 12028 } 12029 12030 // GNU warning -Wstrict-prototypes 12031 // Warn if K&R function is defined without a previous declaration. 12032 // This warning is issued only if the definition itself does not provide 12033 // a prototype. Only K&R definitions do not provide a prototype. 12034 // An empty list in a function declarator that is part of a definition 12035 // of that function specifies that the function has no parameters 12036 // (C99 6.7.5.3p14) 12037 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12038 !LangOpts.CPlusPlus) { 12039 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12040 TypeLoc TL = TI->getTypeLoc(); 12041 FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>(); 12042 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12043 } 12044 } 12045 12046 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12047 const CXXMethodDecl *KeyFunction; 12048 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12049 MD->isVirtual() && 12050 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12051 MD == KeyFunction->getCanonicalDecl()) { 12052 // Update the key-function state if necessary for this ABI. 12053 if (FD->isInlined() && 12054 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12055 Context.setNonKeyFunction(MD); 12056 12057 // If the newly-chosen key function is already defined, then we 12058 // need to mark the vtable as used retroactively. 12059 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12060 const FunctionDecl *Definition; 12061 if (KeyFunction && KeyFunction->isDefined(Definition)) 12062 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12063 } else { 12064 // We just defined they key function; mark the vtable as used. 12065 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12066 } 12067 } 12068 } 12069 12070 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12071 "Function parsing confused"); 12072 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12073 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12074 MD->setBody(Body); 12075 if (!MD->isInvalidDecl()) { 12076 DiagnoseUnusedParameters(MD->parameters()); 12077 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12078 MD->getReturnType(), MD); 12079 12080 if (Body) 12081 computeNRVO(Body, getCurFunction()); 12082 } 12083 if (getCurFunction()->ObjCShouldCallSuper) { 12084 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12085 << MD->getSelector().getAsString(); 12086 getCurFunction()->ObjCShouldCallSuper = false; 12087 } 12088 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12089 const ObjCMethodDecl *InitMethod = nullptr; 12090 bool isDesignated = 12091 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12092 assert(isDesignated && InitMethod); 12093 (void)isDesignated; 12094 12095 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12096 auto IFace = MD->getClassInterface(); 12097 if (!IFace) 12098 return false; 12099 auto SuperD = IFace->getSuperClass(); 12100 if (!SuperD) 12101 return false; 12102 return SuperD->getIdentifier() == 12103 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12104 }; 12105 // Don't issue this warning for unavailable inits or direct subclasses 12106 // of NSObject. 12107 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12108 Diag(MD->getLocation(), 12109 diag::warn_objc_designated_init_missing_super_call); 12110 Diag(InitMethod->getLocation(), 12111 diag::note_objc_designated_init_marked_here); 12112 } 12113 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12114 } 12115 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12116 // Don't issue this warning for unavaialable inits. 12117 if (!MD->isUnavailable()) 12118 Diag(MD->getLocation(), 12119 diag::warn_objc_secondary_init_missing_init_call); 12120 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12121 } 12122 } else { 12123 return nullptr; 12124 } 12125 12126 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12127 DiagnoseUnguardedAvailabilityViolations(dcl); 12128 12129 assert(!getCurFunction()->ObjCShouldCallSuper && 12130 "This should only be set for ObjC methods, which should have been " 12131 "handled in the block above."); 12132 12133 // Verify and clean out per-function state. 12134 if (Body && (!FD || !FD->isDefaulted())) { 12135 // C++ constructors that have function-try-blocks can't have return 12136 // statements in the handlers of that block. (C++ [except.handle]p14) 12137 // Verify this. 12138 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12139 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12140 12141 // Verify that gotos and switch cases don't jump into scopes illegally. 12142 if (getCurFunction()->NeedsScopeChecking() && 12143 !PP.isCodeCompletionEnabled()) 12144 DiagnoseInvalidJumps(Body); 12145 12146 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12147 if (!Destructor->getParent()->isDependentType()) 12148 CheckDestructor(Destructor); 12149 12150 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12151 Destructor->getParent()); 12152 } 12153 12154 // If any errors have occurred, clear out any temporaries that may have 12155 // been leftover. This ensures that these temporaries won't be picked up for 12156 // deletion in some later function. 12157 if (getDiagnostics().hasErrorOccurred() || 12158 getDiagnostics().getSuppressAllDiagnostics()) { 12159 DiscardCleanupsInEvaluationContext(); 12160 } 12161 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12162 !isa<FunctionTemplateDecl>(dcl)) { 12163 // Since the body is valid, issue any analysis-based warnings that are 12164 // enabled. 12165 ActivePolicy = &WP; 12166 } 12167 12168 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12169 (!CheckConstexprFunctionDecl(FD) || 12170 !CheckConstexprFunctionBody(FD, Body))) 12171 FD->setInvalidDecl(); 12172 12173 if (FD && FD->hasAttr<NakedAttr>()) { 12174 for (const Stmt *S : Body->children()) { 12175 // Allow local register variables without initializer as they don't 12176 // require prologue. 12177 bool RegisterVariables = false; 12178 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12179 for (const auto *Decl : DS->decls()) { 12180 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12181 RegisterVariables = 12182 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12183 if (!RegisterVariables) 12184 break; 12185 } 12186 } 12187 } 12188 if (RegisterVariables) 12189 continue; 12190 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12191 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12192 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12193 FD->setInvalidDecl(); 12194 break; 12195 } 12196 } 12197 } 12198 12199 assert(ExprCleanupObjects.size() == 12200 ExprEvalContexts.back().NumCleanupObjects && 12201 "Leftover temporaries in function"); 12202 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12203 assert(MaybeODRUseExprs.empty() && 12204 "Leftover expressions for odr-use checking"); 12205 } 12206 12207 if (!IsInstantiation) 12208 PopDeclContext(); 12209 12210 PopFunctionScopeInfo(ActivePolicy, dcl); 12211 // If any errors have occurred, clear out any temporaries that may have 12212 // been leftover. This ensures that these temporaries won't be picked up for 12213 // deletion in some later function. 12214 if (getDiagnostics().hasErrorOccurred()) { 12215 DiscardCleanupsInEvaluationContext(); 12216 } 12217 12218 return dcl; 12219 } 12220 12221 /// When we finish delayed parsing of an attribute, we must attach it to the 12222 /// relevant Decl. 12223 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12224 ParsedAttributes &Attrs) { 12225 // Always attach attributes to the underlying decl. 12226 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12227 D = TD->getTemplatedDecl(); 12228 ProcessDeclAttributeList(S, D, Attrs.getList()); 12229 12230 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12231 if (Method->isStatic()) 12232 checkThisInStaticMemberFunctionAttributes(Method); 12233 } 12234 12235 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12236 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12237 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12238 IdentifierInfo &II, Scope *S) { 12239 // Before we produce a declaration for an implicitly defined 12240 // function, see whether there was a locally-scoped declaration of 12241 // this name as a function or variable. If so, use that 12242 // (non-visible) declaration, and complain about it. 12243 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12244 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12245 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12246 return ExternCPrev; 12247 } 12248 12249 // Extension in C99. Legal in C90, but warn about it. 12250 unsigned diag_id; 12251 if (II.getName().startswith("__builtin_")) 12252 diag_id = diag::warn_builtin_unknown; 12253 else if (getLangOpts().C99) 12254 diag_id = diag::ext_implicit_function_decl; 12255 else 12256 diag_id = diag::warn_implicit_function_decl; 12257 Diag(Loc, diag_id) << &II; 12258 12259 // Because typo correction is expensive, only do it if the implicit 12260 // function declaration is going to be treated as an error. 12261 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12262 TypoCorrection Corrected; 12263 if (S && 12264 (Corrected = CorrectTypo( 12265 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12266 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12267 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12268 /*ErrorRecovery*/false); 12269 } 12270 12271 // Set a Declarator for the implicit definition: int foo(); 12272 const char *Dummy; 12273 AttributeFactory attrFactory; 12274 DeclSpec DS(attrFactory); 12275 unsigned DiagID; 12276 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12277 Context.getPrintingPolicy()); 12278 (void)Error; // Silence warning. 12279 assert(!Error && "Error setting up implicit decl!"); 12280 SourceLocation NoLoc; 12281 Declarator D(DS, Declarator::BlockContext); 12282 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12283 /*IsAmbiguous=*/false, 12284 /*LParenLoc=*/NoLoc, 12285 /*Params=*/nullptr, 12286 /*NumParams=*/0, 12287 /*EllipsisLoc=*/NoLoc, 12288 /*RParenLoc=*/NoLoc, 12289 /*TypeQuals=*/0, 12290 /*RefQualifierIsLvalueRef=*/true, 12291 /*RefQualifierLoc=*/NoLoc, 12292 /*ConstQualifierLoc=*/NoLoc, 12293 /*VolatileQualifierLoc=*/NoLoc, 12294 /*RestrictQualifierLoc=*/NoLoc, 12295 /*MutableLoc=*/NoLoc, 12296 EST_None, 12297 /*ESpecRange=*/SourceRange(), 12298 /*Exceptions=*/nullptr, 12299 /*ExceptionRanges=*/nullptr, 12300 /*NumExceptions=*/0, 12301 /*NoexceptExpr=*/nullptr, 12302 /*ExceptionSpecTokens=*/nullptr, 12303 /*DeclsInPrototype=*/None, 12304 Loc, Loc, D), 12305 DS.getAttributes(), 12306 SourceLocation()); 12307 D.SetIdentifier(&II, Loc); 12308 12309 // Insert this function into translation-unit scope. 12310 12311 DeclContext *PrevDC = CurContext; 12312 CurContext = Context.getTranslationUnitDecl(); 12313 12314 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12315 FD->setImplicit(); 12316 12317 CurContext = PrevDC; 12318 12319 AddKnownFunctionAttributes(FD); 12320 12321 return FD; 12322 } 12323 12324 /// \brief Adds any function attributes that we know a priori based on 12325 /// the declaration of this function. 12326 /// 12327 /// These attributes can apply both to implicitly-declared builtins 12328 /// (like __builtin___printf_chk) or to library-declared functions 12329 /// like NSLog or printf. 12330 /// 12331 /// We need to check for duplicate attributes both here and where user-written 12332 /// attributes are applied to declarations. 12333 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12334 if (FD->isInvalidDecl()) 12335 return; 12336 12337 // If this is a built-in function, map its builtin attributes to 12338 // actual attributes. 12339 if (unsigned BuiltinID = FD->getBuiltinID()) { 12340 // Handle printf-formatting attributes. 12341 unsigned FormatIdx; 12342 bool HasVAListArg; 12343 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12344 if (!FD->hasAttr<FormatAttr>()) { 12345 const char *fmt = "printf"; 12346 unsigned int NumParams = FD->getNumParams(); 12347 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12348 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12349 fmt = "NSString"; 12350 FD->addAttr(FormatAttr::CreateImplicit(Context, 12351 &Context.Idents.get(fmt), 12352 FormatIdx+1, 12353 HasVAListArg ? 0 : FormatIdx+2, 12354 FD->getLocation())); 12355 } 12356 } 12357 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12358 HasVAListArg)) { 12359 if (!FD->hasAttr<FormatAttr>()) 12360 FD->addAttr(FormatAttr::CreateImplicit(Context, 12361 &Context.Idents.get("scanf"), 12362 FormatIdx+1, 12363 HasVAListArg ? 0 : FormatIdx+2, 12364 FD->getLocation())); 12365 } 12366 12367 // Mark const if we don't care about errno and that is the only 12368 // thing preventing the function from being const. This allows 12369 // IRgen to use LLVM intrinsics for such functions. 12370 if (!getLangOpts().MathErrno && 12371 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12372 if (!FD->hasAttr<ConstAttr>()) 12373 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12374 } 12375 12376 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12377 !FD->hasAttr<ReturnsTwiceAttr>()) 12378 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12379 FD->getLocation())); 12380 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12381 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12382 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12383 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12384 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12385 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12386 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12387 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12388 // Add the appropriate attribute, depending on the CUDA compilation mode 12389 // and which target the builtin belongs to. For example, during host 12390 // compilation, aux builtins are __device__, while the rest are __host__. 12391 if (getLangOpts().CUDAIsDevice != 12392 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12393 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12394 else 12395 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12396 } 12397 } 12398 12399 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12400 // throw, add an implicit nothrow attribute to any extern "C" function we come 12401 // across. 12402 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12403 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12404 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12405 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12406 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12407 } 12408 12409 IdentifierInfo *Name = FD->getIdentifier(); 12410 if (!Name) 12411 return; 12412 if ((!getLangOpts().CPlusPlus && 12413 FD->getDeclContext()->isTranslationUnit()) || 12414 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12415 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12416 LinkageSpecDecl::lang_c)) { 12417 // Okay: this could be a libc/libm/Objective-C function we know 12418 // about. 12419 } else 12420 return; 12421 12422 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12423 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12424 // target-specific builtins, perhaps? 12425 if (!FD->hasAttr<FormatAttr>()) 12426 FD->addAttr(FormatAttr::CreateImplicit(Context, 12427 &Context.Idents.get("printf"), 2, 12428 Name->isStr("vasprintf") ? 0 : 3, 12429 FD->getLocation())); 12430 } 12431 12432 if (Name->isStr("__CFStringMakeConstantString")) { 12433 // We already have a __builtin___CFStringMakeConstantString, 12434 // but builds that use -fno-constant-cfstrings don't go through that. 12435 if (!FD->hasAttr<FormatArgAttr>()) 12436 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12437 FD->getLocation())); 12438 } 12439 } 12440 12441 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12442 TypeSourceInfo *TInfo) { 12443 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12444 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12445 12446 if (!TInfo) { 12447 assert(D.isInvalidType() && "no declarator info for valid type"); 12448 TInfo = Context.getTrivialTypeSourceInfo(T); 12449 } 12450 12451 // Scope manipulation handled by caller. 12452 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12453 D.getLocStart(), 12454 D.getIdentifierLoc(), 12455 D.getIdentifier(), 12456 TInfo); 12457 12458 // Bail out immediately if we have an invalid declaration. 12459 if (D.isInvalidType()) { 12460 NewTD->setInvalidDecl(); 12461 return NewTD; 12462 } 12463 12464 if (D.getDeclSpec().isModulePrivateSpecified()) { 12465 if (CurContext->isFunctionOrMethod()) 12466 Diag(NewTD->getLocation(), diag::err_module_private_local) 12467 << 2 << NewTD->getDeclName() 12468 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12469 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12470 else 12471 NewTD->setModulePrivate(); 12472 } 12473 12474 // C++ [dcl.typedef]p8: 12475 // If the typedef declaration defines an unnamed class (or 12476 // enum), the first typedef-name declared by the declaration 12477 // to be that class type (or enum type) is used to denote the 12478 // class type (or enum type) for linkage purposes only. 12479 // We need to check whether the type was declared in the declaration. 12480 switch (D.getDeclSpec().getTypeSpecType()) { 12481 case TST_enum: 12482 case TST_struct: 12483 case TST_interface: 12484 case TST_union: 12485 case TST_class: { 12486 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12487 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12488 break; 12489 } 12490 12491 default: 12492 break; 12493 } 12494 12495 return NewTD; 12496 } 12497 12498 /// \brief Check that this is a valid underlying type for an enum declaration. 12499 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12500 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12501 QualType T = TI->getType(); 12502 12503 if (T->isDependentType()) 12504 return false; 12505 12506 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12507 if (BT->isInteger()) 12508 return false; 12509 12510 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12511 return true; 12512 } 12513 12514 /// Check whether this is a valid redeclaration of a previous enumeration. 12515 /// \return true if the redeclaration was invalid. 12516 bool Sema::CheckEnumRedeclaration( 12517 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12518 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12519 bool IsFixed = !EnumUnderlyingTy.isNull(); 12520 12521 if (IsScoped != Prev->isScoped()) { 12522 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12523 << Prev->isScoped(); 12524 Diag(Prev->getLocation(), diag::note_previous_declaration); 12525 return true; 12526 } 12527 12528 if (IsFixed && Prev->isFixed()) { 12529 if (!EnumUnderlyingTy->isDependentType() && 12530 !Prev->getIntegerType()->isDependentType() && 12531 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12532 Prev->getIntegerType())) { 12533 // TODO: Highlight the underlying type of the redeclaration. 12534 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12535 << EnumUnderlyingTy << Prev->getIntegerType(); 12536 Diag(Prev->getLocation(), diag::note_previous_declaration) 12537 << Prev->getIntegerTypeRange(); 12538 return true; 12539 } 12540 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12541 ; 12542 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12543 ; 12544 } else if (IsFixed != Prev->isFixed()) { 12545 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12546 << Prev->isFixed(); 12547 Diag(Prev->getLocation(), diag::note_previous_declaration); 12548 return true; 12549 } 12550 12551 return false; 12552 } 12553 12554 /// \brief Get diagnostic %select index for tag kind for 12555 /// redeclaration diagnostic message. 12556 /// WARNING: Indexes apply to particular diagnostics only! 12557 /// 12558 /// \returns diagnostic %select index. 12559 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12560 switch (Tag) { 12561 case TTK_Struct: return 0; 12562 case TTK_Interface: return 1; 12563 case TTK_Class: return 2; 12564 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12565 } 12566 } 12567 12568 /// \brief Determine if tag kind is a class-key compatible with 12569 /// class for redeclaration (class, struct, or __interface). 12570 /// 12571 /// \returns true iff the tag kind is compatible. 12572 static bool isClassCompatTagKind(TagTypeKind Tag) 12573 { 12574 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12575 } 12576 12577 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12578 TagTypeKind TTK) { 12579 if (isa<TypedefDecl>(PrevDecl)) 12580 return NTK_Typedef; 12581 else if (isa<TypeAliasDecl>(PrevDecl)) 12582 return NTK_TypeAlias; 12583 else if (isa<ClassTemplateDecl>(PrevDecl)) 12584 return NTK_Template; 12585 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12586 return NTK_TypeAliasTemplate; 12587 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12588 return NTK_TemplateTemplateArgument; 12589 switch (TTK) { 12590 case TTK_Struct: 12591 case TTK_Interface: 12592 case TTK_Class: 12593 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12594 case TTK_Union: 12595 return NTK_NonUnion; 12596 case TTK_Enum: 12597 return NTK_NonEnum; 12598 } 12599 llvm_unreachable("invalid TTK"); 12600 } 12601 12602 /// \brief Determine whether a tag with a given kind is acceptable 12603 /// as a redeclaration of the given tag declaration. 12604 /// 12605 /// \returns true if the new tag kind is acceptable, false otherwise. 12606 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12607 TagTypeKind NewTag, bool isDefinition, 12608 SourceLocation NewTagLoc, 12609 const IdentifierInfo *Name) { 12610 // C++ [dcl.type.elab]p3: 12611 // The class-key or enum keyword present in the 12612 // elaborated-type-specifier shall agree in kind with the 12613 // declaration to which the name in the elaborated-type-specifier 12614 // refers. This rule also applies to the form of 12615 // elaborated-type-specifier that declares a class-name or 12616 // friend class since it can be construed as referring to the 12617 // definition of the class. Thus, in any 12618 // elaborated-type-specifier, the enum keyword shall be used to 12619 // refer to an enumeration (7.2), the union class-key shall be 12620 // used to refer to a union (clause 9), and either the class or 12621 // struct class-key shall be used to refer to a class (clause 9) 12622 // declared using the class or struct class-key. 12623 TagTypeKind OldTag = Previous->getTagKind(); 12624 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12625 if (OldTag == NewTag) 12626 return true; 12627 12628 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12629 // Warn about the struct/class tag mismatch. 12630 bool isTemplate = false; 12631 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12632 isTemplate = Record->getDescribedClassTemplate(); 12633 12634 if (!ActiveTemplateInstantiations.empty()) { 12635 // In a template instantiation, do not offer fix-its for tag mismatches 12636 // since they usually mess up the template instead of fixing the problem. 12637 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12638 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12639 << getRedeclDiagFromTagKind(OldTag); 12640 return true; 12641 } 12642 12643 if (isDefinition) { 12644 // On definitions, check previous tags and issue a fix-it for each 12645 // one that doesn't match the current tag. 12646 if (Previous->getDefinition()) { 12647 // Don't suggest fix-its for redefinitions. 12648 return true; 12649 } 12650 12651 bool previousMismatch = false; 12652 for (auto I : Previous->redecls()) { 12653 if (I->getTagKind() != NewTag) { 12654 if (!previousMismatch) { 12655 previousMismatch = true; 12656 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12657 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12658 << getRedeclDiagFromTagKind(I->getTagKind()); 12659 } 12660 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12661 << getRedeclDiagFromTagKind(NewTag) 12662 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12663 TypeWithKeyword::getTagTypeKindName(NewTag)); 12664 } 12665 } 12666 return true; 12667 } 12668 12669 // Check for a previous definition. If current tag and definition 12670 // are same type, do nothing. If no definition, but disagree with 12671 // with previous tag type, give a warning, but no fix-it. 12672 const TagDecl *Redecl = Previous->getDefinition() ? 12673 Previous->getDefinition() : Previous; 12674 if (Redecl->getTagKind() == NewTag) { 12675 return true; 12676 } 12677 12678 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12679 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12680 << getRedeclDiagFromTagKind(OldTag); 12681 Diag(Redecl->getLocation(), diag::note_previous_use); 12682 12683 // If there is a previous definition, suggest a fix-it. 12684 if (Previous->getDefinition()) { 12685 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12686 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12687 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12688 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12689 } 12690 12691 return true; 12692 } 12693 return false; 12694 } 12695 12696 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12697 /// from an outer enclosing namespace or file scope inside a friend declaration. 12698 /// This should provide the commented out code in the following snippet: 12699 /// namespace N { 12700 /// struct X; 12701 /// namespace M { 12702 /// struct Y { friend struct /*N::*/ X; }; 12703 /// } 12704 /// } 12705 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12706 SourceLocation NameLoc) { 12707 // While the decl is in a namespace, do repeated lookup of that name and see 12708 // if we get the same namespace back. If we do not, continue until 12709 // translation unit scope, at which point we have a fully qualified NNS. 12710 SmallVector<IdentifierInfo *, 4> Namespaces; 12711 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12712 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12713 // This tag should be declared in a namespace, which can only be enclosed by 12714 // other namespaces. Bail if there's an anonymous namespace in the chain. 12715 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12716 if (!Namespace || Namespace->isAnonymousNamespace()) 12717 return FixItHint(); 12718 IdentifierInfo *II = Namespace->getIdentifier(); 12719 Namespaces.push_back(II); 12720 NamedDecl *Lookup = SemaRef.LookupSingleName( 12721 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12722 if (Lookup == Namespace) 12723 break; 12724 } 12725 12726 // Once we have all the namespaces, reverse them to go outermost first, and 12727 // build an NNS. 12728 SmallString<64> Insertion; 12729 llvm::raw_svector_ostream OS(Insertion); 12730 if (DC->isTranslationUnit()) 12731 OS << "::"; 12732 std::reverse(Namespaces.begin(), Namespaces.end()); 12733 for (auto *II : Namespaces) 12734 OS << II->getName() << "::"; 12735 return FixItHint::CreateInsertion(NameLoc, Insertion); 12736 } 12737 12738 /// \brief Determine whether a tag originally declared in context \p OldDC can 12739 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12740 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12741 /// using-declaration). 12742 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12743 DeclContext *NewDC) { 12744 OldDC = OldDC->getRedeclContext(); 12745 NewDC = NewDC->getRedeclContext(); 12746 12747 if (OldDC->Equals(NewDC)) 12748 return true; 12749 12750 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12751 // encloses the other). 12752 if (S.getLangOpts().MSVCCompat && 12753 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12754 return true; 12755 12756 return false; 12757 } 12758 12759 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12760 /// former case, Name will be non-null. In the later case, Name will be null. 12761 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12762 /// reference/declaration/definition of a tag. 12763 /// 12764 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12765 /// trailing-type-specifier) other than one in an alias-declaration. 12766 /// 12767 /// \param SkipBody If non-null, will be set to indicate if the caller should 12768 /// skip the definition of this tag and treat it as if it were a declaration. 12769 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12770 SourceLocation KWLoc, CXXScopeSpec &SS, 12771 IdentifierInfo *Name, SourceLocation NameLoc, 12772 AttributeList *Attr, AccessSpecifier AS, 12773 SourceLocation ModulePrivateLoc, 12774 MultiTemplateParamsArg TemplateParameterLists, 12775 bool &OwnedDecl, bool &IsDependent, 12776 SourceLocation ScopedEnumKWLoc, 12777 bool ScopedEnumUsesClassTag, 12778 TypeResult UnderlyingType, 12779 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12780 // If this is not a definition, it must have a name. 12781 IdentifierInfo *OrigName = Name; 12782 assert((Name != nullptr || TUK == TUK_Definition) && 12783 "Nameless record must be a definition!"); 12784 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12785 12786 OwnedDecl = false; 12787 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12788 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12789 12790 // FIXME: Check explicit specializations more carefully. 12791 bool isExplicitSpecialization = false; 12792 bool Invalid = false; 12793 12794 // We only need to do this matching if we have template parameters 12795 // or a scope specifier, which also conveniently avoids this work 12796 // for non-C++ cases. 12797 if (TemplateParameterLists.size() > 0 || 12798 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12799 if (TemplateParameterList *TemplateParams = 12800 MatchTemplateParametersToScopeSpecifier( 12801 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12802 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12803 if (Kind == TTK_Enum) { 12804 Diag(KWLoc, diag::err_enum_template); 12805 return nullptr; 12806 } 12807 12808 if (TemplateParams->size() > 0) { 12809 // This is a declaration or definition of a class template (which may 12810 // be a member of another template). 12811 12812 if (Invalid) 12813 return nullptr; 12814 12815 OwnedDecl = false; 12816 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12817 SS, Name, NameLoc, Attr, 12818 TemplateParams, AS, 12819 ModulePrivateLoc, 12820 /*FriendLoc*/SourceLocation(), 12821 TemplateParameterLists.size()-1, 12822 TemplateParameterLists.data(), 12823 SkipBody); 12824 return Result.get(); 12825 } else { 12826 // The "template<>" header is extraneous. 12827 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12828 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12829 isExplicitSpecialization = true; 12830 } 12831 } 12832 } 12833 12834 // Figure out the underlying type if this a enum declaration. We need to do 12835 // this early, because it's needed to detect if this is an incompatible 12836 // redeclaration. 12837 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12838 bool EnumUnderlyingIsImplicit = false; 12839 12840 if (Kind == TTK_Enum) { 12841 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12842 // No underlying type explicitly specified, or we failed to parse the 12843 // type, default to int. 12844 EnumUnderlying = Context.IntTy.getTypePtr(); 12845 else if (UnderlyingType.get()) { 12846 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12847 // integral type; any cv-qualification is ignored. 12848 TypeSourceInfo *TI = nullptr; 12849 GetTypeFromParser(UnderlyingType.get(), &TI); 12850 EnumUnderlying = TI; 12851 12852 if (CheckEnumUnderlyingType(TI)) 12853 // Recover by falling back to int. 12854 EnumUnderlying = Context.IntTy.getTypePtr(); 12855 12856 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12857 UPPC_FixedUnderlyingType)) 12858 EnumUnderlying = Context.IntTy.getTypePtr(); 12859 12860 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12861 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12862 // Microsoft enums are always of int type. 12863 EnumUnderlying = Context.IntTy.getTypePtr(); 12864 EnumUnderlyingIsImplicit = true; 12865 } 12866 } 12867 } 12868 12869 DeclContext *SearchDC = CurContext; 12870 DeclContext *DC = CurContext; 12871 bool isStdBadAlloc = false; 12872 bool isStdAlignValT = false; 12873 12874 RedeclarationKind Redecl = ForRedeclaration; 12875 if (TUK == TUK_Friend || TUK == TUK_Reference) 12876 Redecl = NotForRedeclaration; 12877 12878 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12879 if (Name && SS.isNotEmpty()) { 12880 // We have a nested-name tag ('struct foo::bar'). 12881 12882 // Check for invalid 'foo::'. 12883 if (SS.isInvalid()) { 12884 Name = nullptr; 12885 goto CreateNewDecl; 12886 } 12887 12888 // If this is a friend or a reference to a class in a dependent 12889 // context, don't try to make a decl for it. 12890 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12891 DC = computeDeclContext(SS, false); 12892 if (!DC) { 12893 IsDependent = true; 12894 return nullptr; 12895 } 12896 } else { 12897 DC = computeDeclContext(SS, true); 12898 if (!DC) { 12899 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12900 << SS.getRange(); 12901 return nullptr; 12902 } 12903 } 12904 12905 if (RequireCompleteDeclContext(SS, DC)) 12906 return nullptr; 12907 12908 SearchDC = DC; 12909 // Look-up name inside 'foo::'. 12910 LookupQualifiedName(Previous, DC); 12911 12912 if (Previous.isAmbiguous()) 12913 return nullptr; 12914 12915 if (Previous.empty()) { 12916 // Name lookup did not find anything. However, if the 12917 // nested-name-specifier refers to the current instantiation, 12918 // and that current instantiation has any dependent base 12919 // classes, we might find something at instantiation time: treat 12920 // this as a dependent elaborated-type-specifier. 12921 // But this only makes any sense for reference-like lookups. 12922 if (Previous.wasNotFoundInCurrentInstantiation() && 12923 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12924 IsDependent = true; 12925 return nullptr; 12926 } 12927 12928 // A tag 'foo::bar' must already exist. 12929 Diag(NameLoc, diag::err_not_tag_in_scope) 12930 << Kind << Name << DC << SS.getRange(); 12931 Name = nullptr; 12932 Invalid = true; 12933 goto CreateNewDecl; 12934 } 12935 } else if (Name) { 12936 // C++14 [class.mem]p14: 12937 // If T is the name of a class, then each of the following shall have a 12938 // name different from T: 12939 // -- every member of class T that is itself a type 12940 if (TUK != TUK_Reference && TUK != TUK_Friend && 12941 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12942 return nullptr; 12943 12944 // If this is a named struct, check to see if there was a previous forward 12945 // declaration or definition. 12946 // FIXME: We're looking into outer scopes here, even when we 12947 // shouldn't be. Doing so can result in ambiguities that we 12948 // shouldn't be diagnosing. 12949 LookupName(Previous, S); 12950 12951 // When declaring or defining a tag, ignore ambiguities introduced 12952 // by types using'ed into this scope. 12953 if (Previous.isAmbiguous() && 12954 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12955 LookupResult::Filter F = Previous.makeFilter(); 12956 while (F.hasNext()) { 12957 NamedDecl *ND = F.next(); 12958 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12959 SearchDC->getRedeclContext())) 12960 F.erase(); 12961 } 12962 F.done(); 12963 } 12964 12965 // C++11 [namespace.memdef]p3: 12966 // If the name in a friend declaration is neither qualified nor 12967 // a template-id and the declaration is a function or an 12968 // elaborated-type-specifier, the lookup to determine whether 12969 // the entity has been previously declared shall not consider 12970 // any scopes outside the innermost enclosing namespace. 12971 // 12972 // MSVC doesn't implement the above rule for types, so a friend tag 12973 // declaration may be a redeclaration of a type declared in an enclosing 12974 // scope. They do implement this rule for friend functions. 12975 // 12976 // Does it matter that this should be by scope instead of by 12977 // semantic context? 12978 if (!Previous.empty() && TUK == TUK_Friend) { 12979 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12980 LookupResult::Filter F = Previous.makeFilter(); 12981 bool FriendSawTagOutsideEnclosingNamespace = false; 12982 while (F.hasNext()) { 12983 NamedDecl *ND = F.next(); 12984 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12985 if (DC->isFileContext() && 12986 !EnclosingNS->Encloses(ND->getDeclContext())) { 12987 if (getLangOpts().MSVCCompat) 12988 FriendSawTagOutsideEnclosingNamespace = true; 12989 else 12990 F.erase(); 12991 } 12992 } 12993 F.done(); 12994 12995 // Diagnose this MSVC extension in the easy case where lookup would have 12996 // unambiguously found something outside the enclosing namespace. 12997 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12998 NamedDecl *ND = Previous.getFoundDecl(); 12999 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13000 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13001 } 13002 } 13003 13004 // Note: there used to be some attempt at recovery here. 13005 if (Previous.isAmbiguous()) 13006 return nullptr; 13007 13008 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13009 // FIXME: This makes sure that we ignore the contexts associated 13010 // with C structs, unions, and enums when looking for a matching 13011 // tag declaration or definition. See the similar lookup tweak 13012 // in Sema::LookupName; is there a better way to deal with this? 13013 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13014 SearchDC = SearchDC->getParent(); 13015 } 13016 } 13017 13018 if (Previous.isSingleResult() && 13019 Previous.getFoundDecl()->isTemplateParameter()) { 13020 // Maybe we will complain about the shadowed template parameter. 13021 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13022 // Just pretend that we didn't see the previous declaration. 13023 Previous.clear(); 13024 } 13025 13026 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13027 DC->Equals(getStdNamespace())) { 13028 if (Name->isStr("bad_alloc")) { 13029 // This is a declaration of or a reference to "std::bad_alloc". 13030 isStdBadAlloc = true; 13031 13032 // If std::bad_alloc has been implicitly declared (but made invisible to 13033 // name lookup), fill in this implicit declaration as the previous 13034 // declaration, so that the declarations get chained appropriately. 13035 if (Previous.empty() && StdBadAlloc) 13036 Previous.addDecl(getStdBadAlloc()); 13037 } else if (Name->isStr("align_val_t")) { 13038 isStdAlignValT = true; 13039 if (Previous.empty() && StdAlignValT) 13040 Previous.addDecl(getStdAlignValT()); 13041 } 13042 } 13043 13044 // If we didn't find a previous declaration, and this is a reference 13045 // (or friend reference), move to the correct scope. In C++, we 13046 // also need to do a redeclaration lookup there, just in case 13047 // there's a shadow friend decl. 13048 if (Name && Previous.empty() && 13049 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13050 if (Invalid) goto CreateNewDecl; 13051 assert(SS.isEmpty()); 13052 13053 if (TUK == TUK_Reference) { 13054 // C++ [basic.scope.pdecl]p5: 13055 // -- for an elaborated-type-specifier of the form 13056 // 13057 // class-key identifier 13058 // 13059 // if the elaborated-type-specifier is used in the 13060 // decl-specifier-seq or parameter-declaration-clause of a 13061 // function defined in namespace scope, the identifier is 13062 // declared as a class-name in the namespace that contains 13063 // the declaration; otherwise, except as a friend 13064 // declaration, the identifier is declared in the smallest 13065 // non-class, non-function-prototype scope that contains the 13066 // declaration. 13067 // 13068 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13069 // C structs and unions. 13070 // 13071 // It is an error in C++ to declare (rather than define) an enum 13072 // type, including via an elaborated type specifier. We'll 13073 // diagnose that later; for now, declare the enum in the same 13074 // scope as we would have picked for any other tag type. 13075 // 13076 // GNU C also supports this behavior as part of its incomplete 13077 // enum types extension, while GNU C++ does not. 13078 // 13079 // Find the context where we'll be declaring the tag. 13080 // FIXME: We would like to maintain the current DeclContext as the 13081 // lexical context, 13082 SearchDC = getTagInjectionContext(SearchDC); 13083 13084 // Find the scope where we'll be declaring the tag. 13085 S = getTagInjectionScope(S, getLangOpts()); 13086 } else { 13087 assert(TUK == TUK_Friend); 13088 // C++ [namespace.memdef]p3: 13089 // If a friend declaration in a non-local class first declares a 13090 // class or function, the friend class or function is a member of 13091 // the innermost enclosing namespace. 13092 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13093 } 13094 13095 // In C++, we need to do a redeclaration lookup to properly 13096 // diagnose some problems. 13097 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13098 // hidden declaration so that we don't get ambiguity errors when using a 13099 // type declared by an elaborated-type-specifier. In C that is not correct 13100 // and we should instead merge compatible types found by lookup. 13101 if (getLangOpts().CPlusPlus) { 13102 Previous.setRedeclarationKind(ForRedeclaration); 13103 LookupQualifiedName(Previous, SearchDC); 13104 } else { 13105 Previous.setRedeclarationKind(ForRedeclaration); 13106 LookupName(Previous, S); 13107 } 13108 } 13109 13110 // If we have a known previous declaration to use, then use it. 13111 if (Previous.empty() && SkipBody && SkipBody->Previous) 13112 Previous.addDecl(SkipBody->Previous); 13113 13114 if (!Previous.empty()) { 13115 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13116 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13117 13118 // It's okay to have a tag decl in the same scope as a typedef 13119 // which hides a tag decl in the same scope. Finding this 13120 // insanity with a redeclaration lookup can only actually happen 13121 // in C++. 13122 // 13123 // This is also okay for elaborated-type-specifiers, which is 13124 // technically forbidden by the current standard but which is 13125 // okay according to the likely resolution of an open issue; 13126 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13127 if (getLangOpts().CPlusPlus) { 13128 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13129 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13130 TagDecl *Tag = TT->getDecl(); 13131 if (Tag->getDeclName() == Name && 13132 Tag->getDeclContext()->getRedeclContext() 13133 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13134 PrevDecl = Tag; 13135 Previous.clear(); 13136 Previous.addDecl(Tag); 13137 Previous.resolveKind(); 13138 } 13139 } 13140 } 13141 } 13142 13143 // If this is a redeclaration of a using shadow declaration, it must 13144 // declare a tag in the same context. In MSVC mode, we allow a 13145 // redefinition if either context is within the other. 13146 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13147 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13148 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13149 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 13150 !(OldTag && isAcceptableTagRedeclContext( 13151 *this, OldTag->getDeclContext(), SearchDC))) { 13152 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13153 Diag(Shadow->getTargetDecl()->getLocation(), 13154 diag::note_using_decl_target); 13155 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13156 << 0; 13157 // Recover by ignoring the old declaration. 13158 Previous.clear(); 13159 goto CreateNewDecl; 13160 } 13161 } 13162 13163 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13164 // If this is a use of a previous tag, or if the tag is already declared 13165 // in the same scope (so that the definition/declaration completes or 13166 // rementions the tag), reuse the decl. 13167 if (TUK == TUK_Reference || TUK == TUK_Friend || 13168 isDeclInScope(DirectPrevDecl, SearchDC, S, 13169 SS.isNotEmpty() || isExplicitSpecialization)) { 13170 // Make sure that this wasn't declared as an enum and now used as a 13171 // struct or something similar. 13172 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13173 TUK == TUK_Definition, KWLoc, 13174 Name)) { 13175 bool SafeToContinue 13176 = (PrevTagDecl->getTagKind() != TTK_Enum && 13177 Kind != TTK_Enum); 13178 if (SafeToContinue) 13179 Diag(KWLoc, diag::err_use_with_wrong_tag) 13180 << Name 13181 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13182 PrevTagDecl->getKindName()); 13183 else 13184 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13185 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13186 13187 if (SafeToContinue) 13188 Kind = PrevTagDecl->getTagKind(); 13189 else { 13190 // Recover by making this an anonymous redefinition. 13191 Name = nullptr; 13192 Previous.clear(); 13193 Invalid = true; 13194 } 13195 } 13196 13197 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13198 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13199 13200 // If this is an elaborated-type-specifier for a scoped enumeration, 13201 // the 'class' keyword is not necessary and not permitted. 13202 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13203 if (ScopedEnum) 13204 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13205 << PrevEnum->isScoped() 13206 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13207 return PrevTagDecl; 13208 } 13209 13210 QualType EnumUnderlyingTy; 13211 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13212 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13213 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13214 EnumUnderlyingTy = QualType(T, 0); 13215 13216 // All conflicts with previous declarations are recovered by 13217 // returning the previous declaration, unless this is a definition, 13218 // in which case we want the caller to bail out. 13219 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13220 ScopedEnum, EnumUnderlyingTy, 13221 EnumUnderlyingIsImplicit, PrevEnum)) 13222 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13223 } 13224 13225 // C++11 [class.mem]p1: 13226 // A member shall not be declared twice in the member-specification, 13227 // except that a nested class or member class template can be declared 13228 // and then later defined. 13229 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13230 S->isDeclScope(PrevDecl)) { 13231 Diag(NameLoc, diag::ext_member_redeclared); 13232 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13233 } 13234 13235 if (!Invalid) { 13236 // If this is a use, just return the declaration we found, unless 13237 // we have attributes. 13238 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13239 if (Attr) { 13240 // FIXME: Diagnose these attributes. For now, we create a new 13241 // declaration to hold them. 13242 } else if (TUK == TUK_Reference && 13243 (PrevTagDecl->getFriendObjectKind() == 13244 Decl::FOK_Undeclared || 13245 PP.getModuleContainingLocation( 13246 PrevDecl->getLocation()) != 13247 PP.getModuleContainingLocation(KWLoc)) && 13248 SS.isEmpty()) { 13249 // This declaration is a reference to an existing entity, but 13250 // has different visibility from that entity: it either makes 13251 // a friend visible or it makes a type visible in a new module. 13252 // In either case, create a new declaration. We only do this if 13253 // the declaration would have meant the same thing if no prior 13254 // declaration were found, that is, if it was found in the same 13255 // scope where we would have injected a declaration. 13256 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13257 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13258 return PrevTagDecl; 13259 // This is in the injected scope, create a new declaration in 13260 // that scope. 13261 S = getTagInjectionScope(S, getLangOpts()); 13262 } else { 13263 return PrevTagDecl; 13264 } 13265 } 13266 13267 // Diagnose attempts to redefine a tag. 13268 if (TUK == TUK_Definition) { 13269 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13270 // If we're defining a specialization and the previous definition 13271 // is from an implicit instantiation, don't emit an error 13272 // here; we'll catch this in the general case below. 13273 bool IsExplicitSpecializationAfterInstantiation = false; 13274 if (isExplicitSpecialization) { 13275 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13276 IsExplicitSpecializationAfterInstantiation = 13277 RD->getTemplateSpecializationKind() != 13278 TSK_ExplicitSpecialization; 13279 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13280 IsExplicitSpecializationAfterInstantiation = 13281 ED->getTemplateSpecializationKind() != 13282 TSK_ExplicitSpecialization; 13283 } 13284 13285 NamedDecl *Hidden = nullptr; 13286 if (SkipBody && getLangOpts().CPlusPlus && 13287 !hasVisibleDefinition(Def, &Hidden)) { 13288 // There is a definition of this tag, but it is not visible. We 13289 // explicitly make use of C++'s one definition rule here, and 13290 // assume that this definition is identical to the hidden one 13291 // we already have. Make the existing definition visible and 13292 // use it in place of this one. 13293 SkipBody->ShouldSkip = true; 13294 makeMergedDefinitionVisible(Hidden, KWLoc); 13295 return Def; 13296 } else if (!IsExplicitSpecializationAfterInstantiation) { 13297 // A redeclaration in function prototype scope in C isn't 13298 // visible elsewhere, so merely issue a warning. 13299 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13300 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13301 else 13302 Diag(NameLoc, diag::err_redefinition) << Name; 13303 Diag(Def->getLocation(), diag::note_previous_definition); 13304 // If this is a redefinition, recover by making this 13305 // struct be anonymous, which will make any later 13306 // references get the previous definition. 13307 Name = nullptr; 13308 Previous.clear(); 13309 Invalid = true; 13310 } 13311 } else { 13312 // If the type is currently being defined, complain 13313 // about a nested redefinition. 13314 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13315 if (TD->isBeingDefined()) { 13316 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13317 Diag(PrevTagDecl->getLocation(), 13318 diag::note_previous_definition); 13319 Name = nullptr; 13320 Previous.clear(); 13321 Invalid = true; 13322 } 13323 } 13324 13325 // Okay, this is definition of a previously declared or referenced 13326 // tag. We're going to create a new Decl for it. 13327 } 13328 13329 // Okay, we're going to make a redeclaration. If this is some kind 13330 // of reference, make sure we build the redeclaration in the same DC 13331 // as the original, and ignore the current access specifier. 13332 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13333 SearchDC = PrevTagDecl->getDeclContext(); 13334 AS = AS_none; 13335 } 13336 } 13337 // If we get here we have (another) forward declaration or we 13338 // have a definition. Just create a new decl. 13339 13340 } else { 13341 // If we get here, this is a definition of a new tag type in a nested 13342 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13343 // new decl/type. We set PrevDecl to NULL so that the entities 13344 // have distinct types. 13345 Previous.clear(); 13346 } 13347 // If we get here, we're going to create a new Decl. If PrevDecl 13348 // is non-NULL, it's a definition of the tag declared by 13349 // PrevDecl. If it's NULL, we have a new definition. 13350 13351 // Otherwise, PrevDecl is not a tag, but was found with tag 13352 // lookup. This is only actually possible in C++, where a few 13353 // things like templates still live in the tag namespace. 13354 } else { 13355 // Use a better diagnostic if an elaborated-type-specifier 13356 // found the wrong kind of type on the first 13357 // (non-redeclaration) lookup. 13358 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13359 !Previous.isForRedeclaration()) { 13360 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13361 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13362 << Kind; 13363 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13364 Invalid = true; 13365 13366 // Otherwise, only diagnose if the declaration is in scope. 13367 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13368 SS.isNotEmpty() || isExplicitSpecialization)) { 13369 // do nothing 13370 13371 // Diagnose implicit declarations introduced by elaborated types. 13372 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13373 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13374 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13375 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13376 Invalid = true; 13377 13378 // Otherwise it's a declaration. Call out a particularly common 13379 // case here. 13380 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13381 unsigned Kind = 0; 13382 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13383 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13384 << Name << Kind << TND->getUnderlyingType(); 13385 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13386 Invalid = true; 13387 13388 // Otherwise, diagnose. 13389 } else { 13390 // The tag name clashes with something else in the target scope, 13391 // issue an error and recover by making this tag be anonymous. 13392 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13393 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13394 Name = nullptr; 13395 Invalid = true; 13396 } 13397 13398 // The existing declaration isn't relevant to us; we're in a 13399 // new scope, so clear out the previous declaration. 13400 Previous.clear(); 13401 } 13402 } 13403 13404 CreateNewDecl: 13405 13406 TagDecl *PrevDecl = nullptr; 13407 if (Previous.isSingleResult()) 13408 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13409 13410 // If there is an identifier, use the location of the identifier as the 13411 // location of the decl, otherwise use the location of the struct/union 13412 // keyword. 13413 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13414 13415 // Otherwise, create a new declaration. If there is a previous 13416 // declaration of the same entity, the two will be linked via 13417 // PrevDecl. 13418 TagDecl *New; 13419 13420 bool IsForwardReference = false; 13421 if (Kind == TTK_Enum) { 13422 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13423 // enum X { A, B, C } D; D should chain to X. 13424 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13425 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13426 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13427 13428 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13429 StdAlignValT = cast<EnumDecl>(New); 13430 13431 // If this is an undefined enum, warn. 13432 if (TUK != TUK_Definition && !Invalid) { 13433 TagDecl *Def; 13434 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13435 cast<EnumDecl>(New)->isFixed()) { 13436 // C++0x: 7.2p2: opaque-enum-declaration. 13437 // Conflicts are diagnosed above. Do nothing. 13438 } 13439 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13440 Diag(Loc, diag::ext_forward_ref_enum_def) 13441 << New; 13442 Diag(Def->getLocation(), diag::note_previous_definition); 13443 } else { 13444 unsigned DiagID = diag::ext_forward_ref_enum; 13445 if (getLangOpts().MSVCCompat) 13446 DiagID = diag::ext_ms_forward_ref_enum; 13447 else if (getLangOpts().CPlusPlus) 13448 DiagID = diag::err_forward_ref_enum; 13449 Diag(Loc, DiagID); 13450 13451 // If this is a forward-declared reference to an enumeration, make a 13452 // note of it; we won't actually be introducing the declaration into 13453 // the declaration context. 13454 if (TUK == TUK_Reference) 13455 IsForwardReference = true; 13456 } 13457 } 13458 13459 if (EnumUnderlying) { 13460 EnumDecl *ED = cast<EnumDecl>(New); 13461 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13462 ED->setIntegerTypeSourceInfo(TI); 13463 else 13464 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13465 ED->setPromotionType(ED->getIntegerType()); 13466 } 13467 } else { 13468 // struct/union/class 13469 13470 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13471 // struct X { int A; } D; D should chain to X. 13472 if (getLangOpts().CPlusPlus) { 13473 // FIXME: Look for a way to use RecordDecl for simple structs. 13474 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13475 cast_or_null<CXXRecordDecl>(PrevDecl)); 13476 13477 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13478 StdBadAlloc = cast<CXXRecordDecl>(New); 13479 } else 13480 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13481 cast_or_null<RecordDecl>(PrevDecl)); 13482 } 13483 13484 // C++11 [dcl.type]p3: 13485 // A type-specifier-seq shall not define a class or enumeration [...]. 13486 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13487 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13488 << Context.getTagDeclType(New); 13489 Invalid = true; 13490 } 13491 13492 // Maybe add qualifier info. 13493 if (SS.isNotEmpty()) { 13494 if (SS.isSet()) { 13495 // If this is either a declaration or a definition, check the 13496 // nested-name-specifier against the current context. We don't do this 13497 // for explicit specializations, because they have similar checking 13498 // (with more specific diagnostics) in the call to 13499 // CheckMemberSpecialization, below. 13500 if (!isExplicitSpecialization && 13501 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13502 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13503 Invalid = true; 13504 13505 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13506 if (TemplateParameterLists.size() > 0) { 13507 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13508 } 13509 } 13510 else 13511 Invalid = true; 13512 } 13513 13514 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13515 // Add alignment attributes if necessary; these attributes are checked when 13516 // the ASTContext lays out the structure. 13517 // 13518 // It is important for implementing the correct semantics that this 13519 // happen here (in act on tag decl). The #pragma pack stack is 13520 // maintained as a result of parser callbacks which can occur at 13521 // many points during the parsing of a struct declaration (because 13522 // the #pragma tokens are effectively skipped over during the 13523 // parsing of the struct). 13524 if (TUK == TUK_Definition) { 13525 AddAlignmentAttributesForRecord(RD); 13526 AddMsStructLayoutForRecord(RD); 13527 } 13528 } 13529 13530 if (ModulePrivateLoc.isValid()) { 13531 if (isExplicitSpecialization) 13532 Diag(New->getLocation(), diag::err_module_private_specialization) 13533 << 2 13534 << FixItHint::CreateRemoval(ModulePrivateLoc); 13535 // __module_private__ does not apply to local classes. However, we only 13536 // diagnose this as an error when the declaration specifiers are 13537 // freestanding. Here, we just ignore the __module_private__. 13538 else if (!SearchDC->isFunctionOrMethod()) 13539 New->setModulePrivate(); 13540 } 13541 13542 // If this is a specialization of a member class (of a class template), 13543 // check the specialization. 13544 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13545 Invalid = true; 13546 13547 // If we're declaring or defining a tag in function prototype scope in C, 13548 // note that this type can only be used within the function and add it to 13549 // the list of decls to inject into the function definition scope. 13550 if ((Name || Kind == TTK_Enum) && 13551 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13552 if (getLangOpts().CPlusPlus) { 13553 // C++ [dcl.fct]p6: 13554 // Types shall not be defined in return or parameter types. 13555 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13556 Diag(Loc, diag::err_type_defined_in_param_type) 13557 << Name; 13558 Invalid = true; 13559 } 13560 } else if (!PrevDecl) { 13561 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13562 } 13563 } 13564 13565 if (Invalid) 13566 New->setInvalidDecl(); 13567 13568 if (Attr) 13569 ProcessDeclAttributeList(S, New, Attr); 13570 13571 // Set the lexical context. If the tag has a C++ scope specifier, the 13572 // lexical context will be different from the semantic context. 13573 New->setLexicalDeclContext(CurContext); 13574 13575 // Mark this as a friend decl if applicable. 13576 // In Microsoft mode, a friend declaration also acts as a forward 13577 // declaration so we always pass true to setObjectOfFriendDecl to make 13578 // the tag name visible. 13579 if (TUK == TUK_Friend) 13580 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13581 13582 // Set the access specifier. 13583 if (!Invalid && SearchDC->isRecord()) 13584 SetMemberAccessSpecifier(New, PrevDecl, AS); 13585 13586 if (TUK == TUK_Definition) 13587 New->startDefinition(); 13588 13589 // If this has an identifier, add it to the scope stack. 13590 if (TUK == TUK_Friend) { 13591 // We might be replacing an existing declaration in the lookup tables; 13592 // if so, borrow its access specifier. 13593 if (PrevDecl) 13594 New->setAccess(PrevDecl->getAccess()); 13595 13596 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13597 DC->makeDeclVisibleInContext(New); 13598 if (Name) // can be null along some error paths 13599 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13600 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13601 } else if (Name) { 13602 S = getNonFieldDeclScope(S); 13603 PushOnScopeChains(New, S, !IsForwardReference); 13604 if (IsForwardReference) 13605 SearchDC->makeDeclVisibleInContext(New); 13606 } else { 13607 CurContext->addDecl(New); 13608 } 13609 13610 // If this is the C FILE type, notify the AST context. 13611 if (IdentifierInfo *II = New->getIdentifier()) 13612 if (!New->isInvalidDecl() && 13613 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13614 II->isStr("FILE")) 13615 Context.setFILEDecl(New); 13616 13617 if (PrevDecl) 13618 mergeDeclAttributes(New, PrevDecl); 13619 13620 // If there's a #pragma GCC visibility in scope, set the visibility of this 13621 // record. 13622 AddPushedVisibilityAttribute(New); 13623 13624 OwnedDecl = true; 13625 // In C++, don't return an invalid declaration. We can't recover well from 13626 // the cases where we make the type anonymous. 13627 if (Invalid && getLangOpts().CPlusPlus) { 13628 if (New->isBeingDefined()) 13629 if (auto RD = dyn_cast<RecordDecl>(New)) 13630 RD->completeDefinition(); 13631 return nullptr; 13632 } else { 13633 return New; 13634 } 13635 } 13636 13637 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13638 AdjustDeclIfTemplate(TagD); 13639 TagDecl *Tag = cast<TagDecl>(TagD); 13640 13641 // Enter the tag context. 13642 PushDeclContext(S, Tag); 13643 13644 ActOnDocumentableDecl(TagD); 13645 13646 // If there's a #pragma GCC visibility in scope, set the visibility of this 13647 // record. 13648 AddPushedVisibilityAttribute(Tag); 13649 } 13650 13651 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13652 assert(isa<ObjCContainerDecl>(IDecl) && 13653 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13654 DeclContext *OCD = cast<DeclContext>(IDecl); 13655 assert(getContainingDC(OCD) == CurContext && 13656 "The next DeclContext should be lexically contained in the current one."); 13657 CurContext = OCD; 13658 return IDecl; 13659 } 13660 13661 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13662 SourceLocation FinalLoc, 13663 bool IsFinalSpelledSealed, 13664 SourceLocation LBraceLoc) { 13665 AdjustDeclIfTemplate(TagD); 13666 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13667 13668 FieldCollector->StartClass(); 13669 13670 if (!Record->getIdentifier()) 13671 return; 13672 13673 if (FinalLoc.isValid()) 13674 Record->addAttr(new (Context) 13675 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13676 13677 // C++ [class]p2: 13678 // [...] The class-name is also inserted into the scope of the 13679 // class itself; this is known as the injected-class-name. For 13680 // purposes of access checking, the injected-class-name is treated 13681 // as if it were a public member name. 13682 CXXRecordDecl *InjectedClassName 13683 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13684 Record->getLocStart(), Record->getLocation(), 13685 Record->getIdentifier(), 13686 /*PrevDecl=*/nullptr, 13687 /*DelayTypeCreation=*/true); 13688 Context.getTypeDeclType(InjectedClassName, Record); 13689 InjectedClassName->setImplicit(); 13690 InjectedClassName->setAccess(AS_public); 13691 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13692 InjectedClassName->setDescribedClassTemplate(Template); 13693 PushOnScopeChains(InjectedClassName, S); 13694 assert(InjectedClassName->isInjectedClassName() && 13695 "Broken injected-class-name"); 13696 } 13697 13698 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13699 SourceRange BraceRange) { 13700 AdjustDeclIfTemplate(TagD); 13701 TagDecl *Tag = cast<TagDecl>(TagD); 13702 Tag->setBraceRange(BraceRange); 13703 13704 // Make sure we "complete" the definition even it is invalid. 13705 if (Tag->isBeingDefined()) { 13706 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13707 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13708 RD->completeDefinition(); 13709 } 13710 13711 if (isa<CXXRecordDecl>(Tag)) 13712 FieldCollector->FinishClass(); 13713 13714 // Exit this scope of this tag's definition. 13715 PopDeclContext(); 13716 13717 if (getCurLexicalContext()->isObjCContainer() && 13718 Tag->getDeclContext()->isFileContext()) 13719 Tag->setTopLevelDeclInObjCContainer(); 13720 13721 // Notify the consumer that we've defined a tag. 13722 if (!Tag->isInvalidDecl()) 13723 Consumer.HandleTagDeclDefinition(Tag); 13724 } 13725 13726 void Sema::ActOnObjCContainerFinishDefinition() { 13727 // Exit this scope of this interface definition. 13728 PopDeclContext(); 13729 } 13730 13731 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13732 assert(DC == CurContext && "Mismatch of container contexts"); 13733 OriginalLexicalContext = DC; 13734 ActOnObjCContainerFinishDefinition(); 13735 } 13736 13737 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13738 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13739 OriginalLexicalContext = nullptr; 13740 } 13741 13742 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13743 AdjustDeclIfTemplate(TagD); 13744 TagDecl *Tag = cast<TagDecl>(TagD); 13745 Tag->setInvalidDecl(); 13746 13747 // Make sure we "complete" the definition even it is invalid. 13748 if (Tag->isBeingDefined()) { 13749 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13750 RD->completeDefinition(); 13751 } 13752 13753 // We're undoing ActOnTagStartDefinition here, not 13754 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13755 // the FieldCollector. 13756 13757 PopDeclContext(); 13758 } 13759 13760 // Note that FieldName may be null for anonymous bitfields. 13761 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13762 IdentifierInfo *FieldName, 13763 QualType FieldTy, bool IsMsStruct, 13764 Expr *BitWidth, bool *ZeroWidth) { 13765 // Default to true; that shouldn't confuse checks for emptiness 13766 if (ZeroWidth) 13767 *ZeroWidth = true; 13768 13769 // C99 6.7.2.1p4 - verify the field type. 13770 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13771 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13772 // Handle incomplete types with specific error. 13773 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13774 return ExprError(); 13775 if (FieldName) 13776 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13777 << FieldName << FieldTy << BitWidth->getSourceRange(); 13778 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13779 << FieldTy << BitWidth->getSourceRange(); 13780 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13781 UPPC_BitFieldWidth)) 13782 return ExprError(); 13783 13784 // If the bit-width is type- or value-dependent, don't try to check 13785 // it now. 13786 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13787 return BitWidth; 13788 13789 llvm::APSInt Value; 13790 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13791 if (ICE.isInvalid()) 13792 return ICE; 13793 BitWidth = ICE.get(); 13794 13795 if (Value != 0 && ZeroWidth) 13796 *ZeroWidth = false; 13797 13798 // Zero-width bitfield is ok for anonymous field. 13799 if (Value == 0 && FieldName) 13800 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13801 13802 if (Value.isSigned() && Value.isNegative()) { 13803 if (FieldName) 13804 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13805 << FieldName << Value.toString(10); 13806 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13807 << Value.toString(10); 13808 } 13809 13810 if (!FieldTy->isDependentType()) { 13811 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13812 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13813 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13814 13815 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13816 // ABI. 13817 bool CStdConstraintViolation = 13818 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13819 bool MSBitfieldViolation = 13820 Value.ugt(TypeStorageSize) && 13821 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13822 if (CStdConstraintViolation || MSBitfieldViolation) { 13823 unsigned DiagWidth = 13824 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13825 if (FieldName) 13826 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13827 << FieldName << (unsigned)Value.getZExtValue() 13828 << !CStdConstraintViolation << DiagWidth; 13829 13830 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13831 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13832 << DiagWidth; 13833 } 13834 13835 // Warn on types where the user might conceivably expect to get all 13836 // specified bits as value bits: that's all integral types other than 13837 // 'bool'. 13838 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13839 if (FieldName) 13840 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13841 << FieldName << (unsigned)Value.getZExtValue() 13842 << (unsigned)TypeWidth; 13843 else 13844 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13845 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13846 } 13847 } 13848 13849 return BitWidth; 13850 } 13851 13852 /// ActOnField - Each field of a C struct/union is passed into this in order 13853 /// to create a FieldDecl object for it. 13854 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13855 Declarator &D, Expr *BitfieldWidth) { 13856 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13857 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13858 /*InitStyle=*/ICIS_NoInit, AS_public); 13859 return Res; 13860 } 13861 13862 /// HandleField - Analyze a field of a C struct or a C++ data member. 13863 /// 13864 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13865 SourceLocation DeclStart, 13866 Declarator &D, Expr *BitWidth, 13867 InClassInitStyle InitStyle, 13868 AccessSpecifier AS) { 13869 if (D.isDecompositionDeclarator()) { 13870 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13871 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13872 << Decomp.getSourceRange(); 13873 return nullptr; 13874 } 13875 13876 IdentifierInfo *II = D.getIdentifier(); 13877 SourceLocation Loc = DeclStart; 13878 if (II) Loc = D.getIdentifierLoc(); 13879 13880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13881 QualType T = TInfo->getType(); 13882 if (getLangOpts().CPlusPlus) { 13883 CheckExtraCXXDefaultArguments(D); 13884 13885 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13886 UPPC_DataMemberType)) { 13887 D.setInvalidType(); 13888 T = Context.IntTy; 13889 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13890 } 13891 } 13892 13893 // TR 18037 does not allow fields to be declared with address spaces. 13894 if (T.getQualifiers().hasAddressSpace()) { 13895 Diag(Loc, diag::err_field_with_address_space); 13896 D.setInvalidType(); 13897 } 13898 13899 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13900 // used as structure or union field: image, sampler, event or block types. 13901 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13902 T->isSamplerT() || T->isBlockPointerType())) { 13903 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13904 D.setInvalidType(); 13905 } 13906 13907 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13908 13909 if (D.getDeclSpec().isInlineSpecified()) 13910 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13911 << getLangOpts().CPlusPlus1z; 13912 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13913 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13914 diag::err_invalid_thread) 13915 << DeclSpec::getSpecifierName(TSCS); 13916 13917 // Check to see if this name was declared as a member previously 13918 NamedDecl *PrevDecl = nullptr; 13919 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13920 LookupName(Previous, S); 13921 switch (Previous.getResultKind()) { 13922 case LookupResult::Found: 13923 case LookupResult::FoundUnresolvedValue: 13924 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13925 break; 13926 13927 case LookupResult::FoundOverloaded: 13928 PrevDecl = Previous.getRepresentativeDecl(); 13929 break; 13930 13931 case LookupResult::NotFound: 13932 case LookupResult::NotFoundInCurrentInstantiation: 13933 case LookupResult::Ambiguous: 13934 break; 13935 } 13936 Previous.suppressDiagnostics(); 13937 13938 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13939 // Maybe we will complain about the shadowed template parameter. 13940 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13941 // Just pretend that we didn't see the previous declaration. 13942 PrevDecl = nullptr; 13943 } 13944 13945 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13946 PrevDecl = nullptr; 13947 13948 bool Mutable 13949 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13950 SourceLocation TSSL = D.getLocStart(); 13951 FieldDecl *NewFD 13952 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13953 TSSL, AS, PrevDecl, &D); 13954 13955 if (NewFD->isInvalidDecl()) 13956 Record->setInvalidDecl(); 13957 13958 if (D.getDeclSpec().isModulePrivateSpecified()) 13959 NewFD->setModulePrivate(); 13960 13961 if (NewFD->isInvalidDecl() && PrevDecl) { 13962 // Don't introduce NewFD into scope; there's already something 13963 // with the same name in the same scope. 13964 } else if (II) { 13965 PushOnScopeChains(NewFD, S); 13966 } else 13967 Record->addDecl(NewFD); 13968 13969 return NewFD; 13970 } 13971 13972 /// \brief Build a new FieldDecl and check its well-formedness. 13973 /// 13974 /// This routine builds a new FieldDecl given the fields name, type, 13975 /// record, etc. \p PrevDecl should refer to any previous declaration 13976 /// with the same name and in the same scope as the field to be 13977 /// created. 13978 /// 13979 /// \returns a new FieldDecl. 13980 /// 13981 /// \todo The Declarator argument is a hack. It will be removed once 13982 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13983 TypeSourceInfo *TInfo, 13984 RecordDecl *Record, SourceLocation Loc, 13985 bool Mutable, Expr *BitWidth, 13986 InClassInitStyle InitStyle, 13987 SourceLocation TSSL, 13988 AccessSpecifier AS, NamedDecl *PrevDecl, 13989 Declarator *D) { 13990 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13991 bool InvalidDecl = false; 13992 if (D) InvalidDecl = D->isInvalidType(); 13993 13994 // If we receive a broken type, recover by assuming 'int' and 13995 // marking this declaration as invalid. 13996 if (T.isNull()) { 13997 InvalidDecl = true; 13998 T = Context.IntTy; 13999 } 14000 14001 QualType EltTy = Context.getBaseElementType(T); 14002 if (!EltTy->isDependentType()) { 14003 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14004 // Fields of incomplete type force their record to be invalid. 14005 Record->setInvalidDecl(); 14006 InvalidDecl = true; 14007 } else { 14008 NamedDecl *Def; 14009 EltTy->isIncompleteType(&Def); 14010 if (Def && Def->isInvalidDecl()) { 14011 Record->setInvalidDecl(); 14012 InvalidDecl = true; 14013 } 14014 } 14015 } 14016 14017 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14018 if (BitWidth && getLangOpts().OpenCL) { 14019 Diag(Loc, diag::err_opencl_bitfields); 14020 InvalidDecl = true; 14021 } 14022 14023 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14024 // than a variably modified type. 14025 if (!InvalidDecl && T->isVariablyModifiedType()) { 14026 bool SizeIsNegative; 14027 llvm::APSInt Oversized; 14028 14029 TypeSourceInfo *FixedTInfo = 14030 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14031 SizeIsNegative, 14032 Oversized); 14033 if (FixedTInfo) { 14034 Diag(Loc, diag::warn_illegal_constant_array_size); 14035 TInfo = FixedTInfo; 14036 T = FixedTInfo->getType(); 14037 } else { 14038 if (SizeIsNegative) 14039 Diag(Loc, diag::err_typecheck_negative_array_size); 14040 else if (Oversized.getBoolValue()) 14041 Diag(Loc, diag::err_array_too_large) 14042 << Oversized.toString(10); 14043 else 14044 Diag(Loc, diag::err_typecheck_field_variable_size); 14045 InvalidDecl = true; 14046 } 14047 } 14048 14049 // Fields can not have abstract class types 14050 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14051 diag::err_abstract_type_in_decl, 14052 AbstractFieldType)) 14053 InvalidDecl = true; 14054 14055 bool ZeroWidth = false; 14056 if (InvalidDecl) 14057 BitWidth = nullptr; 14058 // If this is declared as a bit-field, check the bit-field. 14059 if (BitWidth) { 14060 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14061 &ZeroWidth).get(); 14062 if (!BitWidth) { 14063 InvalidDecl = true; 14064 BitWidth = nullptr; 14065 ZeroWidth = false; 14066 } 14067 } 14068 14069 // Check that 'mutable' is consistent with the type of the declaration. 14070 if (!InvalidDecl && Mutable) { 14071 unsigned DiagID = 0; 14072 if (T->isReferenceType()) 14073 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14074 : diag::err_mutable_reference; 14075 else if (T.isConstQualified()) 14076 DiagID = diag::err_mutable_const; 14077 14078 if (DiagID) { 14079 SourceLocation ErrLoc = Loc; 14080 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14081 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14082 Diag(ErrLoc, DiagID); 14083 if (DiagID != diag::ext_mutable_reference) { 14084 Mutable = false; 14085 InvalidDecl = true; 14086 } 14087 } 14088 } 14089 14090 // C++11 [class.union]p8 (DR1460): 14091 // At most one variant member of a union may have a 14092 // brace-or-equal-initializer. 14093 if (InitStyle != ICIS_NoInit) 14094 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14095 14096 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14097 BitWidth, Mutable, InitStyle); 14098 if (InvalidDecl) 14099 NewFD->setInvalidDecl(); 14100 14101 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14102 Diag(Loc, diag::err_duplicate_member) << II; 14103 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14104 NewFD->setInvalidDecl(); 14105 } 14106 14107 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14108 if (Record->isUnion()) { 14109 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14110 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14111 if (RDecl->getDefinition()) { 14112 // C++ [class.union]p1: An object of a class with a non-trivial 14113 // constructor, a non-trivial copy constructor, a non-trivial 14114 // destructor, or a non-trivial copy assignment operator 14115 // cannot be a member of a union, nor can an array of such 14116 // objects. 14117 if (CheckNontrivialField(NewFD)) 14118 NewFD->setInvalidDecl(); 14119 } 14120 } 14121 14122 // C++ [class.union]p1: If a union contains a member of reference type, 14123 // the program is ill-formed, except when compiling with MSVC extensions 14124 // enabled. 14125 if (EltTy->isReferenceType()) { 14126 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14127 diag::ext_union_member_of_reference_type : 14128 diag::err_union_member_of_reference_type) 14129 << NewFD->getDeclName() << EltTy; 14130 if (!getLangOpts().MicrosoftExt) 14131 NewFD->setInvalidDecl(); 14132 } 14133 } 14134 } 14135 14136 // FIXME: We need to pass in the attributes given an AST 14137 // representation, not a parser representation. 14138 if (D) { 14139 // FIXME: The current scope is almost... but not entirely... correct here. 14140 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14141 14142 if (NewFD->hasAttrs()) 14143 CheckAlignasUnderalignment(NewFD); 14144 } 14145 14146 // In auto-retain/release, infer strong retension for fields of 14147 // retainable type. 14148 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14149 NewFD->setInvalidDecl(); 14150 14151 if (T.isObjCGCWeak()) 14152 Diag(Loc, diag::warn_attribute_weak_on_field); 14153 14154 NewFD->setAccess(AS); 14155 return NewFD; 14156 } 14157 14158 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14159 assert(FD); 14160 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14161 14162 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14163 return false; 14164 14165 QualType EltTy = Context.getBaseElementType(FD->getType()); 14166 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14167 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14168 if (RDecl->getDefinition()) { 14169 // We check for copy constructors before constructors 14170 // because otherwise we'll never get complaints about 14171 // copy constructors. 14172 14173 CXXSpecialMember member = CXXInvalid; 14174 // We're required to check for any non-trivial constructors. Since the 14175 // implicit default constructor is suppressed if there are any 14176 // user-declared constructors, we just need to check that there is a 14177 // trivial default constructor and a trivial copy constructor. (We don't 14178 // worry about move constructors here, since this is a C++98 check.) 14179 if (RDecl->hasNonTrivialCopyConstructor()) 14180 member = CXXCopyConstructor; 14181 else if (!RDecl->hasTrivialDefaultConstructor()) 14182 member = CXXDefaultConstructor; 14183 else if (RDecl->hasNonTrivialCopyAssignment()) 14184 member = CXXCopyAssignment; 14185 else if (RDecl->hasNonTrivialDestructor()) 14186 member = CXXDestructor; 14187 14188 if (member != CXXInvalid) { 14189 if (!getLangOpts().CPlusPlus11 && 14190 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14191 // Objective-C++ ARC: it is an error to have a non-trivial field of 14192 // a union. However, system headers in Objective-C programs 14193 // occasionally have Objective-C lifetime objects within unions, 14194 // and rather than cause the program to fail, we make those 14195 // members unavailable. 14196 SourceLocation Loc = FD->getLocation(); 14197 if (getSourceManager().isInSystemHeader(Loc)) { 14198 if (!FD->hasAttr<UnavailableAttr>()) 14199 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14200 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14201 return false; 14202 } 14203 } 14204 14205 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14206 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14207 diag::err_illegal_union_or_anon_struct_member) 14208 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14209 DiagnoseNontrivial(RDecl, member); 14210 return !getLangOpts().CPlusPlus11; 14211 } 14212 } 14213 } 14214 14215 return false; 14216 } 14217 14218 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14219 /// AST enum value. 14220 static ObjCIvarDecl::AccessControl 14221 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14222 switch (ivarVisibility) { 14223 default: llvm_unreachable("Unknown visitibility kind"); 14224 case tok::objc_private: return ObjCIvarDecl::Private; 14225 case tok::objc_public: return ObjCIvarDecl::Public; 14226 case tok::objc_protected: return ObjCIvarDecl::Protected; 14227 case tok::objc_package: return ObjCIvarDecl::Package; 14228 } 14229 } 14230 14231 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14232 /// in order to create an IvarDecl object for it. 14233 Decl *Sema::ActOnIvar(Scope *S, 14234 SourceLocation DeclStart, 14235 Declarator &D, Expr *BitfieldWidth, 14236 tok::ObjCKeywordKind Visibility) { 14237 14238 IdentifierInfo *II = D.getIdentifier(); 14239 Expr *BitWidth = (Expr*)BitfieldWidth; 14240 SourceLocation Loc = DeclStart; 14241 if (II) Loc = D.getIdentifierLoc(); 14242 14243 // FIXME: Unnamed fields can be handled in various different ways, for 14244 // example, unnamed unions inject all members into the struct namespace! 14245 14246 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14247 QualType T = TInfo->getType(); 14248 14249 if (BitWidth) { 14250 // 6.7.2.1p3, 6.7.2.1p4 14251 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14252 if (!BitWidth) 14253 D.setInvalidType(); 14254 } else { 14255 // Not a bitfield. 14256 14257 // validate II. 14258 14259 } 14260 if (T->isReferenceType()) { 14261 Diag(Loc, diag::err_ivar_reference_type); 14262 D.setInvalidType(); 14263 } 14264 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14265 // than a variably modified type. 14266 else if (T->isVariablyModifiedType()) { 14267 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14268 D.setInvalidType(); 14269 } 14270 14271 // Get the visibility (access control) for this ivar. 14272 ObjCIvarDecl::AccessControl ac = 14273 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14274 : ObjCIvarDecl::None; 14275 // Must set ivar's DeclContext to its enclosing interface. 14276 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14277 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14278 return nullptr; 14279 ObjCContainerDecl *EnclosingContext; 14280 if (ObjCImplementationDecl *IMPDecl = 14281 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14282 if (LangOpts.ObjCRuntime.isFragile()) { 14283 // Case of ivar declared in an implementation. Context is that of its class. 14284 EnclosingContext = IMPDecl->getClassInterface(); 14285 assert(EnclosingContext && "Implementation has no class interface!"); 14286 } 14287 else 14288 EnclosingContext = EnclosingDecl; 14289 } else { 14290 if (ObjCCategoryDecl *CDecl = 14291 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14292 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14293 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14294 return nullptr; 14295 } 14296 } 14297 EnclosingContext = EnclosingDecl; 14298 } 14299 14300 // Construct the decl. 14301 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14302 DeclStart, Loc, II, T, 14303 TInfo, ac, (Expr *)BitfieldWidth); 14304 14305 if (II) { 14306 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14307 ForRedeclaration); 14308 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14309 && !isa<TagDecl>(PrevDecl)) { 14310 Diag(Loc, diag::err_duplicate_member) << II; 14311 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14312 NewID->setInvalidDecl(); 14313 } 14314 } 14315 14316 // Process attributes attached to the ivar. 14317 ProcessDeclAttributes(S, NewID, D); 14318 14319 if (D.isInvalidType()) 14320 NewID->setInvalidDecl(); 14321 14322 // In ARC, infer 'retaining' for ivars of retainable type. 14323 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14324 NewID->setInvalidDecl(); 14325 14326 if (D.getDeclSpec().isModulePrivateSpecified()) 14327 NewID->setModulePrivate(); 14328 14329 if (II) { 14330 // FIXME: When interfaces are DeclContexts, we'll need to add 14331 // these to the interface. 14332 S->AddDecl(NewID); 14333 IdResolver.AddDecl(NewID); 14334 } 14335 14336 if (LangOpts.ObjCRuntime.isNonFragile() && 14337 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14338 Diag(Loc, diag::warn_ivars_in_interface); 14339 14340 return NewID; 14341 } 14342 14343 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14344 /// class and class extensions. For every class \@interface and class 14345 /// extension \@interface, if the last ivar is a bitfield of any type, 14346 /// then add an implicit `char :0` ivar to the end of that interface. 14347 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14348 SmallVectorImpl<Decl *> &AllIvarDecls) { 14349 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14350 return; 14351 14352 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14353 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14354 14355 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14356 return; 14357 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14358 if (!ID) { 14359 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14360 if (!CD->IsClassExtension()) 14361 return; 14362 } 14363 // No need to add this to end of @implementation. 14364 else 14365 return; 14366 } 14367 // All conditions are met. Add a new bitfield to the tail end of ivars. 14368 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14369 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14370 14371 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14372 DeclLoc, DeclLoc, nullptr, 14373 Context.CharTy, 14374 Context.getTrivialTypeSourceInfo(Context.CharTy, 14375 DeclLoc), 14376 ObjCIvarDecl::Private, BW, 14377 true); 14378 AllIvarDecls.push_back(Ivar); 14379 } 14380 14381 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14382 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14383 SourceLocation RBrac, AttributeList *Attr) { 14384 assert(EnclosingDecl && "missing record or interface decl"); 14385 14386 // If this is an Objective-C @implementation or category and we have 14387 // new fields here we should reset the layout of the interface since 14388 // it will now change. 14389 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14390 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14391 switch (DC->getKind()) { 14392 default: break; 14393 case Decl::ObjCCategory: 14394 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14395 break; 14396 case Decl::ObjCImplementation: 14397 Context. 14398 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14399 break; 14400 } 14401 } 14402 14403 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14404 14405 // Start counting up the number of named members; make sure to include 14406 // members of anonymous structs and unions in the total. 14407 unsigned NumNamedMembers = 0; 14408 if (Record) { 14409 for (const auto *I : Record->decls()) { 14410 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14411 if (IFD->getDeclName()) 14412 ++NumNamedMembers; 14413 } 14414 } 14415 14416 // Verify that all the fields are okay. 14417 SmallVector<FieldDecl*, 32> RecFields; 14418 14419 bool ARCErrReported = false; 14420 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14421 i != end; ++i) { 14422 FieldDecl *FD = cast<FieldDecl>(*i); 14423 14424 // Get the type for the field. 14425 const Type *FDTy = FD->getType().getTypePtr(); 14426 14427 if (!FD->isAnonymousStructOrUnion()) { 14428 // Remember all fields written by the user. 14429 RecFields.push_back(FD); 14430 } 14431 14432 // If the field is already invalid for some reason, don't emit more 14433 // diagnostics about it. 14434 if (FD->isInvalidDecl()) { 14435 EnclosingDecl->setInvalidDecl(); 14436 continue; 14437 } 14438 14439 // C99 6.7.2.1p2: 14440 // A structure or union shall not contain a member with 14441 // incomplete or function type (hence, a structure shall not 14442 // contain an instance of itself, but may contain a pointer to 14443 // an instance of itself), except that the last member of a 14444 // structure with more than one named member may have incomplete 14445 // array type; such a structure (and any union containing, 14446 // possibly recursively, a member that is such a structure) 14447 // shall not be a member of a structure or an element of an 14448 // array. 14449 if (FDTy->isFunctionType()) { 14450 // Field declared as a function. 14451 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14452 << FD->getDeclName(); 14453 FD->setInvalidDecl(); 14454 EnclosingDecl->setInvalidDecl(); 14455 continue; 14456 } else if (FDTy->isIncompleteArrayType() && Record && 14457 ((i + 1 == Fields.end() && !Record->isUnion()) || 14458 ((getLangOpts().MicrosoftExt || 14459 getLangOpts().CPlusPlus) && 14460 (i + 1 == Fields.end() || Record->isUnion())))) { 14461 // Flexible array member. 14462 // Microsoft and g++ is more permissive regarding flexible array. 14463 // It will accept flexible array in union and also 14464 // as the sole element of a struct/class. 14465 unsigned DiagID = 0; 14466 if (Record->isUnion()) 14467 DiagID = getLangOpts().MicrosoftExt 14468 ? diag::ext_flexible_array_union_ms 14469 : getLangOpts().CPlusPlus 14470 ? diag::ext_flexible_array_union_gnu 14471 : diag::err_flexible_array_union; 14472 else if (NumNamedMembers < 1) 14473 DiagID = getLangOpts().MicrosoftExt 14474 ? diag::ext_flexible_array_empty_aggregate_ms 14475 : getLangOpts().CPlusPlus 14476 ? diag::ext_flexible_array_empty_aggregate_gnu 14477 : diag::err_flexible_array_empty_aggregate; 14478 14479 if (DiagID) 14480 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14481 << Record->getTagKind(); 14482 // While the layout of types that contain virtual bases is not specified 14483 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14484 // virtual bases after the derived members. This would make a flexible 14485 // array member declared at the end of an object not adjacent to the end 14486 // of the type. 14487 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14488 if (RD->getNumVBases() != 0) 14489 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14490 << FD->getDeclName() << Record->getTagKind(); 14491 if (!getLangOpts().C99) 14492 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14493 << FD->getDeclName() << Record->getTagKind(); 14494 14495 // If the element type has a non-trivial destructor, we would not 14496 // implicitly destroy the elements, so disallow it for now. 14497 // 14498 // FIXME: GCC allows this. We should probably either implicitly delete 14499 // the destructor of the containing class, or just allow this. 14500 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14501 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14502 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14503 << FD->getDeclName() << FD->getType(); 14504 FD->setInvalidDecl(); 14505 EnclosingDecl->setInvalidDecl(); 14506 continue; 14507 } 14508 // Okay, we have a legal flexible array member at the end of the struct. 14509 Record->setHasFlexibleArrayMember(true); 14510 } else if (!FDTy->isDependentType() && 14511 RequireCompleteType(FD->getLocation(), FD->getType(), 14512 diag::err_field_incomplete)) { 14513 // Incomplete type 14514 FD->setInvalidDecl(); 14515 EnclosingDecl->setInvalidDecl(); 14516 continue; 14517 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14518 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14519 // A type which contains a flexible array member is considered to be a 14520 // flexible array member. 14521 Record->setHasFlexibleArrayMember(true); 14522 if (!Record->isUnion()) { 14523 // If this is a struct/class and this is not the last element, reject 14524 // it. Note that GCC supports variable sized arrays in the middle of 14525 // structures. 14526 if (i + 1 != Fields.end()) 14527 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14528 << FD->getDeclName() << FD->getType(); 14529 else { 14530 // We support flexible arrays at the end of structs in 14531 // other structs as an extension. 14532 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14533 << FD->getDeclName(); 14534 } 14535 } 14536 } 14537 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14538 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14539 diag::err_abstract_type_in_decl, 14540 AbstractIvarType)) { 14541 // Ivars can not have abstract class types 14542 FD->setInvalidDecl(); 14543 } 14544 if (Record && FDTTy->getDecl()->hasObjectMember()) 14545 Record->setHasObjectMember(true); 14546 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14547 Record->setHasVolatileMember(true); 14548 } else if (FDTy->isObjCObjectType()) { 14549 /// A field cannot be an Objective-c object 14550 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14551 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14552 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14553 FD->setType(T); 14554 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14555 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14556 // It's an error in ARC if a field has lifetime. 14557 // We don't want to report this in a system header, though, 14558 // so we just make the field unavailable. 14559 // FIXME: that's really not sufficient; we need to make the type 14560 // itself invalid to, say, initialize or copy. 14561 QualType T = FD->getType(); 14562 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14563 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14564 SourceLocation loc = FD->getLocation(); 14565 if (getSourceManager().isInSystemHeader(loc)) { 14566 if (!FD->hasAttr<UnavailableAttr>()) { 14567 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14568 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14569 } 14570 } else { 14571 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14572 << T->isBlockPointerType() << Record->getTagKind(); 14573 } 14574 ARCErrReported = true; 14575 } 14576 } else if (getLangOpts().ObjC1 && 14577 getLangOpts().getGC() != LangOptions::NonGC && 14578 Record && !Record->hasObjectMember()) { 14579 if (FD->getType()->isObjCObjectPointerType() || 14580 FD->getType().isObjCGCStrong()) 14581 Record->setHasObjectMember(true); 14582 else if (Context.getAsArrayType(FD->getType())) { 14583 QualType BaseType = Context.getBaseElementType(FD->getType()); 14584 if (BaseType->isRecordType() && 14585 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14586 Record->setHasObjectMember(true); 14587 else if (BaseType->isObjCObjectPointerType() || 14588 BaseType.isObjCGCStrong()) 14589 Record->setHasObjectMember(true); 14590 } 14591 } 14592 if (Record && FD->getType().isVolatileQualified()) 14593 Record->setHasVolatileMember(true); 14594 // Keep track of the number of named members. 14595 if (FD->getIdentifier()) 14596 ++NumNamedMembers; 14597 } 14598 14599 // Okay, we successfully defined 'Record'. 14600 if (Record) { 14601 bool Completed = false; 14602 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14603 if (!CXXRecord->isInvalidDecl()) { 14604 // Set access bits correctly on the directly-declared conversions. 14605 for (CXXRecordDecl::conversion_iterator 14606 I = CXXRecord->conversion_begin(), 14607 E = CXXRecord->conversion_end(); I != E; ++I) 14608 I.setAccess((*I)->getAccess()); 14609 } 14610 14611 if (!CXXRecord->isDependentType()) { 14612 if (CXXRecord->hasUserDeclaredDestructor()) { 14613 // Adjust user-defined destructor exception spec. 14614 if (getLangOpts().CPlusPlus11) 14615 AdjustDestructorExceptionSpec(CXXRecord, 14616 CXXRecord->getDestructor()); 14617 } 14618 14619 if (!CXXRecord->isInvalidDecl()) { 14620 // Add any implicitly-declared members to this class. 14621 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14622 14623 // If we have virtual base classes, we may end up finding multiple 14624 // final overriders for a given virtual function. Check for this 14625 // problem now. 14626 if (CXXRecord->getNumVBases()) { 14627 CXXFinalOverriderMap FinalOverriders; 14628 CXXRecord->getFinalOverriders(FinalOverriders); 14629 14630 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14631 MEnd = FinalOverriders.end(); 14632 M != MEnd; ++M) { 14633 for (OverridingMethods::iterator SO = M->second.begin(), 14634 SOEnd = M->second.end(); 14635 SO != SOEnd; ++SO) { 14636 assert(SO->second.size() > 0 && 14637 "Virtual function without overridding functions?"); 14638 if (SO->second.size() == 1) 14639 continue; 14640 14641 // C++ [class.virtual]p2: 14642 // In a derived class, if a virtual member function of a base 14643 // class subobject has more than one final overrider the 14644 // program is ill-formed. 14645 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14646 << (const NamedDecl *)M->first << Record; 14647 Diag(M->first->getLocation(), 14648 diag::note_overridden_virtual_function); 14649 for (OverridingMethods::overriding_iterator 14650 OM = SO->second.begin(), 14651 OMEnd = SO->second.end(); 14652 OM != OMEnd; ++OM) 14653 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14654 << (const NamedDecl *)M->first << OM->Method->getParent(); 14655 14656 Record->setInvalidDecl(); 14657 } 14658 } 14659 CXXRecord->completeDefinition(&FinalOverriders); 14660 Completed = true; 14661 } 14662 } 14663 } 14664 } 14665 14666 if (!Completed) 14667 Record->completeDefinition(); 14668 14669 // We may have deferred checking for a deleted destructor. Check now. 14670 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14671 auto *Dtor = CXXRecord->getDestructor(); 14672 if (Dtor && Dtor->isImplicit() && 14673 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14674 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14675 } 14676 14677 if (Record->hasAttrs()) { 14678 CheckAlignasUnderalignment(Record); 14679 14680 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14681 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14682 IA->getRange(), IA->getBestCase(), 14683 IA->getSemanticSpelling()); 14684 } 14685 14686 // Check if the structure/union declaration is a type that can have zero 14687 // size in C. For C this is a language extension, for C++ it may cause 14688 // compatibility problems. 14689 bool CheckForZeroSize; 14690 if (!getLangOpts().CPlusPlus) { 14691 CheckForZeroSize = true; 14692 } else { 14693 // For C++ filter out types that cannot be referenced in C code. 14694 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14695 CheckForZeroSize = 14696 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14697 !CXXRecord->isDependentType() && 14698 CXXRecord->isCLike(); 14699 } 14700 if (CheckForZeroSize) { 14701 bool ZeroSize = true; 14702 bool IsEmpty = true; 14703 unsigned NonBitFields = 0; 14704 for (RecordDecl::field_iterator I = Record->field_begin(), 14705 E = Record->field_end(); 14706 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14707 IsEmpty = false; 14708 if (I->isUnnamedBitfield()) { 14709 if (I->getBitWidthValue(Context) > 0) 14710 ZeroSize = false; 14711 } else { 14712 ++NonBitFields; 14713 QualType FieldType = I->getType(); 14714 if (FieldType->isIncompleteType() || 14715 !Context.getTypeSizeInChars(FieldType).isZero()) 14716 ZeroSize = false; 14717 } 14718 } 14719 14720 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14721 // allowed in C++, but warn if its declaration is inside 14722 // extern "C" block. 14723 if (ZeroSize) { 14724 Diag(RecLoc, getLangOpts().CPlusPlus ? 14725 diag::warn_zero_size_struct_union_in_extern_c : 14726 diag::warn_zero_size_struct_union_compat) 14727 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14728 } 14729 14730 // Structs without named members are extension in C (C99 6.7.2.1p7), 14731 // but are accepted by GCC. 14732 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14733 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14734 diag::ext_no_named_members_in_struct_union) 14735 << Record->isUnion(); 14736 } 14737 } 14738 } else { 14739 ObjCIvarDecl **ClsFields = 14740 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14741 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14742 ID->setEndOfDefinitionLoc(RBrac); 14743 // Add ivar's to class's DeclContext. 14744 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14745 ClsFields[i]->setLexicalDeclContext(ID); 14746 ID->addDecl(ClsFields[i]); 14747 } 14748 // Must enforce the rule that ivars in the base classes may not be 14749 // duplicates. 14750 if (ID->getSuperClass()) 14751 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14752 } else if (ObjCImplementationDecl *IMPDecl = 14753 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14754 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14755 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14756 // Ivar declared in @implementation never belongs to the implementation. 14757 // Only it is in implementation's lexical context. 14758 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14759 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14760 IMPDecl->setIvarLBraceLoc(LBrac); 14761 IMPDecl->setIvarRBraceLoc(RBrac); 14762 } else if (ObjCCategoryDecl *CDecl = 14763 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14764 // case of ivars in class extension; all other cases have been 14765 // reported as errors elsewhere. 14766 // FIXME. Class extension does not have a LocEnd field. 14767 // CDecl->setLocEnd(RBrac); 14768 // Add ivar's to class extension's DeclContext. 14769 // Diagnose redeclaration of private ivars. 14770 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14771 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14772 if (IDecl) { 14773 if (const ObjCIvarDecl *ClsIvar = 14774 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14775 Diag(ClsFields[i]->getLocation(), 14776 diag::err_duplicate_ivar_declaration); 14777 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14778 continue; 14779 } 14780 for (const auto *Ext : IDecl->known_extensions()) { 14781 if (const ObjCIvarDecl *ClsExtIvar 14782 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14783 Diag(ClsFields[i]->getLocation(), 14784 diag::err_duplicate_ivar_declaration); 14785 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14786 continue; 14787 } 14788 } 14789 } 14790 ClsFields[i]->setLexicalDeclContext(CDecl); 14791 CDecl->addDecl(ClsFields[i]); 14792 } 14793 CDecl->setIvarLBraceLoc(LBrac); 14794 CDecl->setIvarRBraceLoc(RBrac); 14795 } 14796 } 14797 14798 if (Attr) 14799 ProcessDeclAttributeList(S, Record, Attr); 14800 } 14801 14802 /// \brief Determine whether the given integral value is representable within 14803 /// the given type T. 14804 static bool isRepresentableIntegerValue(ASTContext &Context, 14805 llvm::APSInt &Value, 14806 QualType T) { 14807 assert(T->isIntegralType(Context) && "Integral type required!"); 14808 unsigned BitWidth = Context.getIntWidth(T); 14809 14810 if (Value.isUnsigned() || Value.isNonNegative()) { 14811 if (T->isSignedIntegerOrEnumerationType()) 14812 --BitWidth; 14813 return Value.getActiveBits() <= BitWidth; 14814 } 14815 return Value.getMinSignedBits() <= BitWidth; 14816 } 14817 14818 // \brief Given an integral type, return the next larger integral type 14819 // (or a NULL type of no such type exists). 14820 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14821 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14822 // enum checking below. 14823 assert(T->isIntegralType(Context) && "Integral type required!"); 14824 const unsigned NumTypes = 4; 14825 QualType SignedIntegralTypes[NumTypes] = { 14826 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14827 }; 14828 QualType UnsignedIntegralTypes[NumTypes] = { 14829 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14830 Context.UnsignedLongLongTy 14831 }; 14832 14833 unsigned BitWidth = Context.getTypeSize(T); 14834 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14835 : UnsignedIntegralTypes; 14836 for (unsigned I = 0; I != NumTypes; ++I) 14837 if (Context.getTypeSize(Types[I]) > BitWidth) 14838 return Types[I]; 14839 14840 return QualType(); 14841 } 14842 14843 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14844 EnumConstantDecl *LastEnumConst, 14845 SourceLocation IdLoc, 14846 IdentifierInfo *Id, 14847 Expr *Val) { 14848 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14849 llvm::APSInt EnumVal(IntWidth); 14850 QualType EltTy; 14851 14852 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14853 Val = nullptr; 14854 14855 if (Val) 14856 Val = DefaultLvalueConversion(Val).get(); 14857 14858 if (Val) { 14859 if (Enum->isDependentType() || Val->isTypeDependent()) 14860 EltTy = Context.DependentTy; 14861 else { 14862 SourceLocation ExpLoc; 14863 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14864 !getLangOpts().MSVCCompat) { 14865 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14866 // constant-expression in the enumerator-definition shall be a converted 14867 // constant expression of the underlying type. 14868 EltTy = Enum->getIntegerType(); 14869 ExprResult Converted = 14870 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14871 CCEK_Enumerator); 14872 if (Converted.isInvalid()) 14873 Val = nullptr; 14874 else 14875 Val = Converted.get(); 14876 } else if (!Val->isValueDependent() && 14877 !(Val = VerifyIntegerConstantExpression(Val, 14878 &EnumVal).get())) { 14879 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14880 } else { 14881 if (Enum->isFixed()) { 14882 EltTy = Enum->getIntegerType(); 14883 14884 // In Obj-C and Microsoft mode, require the enumeration value to be 14885 // representable in the underlying type of the enumeration. In C++11, 14886 // we perform a non-narrowing conversion as part of converted constant 14887 // expression checking. 14888 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14889 if (getLangOpts().MSVCCompat) { 14890 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14891 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14892 } else 14893 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14894 } else 14895 Val = ImpCastExprToType(Val, EltTy, 14896 EltTy->isBooleanType() ? 14897 CK_IntegralToBoolean : CK_IntegralCast) 14898 .get(); 14899 } else if (getLangOpts().CPlusPlus) { 14900 // C++11 [dcl.enum]p5: 14901 // If the underlying type is not fixed, the type of each enumerator 14902 // is the type of its initializing value: 14903 // - If an initializer is specified for an enumerator, the 14904 // initializing value has the same type as the expression. 14905 EltTy = Val->getType(); 14906 } else { 14907 // C99 6.7.2.2p2: 14908 // The expression that defines the value of an enumeration constant 14909 // shall be an integer constant expression that has a value 14910 // representable as an int. 14911 14912 // Complain if the value is not representable in an int. 14913 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14914 Diag(IdLoc, diag::ext_enum_value_not_int) 14915 << EnumVal.toString(10) << Val->getSourceRange() 14916 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14917 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14918 // Force the type of the expression to 'int'. 14919 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14920 } 14921 EltTy = Val->getType(); 14922 } 14923 } 14924 } 14925 } 14926 14927 if (!Val) { 14928 if (Enum->isDependentType()) 14929 EltTy = Context.DependentTy; 14930 else if (!LastEnumConst) { 14931 // C++0x [dcl.enum]p5: 14932 // If the underlying type is not fixed, the type of each enumerator 14933 // is the type of its initializing value: 14934 // - If no initializer is specified for the first enumerator, the 14935 // initializing value has an unspecified integral type. 14936 // 14937 // GCC uses 'int' for its unspecified integral type, as does 14938 // C99 6.7.2.2p3. 14939 if (Enum->isFixed()) { 14940 EltTy = Enum->getIntegerType(); 14941 } 14942 else { 14943 EltTy = Context.IntTy; 14944 } 14945 } else { 14946 // Assign the last value + 1. 14947 EnumVal = LastEnumConst->getInitVal(); 14948 ++EnumVal; 14949 EltTy = LastEnumConst->getType(); 14950 14951 // Check for overflow on increment. 14952 if (EnumVal < LastEnumConst->getInitVal()) { 14953 // C++0x [dcl.enum]p5: 14954 // If the underlying type is not fixed, the type of each enumerator 14955 // is the type of its initializing value: 14956 // 14957 // - Otherwise the type of the initializing value is the same as 14958 // the type of the initializing value of the preceding enumerator 14959 // unless the incremented value is not representable in that type, 14960 // in which case the type is an unspecified integral type 14961 // sufficient to contain the incremented value. If no such type 14962 // exists, the program is ill-formed. 14963 QualType T = getNextLargerIntegralType(Context, EltTy); 14964 if (T.isNull() || Enum->isFixed()) { 14965 // There is no integral type larger enough to represent this 14966 // value. Complain, then allow the value to wrap around. 14967 EnumVal = LastEnumConst->getInitVal(); 14968 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14969 ++EnumVal; 14970 if (Enum->isFixed()) 14971 // When the underlying type is fixed, this is ill-formed. 14972 Diag(IdLoc, diag::err_enumerator_wrapped) 14973 << EnumVal.toString(10) 14974 << EltTy; 14975 else 14976 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14977 << EnumVal.toString(10); 14978 } else { 14979 EltTy = T; 14980 } 14981 14982 // Retrieve the last enumerator's value, extent that type to the 14983 // type that is supposed to be large enough to represent the incremented 14984 // value, then increment. 14985 EnumVal = LastEnumConst->getInitVal(); 14986 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14987 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14988 ++EnumVal; 14989 14990 // If we're not in C++, diagnose the overflow of enumerator values, 14991 // which in C99 means that the enumerator value is not representable in 14992 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14993 // permits enumerator values that are representable in some larger 14994 // integral type. 14995 if (!getLangOpts().CPlusPlus && !T.isNull()) 14996 Diag(IdLoc, diag::warn_enum_value_overflow); 14997 } else if (!getLangOpts().CPlusPlus && 14998 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14999 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15000 Diag(IdLoc, diag::ext_enum_value_not_int) 15001 << EnumVal.toString(10) << 1; 15002 } 15003 } 15004 } 15005 15006 if (!EltTy->isDependentType()) { 15007 // Make the enumerator value match the signedness and size of the 15008 // enumerator's type. 15009 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15010 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15011 } 15012 15013 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15014 Val, EnumVal); 15015 } 15016 15017 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15018 SourceLocation IILoc) { 15019 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15020 !getLangOpts().CPlusPlus) 15021 return SkipBodyInfo(); 15022 15023 // We have an anonymous enum definition. Look up the first enumerator to 15024 // determine if we should merge the definition with an existing one and 15025 // skip the body. 15026 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15027 ForRedeclaration); 15028 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15029 if (!PrevECD) 15030 return SkipBodyInfo(); 15031 15032 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15033 NamedDecl *Hidden; 15034 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15035 SkipBodyInfo Skip; 15036 Skip.Previous = Hidden; 15037 return Skip; 15038 } 15039 15040 return SkipBodyInfo(); 15041 } 15042 15043 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15044 SourceLocation IdLoc, IdentifierInfo *Id, 15045 AttributeList *Attr, 15046 SourceLocation EqualLoc, Expr *Val) { 15047 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15048 EnumConstantDecl *LastEnumConst = 15049 cast_or_null<EnumConstantDecl>(lastEnumConst); 15050 15051 // The scope passed in may not be a decl scope. Zip up the scope tree until 15052 // we find one that is. 15053 S = getNonFieldDeclScope(S); 15054 15055 // Verify that there isn't already something declared with this name in this 15056 // scope. 15057 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15058 ForRedeclaration); 15059 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15060 // Maybe we will complain about the shadowed template parameter. 15061 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15062 // Just pretend that we didn't see the previous declaration. 15063 PrevDecl = nullptr; 15064 } 15065 15066 // C++ [class.mem]p15: 15067 // If T is the name of a class, then each of the following shall have a name 15068 // different from T: 15069 // - every enumerator of every member of class T that is an unscoped 15070 // enumerated type 15071 if (!TheEnumDecl->isScoped()) 15072 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15073 DeclarationNameInfo(Id, IdLoc)); 15074 15075 EnumConstantDecl *New = 15076 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15077 if (!New) 15078 return nullptr; 15079 15080 if (PrevDecl) { 15081 // When in C++, we may get a TagDecl with the same name; in this case the 15082 // enum constant will 'hide' the tag. 15083 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15084 "Received TagDecl when not in C++!"); 15085 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15086 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15087 if (isa<EnumConstantDecl>(PrevDecl)) 15088 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15089 else 15090 Diag(IdLoc, diag::err_redefinition) << Id; 15091 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15092 return nullptr; 15093 } 15094 } 15095 15096 // Process attributes. 15097 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15098 15099 // Register this decl in the current scope stack. 15100 New->setAccess(TheEnumDecl->getAccess()); 15101 PushOnScopeChains(New, S); 15102 15103 ActOnDocumentableDecl(New); 15104 15105 return New; 15106 } 15107 15108 // Returns true when the enum initial expression does not trigger the 15109 // duplicate enum warning. A few common cases are exempted as follows: 15110 // Element2 = Element1 15111 // Element2 = Element1 + 1 15112 // Element2 = Element1 - 1 15113 // Where Element2 and Element1 are from the same enum. 15114 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15115 Expr *InitExpr = ECD->getInitExpr(); 15116 if (!InitExpr) 15117 return true; 15118 InitExpr = InitExpr->IgnoreImpCasts(); 15119 15120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15121 if (!BO->isAdditiveOp()) 15122 return true; 15123 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15124 if (!IL) 15125 return true; 15126 if (IL->getValue() != 1) 15127 return true; 15128 15129 InitExpr = BO->getLHS(); 15130 } 15131 15132 // This checks if the elements are from the same enum. 15133 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15134 if (!DRE) 15135 return true; 15136 15137 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15138 if (!EnumConstant) 15139 return true; 15140 15141 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15142 Enum) 15143 return true; 15144 15145 return false; 15146 } 15147 15148 namespace { 15149 struct DupKey { 15150 int64_t val; 15151 bool isTombstoneOrEmptyKey; 15152 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15153 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15154 }; 15155 15156 static DupKey GetDupKey(const llvm::APSInt& Val) { 15157 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15158 false); 15159 } 15160 15161 struct DenseMapInfoDupKey { 15162 static DupKey getEmptyKey() { return DupKey(0, true); } 15163 static DupKey getTombstoneKey() { return DupKey(1, true); } 15164 static unsigned getHashValue(const DupKey Key) { 15165 return (unsigned)(Key.val * 37); 15166 } 15167 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15168 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15169 LHS.val == RHS.val; 15170 } 15171 }; 15172 } // end anonymous namespace 15173 15174 // Emits a warning when an element is implicitly set a value that 15175 // a previous element has already been set to. 15176 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15177 EnumDecl *Enum, 15178 QualType EnumType) { 15179 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15180 return; 15181 // Avoid anonymous enums 15182 if (!Enum->getIdentifier()) 15183 return; 15184 15185 // Only check for small enums. 15186 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15187 return; 15188 15189 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15190 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15191 15192 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15193 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15194 ValueToVectorMap; 15195 15196 DuplicatesVector DupVector; 15197 ValueToVectorMap EnumMap; 15198 15199 // Populate the EnumMap with all values represented by enum constants without 15200 // an initialier. 15201 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15202 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15203 15204 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15205 // this constant. Skip this enum since it may be ill-formed. 15206 if (!ECD) { 15207 return; 15208 } 15209 15210 if (ECD->getInitExpr()) 15211 continue; 15212 15213 DupKey Key = GetDupKey(ECD->getInitVal()); 15214 DeclOrVector &Entry = EnumMap[Key]; 15215 15216 // First time encountering this value. 15217 if (Entry.isNull()) 15218 Entry = ECD; 15219 } 15220 15221 // Create vectors for any values that has duplicates. 15222 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15223 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15224 if (!ValidDuplicateEnum(ECD, Enum)) 15225 continue; 15226 15227 DupKey Key = GetDupKey(ECD->getInitVal()); 15228 15229 DeclOrVector& Entry = EnumMap[Key]; 15230 if (Entry.isNull()) 15231 continue; 15232 15233 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15234 // Ensure constants are different. 15235 if (D == ECD) 15236 continue; 15237 15238 // Create new vector and push values onto it. 15239 ECDVector *Vec = new ECDVector(); 15240 Vec->push_back(D); 15241 Vec->push_back(ECD); 15242 15243 // Update entry to point to the duplicates vector. 15244 Entry = Vec; 15245 15246 // Store the vector somewhere we can consult later for quick emission of 15247 // diagnostics. 15248 DupVector.push_back(Vec); 15249 continue; 15250 } 15251 15252 ECDVector *Vec = Entry.get<ECDVector*>(); 15253 // Make sure constants are not added more than once. 15254 if (*Vec->begin() == ECD) 15255 continue; 15256 15257 Vec->push_back(ECD); 15258 } 15259 15260 // Emit diagnostics. 15261 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15262 DupVectorEnd = DupVector.end(); 15263 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15264 ECDVector *Vec = *DupVectorIter; 15265 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15266 15267 // Emit warning for one enum constant. 15268 ECDVector::iterator I = Vec->begin(); 15269 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15270 << (*I)->getName() << (*I)->getInitVal().toString(10) 15271 << (*I)->getSourceRange(); 15272 ++I; 15273 15274 // Emit one note for each of the remaining enum constants with 15275 // the same value. 15276 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15277 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15278 << (*I)->getName() << (*I)->getInitVal().toString(10) 15279 << (*I)->getSourceRange(); 15280 delete Vec; 15281 } 15282 } 15283 15284 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15285 bool AllowMask) const { 15286 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 15287 assert(ED->isCompleteDefinition() && "expected enum definition"); 15288 15289 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15290 llvm::APInt &FlagBits = R.first->second; 15291 15292 if (R.second) { 15293 for (auto *E : ED->enumerators()) { 15294 const auto &EVal = E->getInitVal(); 15295 // Only single-bit enumerators introduce new flag values. 15296 if (EVal.isPowerOf2()) 15297 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15298 } 15299 } 15300 15301 // A value is in a flag enum if either its bits are a subset of the enum's 15302 // flag bits (the first condition) or we are allowing masks and the same is 15303 // true of its complement (the second condition). When masks are allowed, we 15304 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15305 // 15306 // While it's true that any value could be used as a mask, the assumption is 15307 // that a mask will have all of the insignificant bits set. Anything else is 15308 // likely a logic error. 15309 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15310 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15311 } 15312 15313 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15314 Decl *EnumDeclX, 15315 ArrayRef<Decl *> Elements, 15316 Scope *S, AttributeList *Attr) { 15317 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15318 QualType EnumType = Context.getTypeDeclType(Enum); 15319 15320 if (Attr) 15321 ProcessDeclAttributeList(S, Enum, Attr); 15322 15323 if (Enum->isDependentType()) { 15324 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15325 EnumConstantDecl *ECD = 15326 cast_or_null<EnumConstantDecl>(Elements[i]); 15327 if (!ECD) continue; 15328 15329 ECD->setType(EnumType); 15330 } 15331 15332 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15333 return; 15334 } 15335 15336 // TODO: If the result value doesn't fit in an int, it must be a long or long 15337 // long value. ISO C does not support this, but GCC does as an extension, 15338 // emit a warning. 15339 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15340 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15341 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15342 15343 // Verify that all the values are okay, compute the size of the values, and 15344 // reverse the list. 15345 unsigned NumNegativeBits = 0; 15346 unsigned NumPositiveBits = 0; 15347 15348 // Keep track of whether all elements have type int. 15349 bool AllElementsInt = true; 15350 15351 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15352 EnumConstantDecl *ECD = 15353 cast_or_null<EnumConstantDecl>(Elements[i]); 15354 if (!ECD) continue; // Already issued a diagnostic. 15355 15356 const llvm::APSInt &InitVal = ECD->getInitVal(); 15357 15358 // Keep track of the size of positive and negative values. 15359 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15360 NumPositiveBits = std::max(NumPositiveBits, 15361 (unsigned)InitVal.getActiveBits()); 15362 else 15363 NumNegativeBits = std::max(NumNegativeBits, 15364 (unsigned)InitVal.getMinSignedBits()); 15365 15366 // Keep track of whether every enum element has type int (very commmon). 15367 if (AllElementsInt) 15368 AllElementsInt = ECD->getType() == Context.IntTy; 15369 } 15370 15371 // Figure out the type that should be used for this enum. 15372 QualType BestType; 15373 unsigned BestWidth; 15374 15375 // C++0x N3000 [conv.prom]p3: 15376 // An rvalue of an unscoped enumeration type whose underlying 15377 // type is not fixed can be converted to an rvalue of the first 15378 // of the following types that can represent all the values of 15379 // the enumeration: int, unsigned int, long int, unsigned long 15380 // int, long long int, or unsigned long long int. 15381 // C99 6.4.4.3p2: 15382 // An identifier declared as an enumeration constant has type int. 15383 // The C99 rule is modified by a gcc extension 15384 QualType BestPromotionType; 15385 15386 bool Packed = Enum->hasAttr<PackedAttr>(); 15387 // -fshort-enums is the equivalent to specifying the packed attribute on all 15388 // enum definitions. 15389 if (LangOpts.ShortEnums) 15390 Packed = true; 15391 15392 if (Enum->isFixed()) { 15393 BestType = Enum->getIntegerType(); 15394 if (BestType->isPromotableIntegerType()) 15395 BestPromotionType = Context.getPromotedIntegerType(BestType); 15396 else 15397 BestPromotionType = BestType; 15398 15399 BestWidth = Context.getIntWidth(BestType); 15400 } 15401 else if (NumNegativeBits) { 15402 // If there is a negative value, figure out the smallest integer type (of 15403 // int/long/longlong) that fits. 15404 // If it's packed, check also if it fits a char or a short. 15405 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15406 BestType = Context.SignedCharTy; 15407 BestWidth = CharWidth; 15408 } else if (Packed && NumNegativeBits <= ShortWidth && 15409 NumPositiveBits < ShortWidth) { 15410 BestType = Context.ShortTy; 15411 BestWidth = ShortWidth; 15412 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15413 BestType = Context.IntTy; 15414 BestWidth = IntWidth; 15415 } else { 15416 BestWidth = Context.getTargetInfo().getLongWidth(); 15417 15418 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15419 BestType = Context.LongTy; 15420 } else { 15421 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15422 15423 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15424 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15425 BestType = Context.LongLongTy; 15426 } 15427 } 15428 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15429 } else { 15430 // If there is no negative value, figure out the smallest type that fits 15431 // all of the enumerator values. 15432 // If it's packed, check also if it fits a char or a short. 15433 if (Packed && NumPositiveBits <= CharWidth) { 15434 BestType = Context.UnsignedCharTy; 15435 BestPromotionType = Context.IntTy; 15436 BestWidth = CharWidth; 15437 } else if (Packed && NumPositiveBits <= ShortWidth) { 15438 BestType = Context.UnsignedShortTy; 15439 BestPromotionType = Context.IntTy; 15440 BestWidth = ShortWidth; 15441 } else if (NumPositiveBits <= IntWidth) { 15442 BestType = Context.UnsignedIntTy; 15443 BestWidth = IntWidth; 15444 BestPromotionType 15445 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15446 ? Context.UnsignedIntTy : Context.IntTy; 15447 } else if (NumPositiveBits <= 15448 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15449 BestType = Context.UnsignedLongTy; 15450 BestPromotionType 15451 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15452 ? Context.UnsignedLongTy : Context.LongTy; 15453 } else { 15454 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15455 assert(NumPositiveBits <= BestWidth && 15456 "How could an initializer get larger than ULL?"); 15457 BestType = Context.UnsignedLongLongTy; 15458 BestPromotionType 15459 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15460 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15461 } 15462 } 15463 15464 // Loop over all of the enumerator constants, changing their types to match 15465 // the type of the enum if needed. 15466 for (auto *D : Elements) { 15467 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15468 if (!ECD) continue; // Already issued a diagnostic. 15469 15470 // Standard C says the enumerators have int type, but we allow, as an 15471 // extension, the enumerators to be larger than int size. If each 15472 // enumerator value fits in an int, type it as an int, otherwise type it the 15473 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15474 // that X has type 'int', not 'unsigned'. 15475 15476 // Determine whether the value fits into an int. 15477 llvm::APSInt InitVal = ECD->getInitVal(); 15478 15479 // If it fits into an integer type, force it. Otherwise force it to match 15480 // the enum decl type. 15481 QualType NewTy; 15482 unsigned NewWidth; 15483 bool NewSign; 15484 if (!getLangOpts().CPlusPlus && 15485 !Enum->isFixed() && 15486 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15487 NewTy = Context.IntTy; 15488 NewWidth = IntWidth; 15489 NewSign = true; 15490 } else if (ECD->getType() == BestType) { 15491 // Already the right type! 15492 if (getLangOpts().CPlusPlus) 15493 // C++ [dcl.enum]p4: Following the closing brace of an 15494 // enum-specifier, each enumerator has the type of its 15495 // enumeration. 15496 ECD->setType(EnumType); 15497 continue; 15498 } else { 15499 NewTy = BestType; 15500 NewWidth = BestWidth; 15501 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15502 } 15503 15504 // Adjust the APSInt value. 15505 InitVal = InitVal.extOrTrunc(NewWidth); 15506 InitVal.setIsSigned(NewSign); 15507 ECD->setInitVal(InitVal); 15508 15509 // Adjust the Expr initializer and type. 15510 if (ECD->getInitExpr() && 15511 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15512 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15513 CK_IntegralCast, 15514 ECD->getInitExpr(), 15515 /*base paths*/ nullptr, 15516 VK_RValue)); 15517 if (getLangOpts().CPlusPlus) 15518 // C++ [dcl.enum]p4: Following the closing brace of an 15519 // enum-specifier, each enumerator has the type of its 15520 // enumeration. 15521 ECD->setType(EnumType); 15522 else 15523 ECD->setType(NewTy); 15524 } 15525 15526 Enum->completeDefinition(BestType, BestPromotionType, 15527 NumPositiveBits, NumNegativeBits); 15528 15529 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15530 15531 if (Enum->hasAttr<FlagEnumAttr>()) { 15532 for (Decl *D : Elements) { 15533 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15534 if (!ECD) continue; // Already issued a diagnostic. 15535 15536 llvm::APSInt InitVal = ECD->getInitVal(); 15537 if (InitVal != 0 && !InitVal.isPowerOf2() && 15538 !IsValueInFlagEnum(Enum, InitVal, true)) 15539 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15540 << ECD << Enum; 15541 } 15542 } 15543 15544 // Now that the enum type is defined, ensure it's not been underaligned. 15545 if (Enum->hasAttrs()) 15546 CheckAlignasUnderalignment(Enum); 15547 } 15548 15549 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15550 SourceLocation StartLoc, 15551 SourceLocation EndLoc) { 15552 StringLiteral *AsmString = cast<StringLiteral>(expr); 15553 15554 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15555 AsmString, StartLoc, 15556 EndLoc); 15557 CurContext->addDecl(New); 15558 return New; 15559 } 15560 15561 static void checkModuleImportContext(Sema &S, Module *M, 15562 SourceLocation ImportLoc, DeclContext *DC, 15563 bool FromInclude = false) { 15564 SourceLocation ExternCLoc; 15565 15566 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15567 switch (LSD->getLanguage()) { 15568 case LinkageSpecDecl::lang_c: 15569 if (ExternCLoc.isInvalid()) 15570 ExternCLoc = LSD->getLocStart(); 15571 break; 15572 case LinkageSpecDecl::lang_cxx: 15573 break; 15574 } 15575 DC = LSD->getParent(); 15576 } 15577 15578 while (isa<LinkageSpecDecl>(DC)) 15579 DC = DC->getParent(); 15580 15581 if (!isa<TranslationUnitDecl>(DC)) { 15582 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15583 ? diag::ext_module_import_not_at_top_level_noop 15584 : diag::err_module_import_not_at_top_level_fatal) 15585 << M->getFullModuleName() << DC; 15586 S.Diag(cast<Decl>(DC)->getLocStart(), 15587 diag::note_module_import_not_at_top_level) << DC; 15588 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15589 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15590 << M->getFullModuleName(); 15591 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15592 } 15593 } 15594 15595 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15596 ModuleDeclKind MDK, 15597 ModuleIdPath Path) { 15598 // 'module implementation' requires that we are not compiling a module of any 15599 // kind. 'module' and 'module partition' require that we are compiling a 15600 // module inteface (not a module map). 15601 auto CMK = getLangOpts().getCompilingModule(); 15602 if (MDK == ModuleDeclKind::Implementation 15603 ? CMK != LangOptions::CMK_None 15604 : CMK != LangOptions::CMK_ModuleInterface) { 15605 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15606 << (unsigned)MDK; 15607 return nullptr; 15608 } 15609 15610 // FIXME: Create a ModuleDecl and return it. 15611 15612 // FIXME: Most of this work should be done by the preprocessor rather than 15613 // here, in case we look ahead across something where the current 15614 // module matters (eg a #include). 15615 15616 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15617 // hierarchical module map modules, the dots here are just another character 15618 // that can appear in a module name. Flatten down to the actual module name. 15619 std::string ModuleName; 15620 for (auto &Piece : Path) { 15621 if (!ModuleName.empty()) 15622 ModuleName += "."; 15623 ModuleName += Piece.first->getName(); 15624 } 15625 15626 // If a module name was explicitly specified on the command line, it must be 15627 // correct. 15628 if (!getLangOpts().CurrentModule.empty() && 15629 getLangOpts().CurrentModule != ModuleName) { 15630 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15631 << SourceRange(Path.front().second, Path.back().second) 15632 << getLangOpts().CurrentModule; 15633 return nullptr; 15634 } 15635 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15636 15637 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15638 15639 switch (MDK) { 15640 case ModuleDeclKind::Module: { 15641 // FIXME: Check we're not in a submodule. 15642 15643 // We can't have imported a definition of this module or parsed a module 15644 // map defining it already. 15645 if (auto *M = Map.findModule(ModuleName)) { 15646 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15647 if (M->DefinitionLoc.isValid()) 15648 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15649 else if (const auto *FE = M->getASTFile()) 15650 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15651 << FE->getName(); 15652 return nullptr; 15653 } 15654 15655 // Create a Module for the module that we're defining. 15656 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15657 assert(Mod && "module creation should not fail"); 15658 15659 // Enter the semantic scope of the module. 15660 ActOnModuleBegin(ModuleLoc, Mod); 15661 return nullptr; 15662 } 15663 15664 case ModuleDeclKind::Partition: 15665 // FIXME: Check we are in a submodule of the named module. 15666 return nullptr; 15667 15668 case ModuleDeclKind::Implementation: 15669 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15670 PP.getIdentifierInfo(ModuleName), Path[0].second); 15671 15672 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15673 if (Import.isInvalid()) 15674 return nullptr; 15675 return ConvertDeclToDeclGroup(Import.get()); 15676 } 15677 15678 llvm_unreachable("unexpected module decl kind"); 15679 } 15680 15681 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15682 SourceLocation ImportLoc, 15683 ModuleIdPath Path) { 15684 Module *Mod = 15685 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15686 /*IsIncludeDirective=*/false); 15687 if (!Mod) 15688 return true; 15689 15690 VisibleModules.setVisible(Mod, ImportLoc); 15691 15692 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15693 15694 // FIXME: we should support importing a submodule within a different submodule 15695 // of the same top-level module. Until we do, make it an error rather than 15696 // silently ignoring the import. 15697 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15698 // warn on a redundant import of the current module? 15699 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15700 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15701 Diag(ImportLoc, getLangOpts().isCompilingModule() 15702 ? diag::err_module_self_import 15703 : diag::err_module_import_in_implementation) 15704 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15705 15706 SmallVector<SourceLocation, 2> IdentifierLocs; 15707 Module *ModCheck = Mod; 15708 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15709 // If we've run out of module parents, just drop the remaining identifiers. 15710 // We need the length to be consistent. 15711 if (!ModCheck) 15712 break; 15713 ModCheck = ModCheck->Parent; 15714 15715 IdentifierLocs.push_back(Path[I].second); 15716 } 15717 15718 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15719 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15720 Mod, IdentifierLocs); 15721 if (!ModuleScopes.empty()) 15722 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15723 TU->addDecl(Import); 15724 return Import; 15725 } 15726 15727 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15728 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15729 BuildModuleInclude(DirectiveLoc, Mod); 15730 } 15731 15732 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15733 // Determine whether we're in the #include buffer for a module. The #includes 15734 // in that buffer do not qualify as module imports; they're just an 15735 // implementation detail of us building the module. 15736 // 15737 // FIXME: Should we even get ActOnModuleInclude calls for those? 15738 bool IsInModuleIncludes = 15739 TUKind == TU_Module && 15740 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15741 15742 bool ShouldAddImport = !IsInModuleIncludes; 15743 15744 // If this module import was due to an inclusion directive, create an 15745 // implicit import declaration to capture it in the AST. 15746 if (ShouldAddImport) { 15747 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15748 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15749 DirectiveLoc, Mod, 15750 DirectiveLoc); 15751 if (!ModuleScopes.empty()) 15752 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15753 TU->addDecl(ImportD); 15754 Consumer.HandleImplicitImportDecl(ImportD); 15755 } 15756 15757 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15758 VisibleModules.setVisible(Mod, DirectiveLoc); 15759 } 15760 15761 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15762 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15763 15764 ModuleScopes.push_back({}); 15765 ModuleScopes.back().Module = Mod; 15766 if (getLangOpts().ModulesLocalVisibility) 15767 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15768 15769 VisibleModules.setVisible(Mod, DirectiveLoc); 15770 } 15771 15772 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15773 if (getLangOpts().ModulesLocalVisibility) { 15774 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15775 // Leaving a module hides namespace names, so our visible namespace cache 15776 // is now out of date. 15777 VisibleNamespaceCache.clear(); 15778 } 15779 15780 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15781 "left the wrong module scope"); 15782 ModuleScopes.pop_back(); 15783 15784 // We got to the end of processing a #include of a local module. Create an 15785 // ImportDecl as we would for an imported module. 15786 FileID File = getSourceManager().getFileID(EofLoc); 15787 assert(File != getSourceManager().getMainFileID() && 15788 "end of submodule in main source file"); 15789 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15790 BuildModuleInclude(DirectiveLoc, Mod); 15791 } 15792 15793 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15794 Module *Mod) { 15795 // Bail if we're not allowed to implicitly import a module here. 15796 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15797 return; 15798 15799 // Create the implicit import declaration. 15800 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15801 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15802 Loc, Mod, Loc); 15803 TU->addDecl(ImportD); 15804 Consumer.HandleImplicitImportDecl(ImportD); 15805 15806 // Make the module visible. 15807 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15808 VisibleModules.setVisible(Mod, Loc); 15809 } 15810 15811 /// We have parsed the start of an export declaration, including the '{' 15812 /// (if present). 15813 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15814 SourceLocation LBraceLoc) { 15815 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15816 15817 // C++ Modules TS draft: 15818 // An export-declaration [...] shall not contain more than one 15819 // export keyword. 15820 // 15821 // The intent here is that an export-declaration cannot appear within another 15822 // export-declaration. 15823 if (D->isExported()) 15824 Diag(ExportLoc, diag::err_export_within_export); 15825 15826 CurContext->addDecl(D); 15827 PushDeclContext(S, D); 15828 return D; 15829 } 15830 15831 /// Complete the definition of an export declaration. 15832 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15833 auto *ED = cast<ExportDecl>(D); 15834 if (RBraceLoc.isValid()) 15835 ED->setRBraceLoc(RBraceLoc); 15836 15837 // FIXME: Diagnose export of internal-linkage declaration (including 15838 // anonymous namespace). 15839 15840 PopDeclContext(); 15841 return D; 15842 } 15843 15844 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15845 IdentifierInfo* AliasName, 15846 SourceLocation PragmaLoc, 15847 SourceLocation NameLoc, 15848 SourceLocation AliasNameLoc) { 15849 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15850 LookupOrdinaryName); 15851 AsmLabelAttr *Attr = 15852 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15853 15854 // If a declaration that: 15855 // 1) declares a function or a variable 15856 // 2) has external linkage 15857 // already exists, add a label attribute to it. 15858 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15859 if (isDeclExternC(PrevDecl)) 15860 PrevDecl->addAttr(Attr); 15861 else 15862 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15863 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15864 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15865 } else 15866 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15867 } 15868 15869 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15870 SourceLocation PragmaLoc, 15871 SourceLocation NameLoc) { 15872 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15873 15874 if (PrevDecl) { 15875 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15876 } else { 15877 (void)WeakUndeclaredIdentifiers.insert( 15878 std::pair<IdentifierInfo*,WeakInfo> 15879 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15880 } 15881 } 15882 15883 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15884 IdentifierInfo* AliasName, 15885 SourceLocation PragmaLoc, 15886 SourceLocation NameLoc, 15887 SourceLocation AliasNameLoc) { 15888 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15889 LookupOrdinaryName); 15890 WeakInfo W = WeakInfo(Name, NameLoc); 15891 15892 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15893 if (!PrevDecl->hasAttr<AliasAttr>()) 15894 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15895 DeclApplyPragmaWeak(TUScope, ND, W); 15896 } else { 15897 (void)WeakUndeclaredIdentifiers.insert( 15898 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15899 } 15900 } 15901 15902 Decl *Sema::getObjCDeclContext() const { 15903 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15904 } 15905