1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Parse/ParseDiagnostic.h" 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 68 bool AllowTemplates=false) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 /// \brief If the identifier refers to a type name within this scope, 132 /// return the declaration of that type. 133 /// 134 /// This routine performs ordinary name lookup of the identifier II 135 /// within the given scope, with optional C++ scope specifier SS, to 136 /// determine whether the name refers to a type. If so, returns an 137 /// opaque pointer (actually a QualType) corresponding to that 138 /// type. Otherwise, returns NULL. 139 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 140 Scope *S, CXXScopeSpec *SS, 141 bool isClassName, bool HasTrailingDot, 142 ParsedType ObjectTypePtr, 143 bool IsCtorOrDtorName, 144 bool WantNontrivialTypeSourceInfo, 145 IdentifierInfo **CorrectedII) { 146 // Determine where we will perform name lookup. 147 DeclContext *LookupCtx = nullptr; 148 if (ObjectTypePtr) { 149 QualType ObjectType = ObjectTypePtr.get(); 150 if (ObjectType->isRecordType()) 151 LookupCtx = computeDeclContext(ObjectType); 152 } else if (SS && SS->isNotEmpty()) { 153 LookupCtx = computeDeclContext(*SS, false); 154 155 if (!LookupCtx) { 156 if (isDependentScopeSpecifier(*SS)) { 157 // C++ [temp.res]p3: 158 // A qualified-id that refers to a type and in which the 159 // nested-name-specifier depends on a template-parameter (14.6.2) 160 // shall be prefixed by the keyword typename to indicate that the 161 // qualified-id denotes a type, forming an 162 // elaborated-type-specifier (7.1.5.3). 163 // 164 // We therefore do not perform any name lookup if the result would 165 // refer to a member of an unknown specialization. 166 if (!isClassName && !IsCtorOrDtorName) 167 return ParsedType(); 168 169 // We know from the grammar that this name refers to a type, 170 // so build a dependent node to describe the type. 171 if (WantNontrivialTypeSourceInfo) 172 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 173 174 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 175 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 176 II, NameLoc); 177 return ParsedType::make(T); 178 } 179 180 return ParsedType(); 181 } 182 183 if (!LookupCtx->isDependentContext() && 184 RequireCompleteDeclContext(*SS, LookupCtx)) 185 return ParsedType(); 186 } 187 188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 189 // lookup for class-names. 190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 191 LookupOrdinaryName; 192 LookupResult Result(*this, &II, NameLoc, Kind); 193 if (LookupCtx) { 194 // Perform "qualified" name lookup into the declaration context we 195 // computed, which is either the type of the base of a member access 196 // expression or the declaration context associated with a prior 197 // nested-name-specifier. 198 LookupQualifiedName(Result, LookupCtx); 199 200 if (ObjectTypePtr && Result.empty()) { 201 // C++ [basic.lookup.classref]p3: 202 // If the unqualified-id is ~type-name, the type-name is looked up 203 // in the context of the entire postfix-expression. If the type T of 204 // the object expression is of a class type C, the type-name is also 205 // looked up in the scope of class C. At least one of the lookups shall 206 // find a name that refers to (possibly cv-qualified) T. 207 LookupName(Result, S); 208 } 209 } else { 210 // Perform unqualified name lookup. 211 LookupName(Result, S); 212 } 213 214 NamedDecl *IIDecl = nullptr; 215 switch (Result.getResultKind()) { 216 case LookupResult::NotFound: 217 case LookupResult::NotFoundInCurrentInstantiation: 218 if (CorrectedII) { 219 TypeNameValidatorCCC Validator(true, isClassName); 220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 221 Kind, S, SS, Validator, 222 CTK_ErrorRecovery); 223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 224 TemplateTy Template; 225 bool MemberOfUnknownSpecialization; 226 UnqualifiedId TemplateName; 227 TemplateName.setIdentifier(NewII, NameLoc); 228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 229 CXXScopeSpec NewSS, *NewSSPtr = SS; 230 if (SS && NNS) { 231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 NewSSPtr = &NewSS; 233 } 234 if (Correction && (NNS || NewII != &II) && 235 // Ignore a correction to a template type as the to-be-corrected 236 // identifier is not a template (typo correction for template names 237 // is handled elsewhere). 238 !(getLangOpts().CPlusPlus && NewSSPtr && 239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 240 false, Template, MemberOfUnknownSpecialization))) { 241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 242 isClassName, HasTrailingDot, ObjectTypePtr, 243 IsCtorOrDtorName, 244 WantNontrivialTypeSourceInfo); 245 if (Ty) { 246 diagnoseTypo(Correction, 247 PDiag(diag::err_unknown_type_or_class_name_suggest) 248 << Result.getLookupName() << isClassName); 249 if (SS && NNS) 250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 251 *CorrectedII = NewII; 252 return Ty; 253 } 254 } 255 } 256 // If typo correction failed or was not performed, fall through 257 case LookupResult::FoundOverloaded: 258 case LookupResult::FoundUnresolvedValue: 259 Result.suppressDiagnostics(); 260 return ParsedType(); 261 262 case LookupResult::Ambiguous: 263 // Recover from type-hiding ambiguities by hiding the type. We'll 264 // do the lookup again when looking for an object, and we can 265 // diagnose the error then. If we don't do this, then the error 266 // about hiding the type will be immediately followed by an error 267 // that only makes sense if the identifier was treated like a type. 268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 269 Result.suppressDiagnostics(); 270 return ParsedType(); 271 } 272 273 // Look to see if we have a type anywhere in the list of results. 274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 275 Res != ResEnd; ++Res) { 276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 277 if (!IIDecl || 278 (*Res)->getLocation().getRawEncoding() < 279 IIDecl->getLocation().getRawEncoding()) 280 IIDecl = *Res; 281 } 282 } 283 284 if (!IIDecl) { 285 // None of the entities we found is a type, so there is no way 286 // to even assume that the result is a type. In this case, don't 287 // complain about the ambiguity. The parser will either try to 288 // perform this lookup again (e.g., as an object name), which 289 // will produce the ambiguity, or will complain that it expected 290 // a type name. 291 Result.suppressDiagnostics(); 292 return ParsedType(); 293 } 294 295 // We found a type within the ambiguous lookup; diagnose the 296 // ambiguity and then return that type. This might be the right 297 // answer, or it might not be, but it suppresses any attempt to 298 // perform the name lookup again. 299 break; 300 301 case LookupResult::Found: 302 IIDecl = Result.getFoundDecl(); 303 break; 304 } 305 306 assert(IIDecl && "Didn't find decl"); 307 308 QualType T; 309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 310 DiagnoseUseOfDecl(IIDecl, NameLoc); 311 312 T = Context.getTypeDeclType(TD); 313 314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 315 // constructor or destructor name (in such a case, the scope specifier 316 // will be attached to the enclosing Expr or Decl node). 317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 318 if (WantNontrivialTypeSourceInfo) { 319 // Construct a type with type-source information. 320 TypeLocBuilder Builder; 321 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 322 323 T = getElaboratedType(ETK_None, *SS, T); 324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 325 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 328 } else { 329 T = getElaboratedType(ETK_None, *SS, T); 330 } 331 } 332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 333 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 334 if (!HasTrailingDot) 335 T = Context.getObjCInterfaceType(IDecl); 336 } 337 338 if (T.isNull()) { 339 // If it's not plausibly a type, suppress diagnostics. 340 Result.suppressDiagnostics(); 341 return ParsedType(); 342 } 343 return ParsedType::make(T); 344 } 345 346 // Builds a fake NNS for the given decl context. 347 static NestedNameSpecifier * 348 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 349 for (;; DC = DC->getLookupParent()) { 350 DC = DC->getPrimaryContext(); 351 auto *ND = dyn_cast<NamespaceDecl>(DC); 352 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 353 return NestedNameSpecifier::Create(Context, nullptr, ND); 354 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 355 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 356 RD->getTypeForDecl()); 357 else if (isa<TranslationUnitDecl>(DC)) 358 return NestedNameSpecifier::GlobalSpecifier(Context); 359 } 360 llvm_unreachable("something isn't in TU scope?"); 361 } 362 363 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 364 SourceLocation NameLoc) { 365 // Accepting an undeclared identifier as a default argument for a template 366 // type parameter is a Microsoft extension. 367 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 368 369 // Build a fake DependentNameType that will perform lookup into CurContext at 370 // instantiation time. The name specifier isn't dependent, so template 371 // instantiation won't transform it. It will retry the lookup, however. 372 NestedNameSpecifier *NNS = 373 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 374 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 375 376 // Build type location information. We synthesized the qualifier, so we have 377 // to build a fake NestedNameSpecifierLoc. 378 NestedNameSpecifierLocBuilder NNSLocBuilder; 379 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 380 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 381 382 TypeLocBuilder Builder; 383 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 384 DepTL.setNameLoc(NameLoc); 385 DepTL.setElaboratedKeywordLoc(SourceLocation()); 386 DepTL.setQualifierLoc(QualifierLoc); 387 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 388 } 389 390 /// isTagName() - This method is called *for error recovery purposes only* 391 /// to determine if the specified name is a valid tag name ("struct foo"). If 392 /// so, this returns the TST for the tag corresponding to it (TST_enum, 393 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 394 /// cases in C where the user forgot to specify the tag. 395 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 396 // Do a tag name lookup in this scope. 397 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 398 LookupName(R, S, false); 399 R.suppressDiagnostics(); 400 if (R.getResultKind() == LookupResult::Found) 401 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 402 switch (TD->getTagKind()) { 403 case TTK_Struct: return DeclSpec::TST_struct; 404 case TTK_Interface: return DeclSpec::TST_interface; 405 case TTK_Union: return DeclSpec::TST_union; 406 case TTK_Class: return DeclSpec::TST_class; 407 case TTK_Enum: return DeclSpec::TST_enum; 408 } 409 } 410 411 return DeclSpec::TST_unspecified; 412 } 413 414 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 415 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 416 /// then downgrade the missing typename error to a warning. 417 /// This is needed for MSVC compatibility; Example: 418 /// @code 419 /// template<class T> class A { 420 /// public: 421 /// typedef int TYPE; 422 /// }; 423 /// template<class T> class B : public A<T> { 424 /// public: 425 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 426 /// }; 427 /// @endcode 428 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 429 if (CurContext->isRecord()) { 430 const Type *Ty = SS->getScopeRep()->getAsType(); 431 432 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 433 for (const auto &Base : RD->bases()) 434 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 435 return true; 436 return S->isFunctionPrototypeScope(); 437 } 438 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 439 } 440 441 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 442 SourceLocation IILoc, 443 Scope *S, 444 CXXScopeSpec *SS, 445 ParsedType &SuggestedType, 446 bool AllowClassTemplates) { 447 // We don't have anything to suggest (yet). 448 SuggestedType = ParsedType(); 449 450 // There may have been a typo in the name of the type. Look up typo 451 // results, in case we have something that we can suggest. 452 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 453 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 454 LookupOrdinaryName, S, SS, 455 Validator, CTK_ErrorRecovery)) { 456 if (Corrected.isKeyword()) { 457 // We corrected to a keyword. 458 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 459 II = Corrected.getCorrectionAsIdentifierInfo(); 460 } else { 461 // We found a similarly-named type or interface; suggest that. 462 if (!SS || !SS->isSet()) { 463 diagnoseTypo(Corrected, 464 PDiag(diag::err_unknown_typename_suggest) << II); 465 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 466 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 467 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 468 II->getName().equals(CorrectedStr); 469 diagnoseTypo(Corrected, 470 PDiag(diag::err_unknown_nested_typename_suggest) 471 << II << DC << DroppedSpecifier << SS->getRange()); 472 } else { 473 llvm_unreachable("could not have corrected a typo here"); 474 } 475 476 CXXScopeSpec tmpSS; 477 if (Corrected.getCorrectionSpecifier()) 478 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 479 SourceRange(IILoc)); 480 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 481 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 482 false, ParsedType(), 483 /*IsCtorOrDtorName=*/false, 484 /*NonTrivialTypeSourceInfo=*/true); 485 } 486 return; 487 } 488 489 if (getLangOpts().CPlusPlus) { 490 // See if II is a class template that the user forgot to pass arguments to. 491 UnqualifiedId Name; 492 Name.setIdentifier(II, IILoc); 493 CXXScopeSpec EmptySS; 494 TemplateTy TemplateResult; 495 bool MemberOfUnknownSpecialization; 496 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 497 Name, ParsedType(), true, TemplateResult, 498 MemberOfUnknownSpecialization) == TNK_Type_template) { 499 TemplateName TplName = TemplateResult.get(); 500 Diag(IILoc, diag::err_template_missing_args) << TplName; 501 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 502 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 503 << TplDecl->getTemplateParameters()->getSourceRange(); 504 } 505 return; 506 } 507 } 508 509 // FIXME: Should we move the logic that tries to recover from a missing tag 510 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 511 512 if (!SS || (!SS->isSet() && !SS->isInvalid())) 513 Diag(IILoc, diag::err_unknown_typename) << II; 514 else if (DeclContext *DC = computeDeclContext(*SS, false)) 515 Diag(IILoc, diag::err_typename_nested_not_found) 516 << II << DC << SS->getRange(); 517 else if (isDependentScopeSpecifier(*SS)) { 518 unsigned DiagID = diag::err_typename_missing; 519 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 520 DiagID = diag::ext_typename_missing; 521 522 Diag(SS->getRange().getBegin(), DiagID) 523 << SS->getScopeRep() << II->getName() 524 << SourceRange(SS->getRange().getBegin(), IILoc) 525 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 526 SuggestedType = ActOnTypenameType(S, SourceLocation(), 527 *SS, *II, IILoc).get(); 528 } else { 529 assert(SS && SS->isInvalid() && 530 "Invalid scope specifier has already been diagnosed"); 531 } 532 } 533 534 /// \brief Determine whether the given result set contains either a type name 535 /// or 536 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 537 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 538 NextToken.is(tok::less); 539 540 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 541 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 542 return true; 543 544 if (CheckTemplate && isa<TemplateDecl>(*I)) 545 return true; 546 } 547 548 return false; 549 } 550 551 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 552 Scope *S, CXXScopeSpec &SS, 553 IdentifierInfo *&Name, 554 SourceLocation NameLoc) { 555 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 556 SemaRef.LookupParsedName(R, S, &SS); 557 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 558 StringRef FixItTagName; 559 switch (Tag->getTagKind()) { 560 case TTK_Class: 561 FixItTagName = "class "; 562 break; 563 564 case TTK_Enum: 565 FixItTagName = "enum "; 566 break; 567 568 case TTK_Struct: 569 FixItTagName = "struct "; 570 break; 571 572 case TTK_Interface: 573 FixItTagName = "__interface "; 574 break; 575 576 case TTK_Union: 577 FixItTagName = "union "; 578 break; 579 } 580 581 StringRef TagName = FixItTagName.drop_back(); 582 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 583 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 584 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 585 586 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 587 I != IEnd; ++I) 588 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 589 << Name << TagName; 590 591 // Replace lookup results with just the tag decl. 592 Result.clear(Sema::LookupTagName); 593 SemaRef.LookupParsedName(Result, S, &SS); 594 return true; 595 } 596 597 return false; 598 } 599 600 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 601 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 602 QualType T, SourceLocation NameLoc) { 603 ASTContext &Context = S.Context; 604 605 TypeLocBuilder Builder; 606 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 607 608 T = S.getElaboratedType(ETK_None, SS, T); 609 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 610 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 611 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 612 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 613 } 614 615 Sema::NameClassification Sema::ClassifyName(Scope *S, 616 CXXScopeSpec &SS, 617 IdentifierInfo *&Name, 618 SourceLocation NameLoc, 619 const Token &NextToken, 620 bool IsAddressOfOperand, 621 CorrectionCandidateCallback *CCC) { 622 DeclarationNameInfo NameInfo(Name, NameLoc); 623 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 624 625 if (NextToken.is(tok::coloncolon)) { 626 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 627 QualType(), false, SS, nullptr, false); 628 } 629 630 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 631 LookupParsedName(Result, S, &SS, !CurMethod); 632 633 // Perform lookup for Objective-C instance variables (including automatically 634 // synthesized instance variables), if we're in an Objective-C method. 635 // FIXME: This lookup really, really needs to be folded in to the normal 636 // unqualified lookup mechanism. 637 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 638 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 639 if (E.get() || E.isInvalid()) 640 return E; 641 } 642 643 bool SecondTry = false; 644 bool IsFilteredTemplateName = false; 645 646 Corrected: 647 switch (Result.getResultKind()) { 648 case LookupResult::NotFound: 649 // If an unqualified-id is followed by a '(', then we have a function 650 // call. 651 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 652 // In C++, this is an ADL-only call. 653 // FIXME: Reference? 654 if (getLangOpts().CPlusPlus) 655 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 656 657 // C90 6.3.2.2: 658 // If the expression that precedes the parenthesized argument list in a 659 // function call consists solely of an identifier, and if no 660 // declaration is visible for this identifier, the identifier is 661 // implicitly declared exactly as if, in the innermost block containing 662 // the function call, the declaration 663 // 664 // extern int identifier (); 665 // 666 // appeared. 667 // 668 // We also allow this in C99 as an extension. 669 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 670 Result.addDecl(D); 671 Result.resolveKind(); 672 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 673 } 674 } 675 676 // In C, we first see whether there is a tag type by the same name, in 677 // which case it's likely that the user just forget to write "enum", 678 // "struct", or "union". 679 if (!getLangOpts().CPlusPlus && !SecondTry && 680 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 681 break; 682 } 683 684 // Perform typo correction to determine if there is another name that is 685 // close to this name. 686 if (!SecondTry && CCC) { 687 SecondTry = true; 688 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 689 Result.getLookupKind(), S, 690 &SS, *CCC, 691 CTK_ErrorRecovery)) { 692 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 693 unsigned QualifiedDiag = diag::err_no_member_suggest; 694 695 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 696 NamedDecl *UnderlyingFirstDecl 697 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 698 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 699 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 700 UnqualifiedDiag = diag::err_no_template_suggest; 701 QualifiedDiag = diag::err_no_member_template_suggest; 702 } else if (UnderlyingFirstDecl && 703 (isa<TypeDecl>(UnderlyingFirstDecl) || 704 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 705 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 706 UnqualifiedDiag = diag::err_unknown_typename_suggest; 707 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 708 } 709 710 if (SS.isEmpty()) { 711 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 712 } else {// FIXME: is this even reachable? Test it. 713 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 714 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 715 Name->getName().equals(CorrectedStr); 716 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 717 << Name << computeDeclContext(SS, false) 718 << DroppedSpecifier << SS.getRange()); 719 } 720 721 // Update the name, so that the caller has the new name. 722 Name = Corrected.getCorrectionAsIdentifierInfo(); 723 724 // Typo correction corrected to a keyword. 725 if (Corrected.isKeyword()) 726 return Name; 727 728 // Also update the LookupResult... 729 // FIXME: This should probably go away at some point 730 Result.clear(); 731 Result.setLookupName(Corrected.getCorrection()); 732 if (FirstDecl) 733 Result.addDecl(FirstDecl); 734 735 // If we found an Objective-C instance variable, let 736 // LookupInObjCMethod build the appropriate expression to 737 // reference the ivar. 738 // FIXME: This is a gross hack. 739 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 740 Result.clear(); 741 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 742 return E; 743 } 744 745 goto Corrected; 746 } 747 } 748 749 // We failed to correct; just fall through and let the parser deal with it. 750 Result.suppressDiagnostics(); 751 return NameClassification::Unknown(); 752 753 case LookupResult::NotFoundInCurrentInstantiation: { 754 // We performed name lookup into the current instantiation, and there were 755 // dependent bases, so we treat this result the same way as any other 756 // dependent nested-name-specifier. 757 758 // C++ [temp.res]p2: 759 // A name used in a template declaration or definition and that is 760 // dependent on a template-parameter is assumed not to name a type 761 // unless the applicable name lookup finds a type name or the name is 762 // qualified by the keyword typename. 763 // 764 // FIXME: If the next token is '<', we might want to ask the parser to 765 // perform some heroics to see if we actually have a 766 // template-argument-list, which would indicate a missing 'template' 767 // keyword here. 768 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 769 NameInfo, IsAddressOfOperand, 770 /*TemplateArgs=*/nullptr); 771 } 772 773 case LookupResult::Found: 774 case LookupResult::FoundOverloaded: 775 case LookupResult::FoundUnresolvedValue: 776 break; 777 778 case LookupResult::Ambiguous: 779 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 780 hasAnyAcceptableTemplateNames(Result)) { 781 // C++ [temp.local]p3: 782 // A lookup that finds an injected-class-name (10.2) can result in an 783 // ambiguity in certain cases (for example, if it is found in more than 784 // one base class). If all of the injected-class-names that are found 785 // refer to specializations of the same class template, and if the name 786 // is followed by a template-argument-list, the reference refers to the 787 // class template itself and not a specialization thereof, and is not 788 // ambiguous. 789 // 790 // This filtering can make an ambiguous result into an unambiguous one, 791 // so try again after filtering out template names. 792 FilterAcceptableTemplateNames(Result); 793 if (!Result.isAmbiguous()) { 794 IsFilteredTemplateName = true; 795 break; 796 } 797 } 798 799 // Diagnose the ambiguity and return an error. 800 return NameClassification::Error(); 801 } 802 803 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 804 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 805 // C++ [temp.names]p3: 806 // After name lookup (3.4) finds that a name is a template-name or that 807 // an operator-function-id or a literal- operator-id refers to a set of 808 // overloaded functions any member of which is a function template if 809 // this is followed by a <, the < is always taken as the delimiter of a 810 // template-argument-list and never as the less-than operator. 811 if (!IsFilteredTemplateName) 812 FilterAcceptableTemplateNames(Result); 813 814 if (!Result.empty()) { 815 bool IsFunctionTemplate; 816 bool IsVarTemplate; 817 TemplateName Template; 818 if (Result.end() - Result.begin() > 1) { 819 IsFunctionTemplate = true; 820 Template = Context.getOverloadedTemplateName(Result.begin(), 821 Result.end()); 822 } else { 823 TemplateDecl *TD 824 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 825 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 826 IsVarTemplate = isa<VarTemplateDecl>(TD); 827 828 if (SS.isSet() && !SS.isInvalid()) 829 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 830 /*TemplateKeyword=*/false, 831 TD); 832 else 833 Template = TemplateName(TD); 834 } 835 836 if (IsFunctionTemplate) { 837 // Function templates always go through overload resolution, at which 838 // point we'll perform the various checks (e.g., accessibility) we need 839 // to based on which function we selected. 840 Result.suppressDiagnostics(); 841 842 return NameClassification::FunctionTemplate(Template); 843 } 844 845 return IsVarTemplate ? NameClassification::VarTemplate(Template) 846 : NameClassification::TypeTemplate(Template); 847 } 848 } 849 850 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 851 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 852 DiagnoseUseOfDecl(Type, NameLoc); 853 QualType T = Context.getTypeDeclType(Type); 854 if (SS.isNotEmpty()) 855 return buildNestedType(*this, SS, T, NameLoc); 856 return ParsedType::make(T); 857 } 858 859 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 860 if (!Class) { 861 // FIXME: It's unfortunate that we don't have a Type node for handling this. 862 if (ObjCCompatibleAliasDecl *Alias = 863 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 864 Class = Alias->getClassInterface(); 865 } 866 867 if (Class) { 868 DiagnoseUseOfDecl(Class, NameLoc); 869 870 if (NextToken.is(tok::period)) { 871 // Interface. <something> is parsed as a property reference expression. 872 // Just return "unknown" as a fall-through for now. 873 Result.suppressDiagnostics(); 874 return NameClassification::Unknown(); 875 } 876 877 QualType T = Context.getObjCInterfaceType(Class); 878 return ParsedType::make(T); 879 } 880 881 // We can have a type template here if we're classifying a template argument. 882 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 883 return NameClassification::TypeTemplate( 884 TemplateName(cast<TemplateDecl>(FirstDecl))); 885 886 // Check for a tag type hidden by a non-type decl in a few cases where it 887 // seems likely a type is wanted instead of the non-type that was found. 888 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 889 if ((NextToken.is(tok::identifier) || 890 (NextIsOp && 891 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 892 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 893 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 894 DiagnoseUseOfDecl(Type, NameLoc); 895 QualType T = Context.getTypeDeclType(Type); 896 if (SS.isNotEmpty()) 897 return buildNestedType(*this, SS, T, NameLoc); 898 return ParsedType::make(T); 899 } 900 901 if (FirstDecl->isCXXClassMember()) 902 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 903 nullptr); 904 905 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 906 return BuildDeclarationNameExpr(SS, Result, ADL); 907 } 908 909 // Determines the context to return to after temporarily entering a 910 // context. This depends in an unnecessarily complicated way on the 911 // exact ordering of callbacks from the parser. 912 DeclContext *Sema::getContainingDC(DeclContext *DC) { 913 914 // Functions defined inline within classes aren't parsed until we've 915 // finished parsing the top-level class, so the top-level class is 916 // the context we'll need to return to. 917 // A Lambda call operator whose parent is a class must not be treated 918 // as an inline member function. A Lambda can be used legally 919 // either as an in-class member initializer or a default argument. These 920 // are parsed once the class has been marked complete and so the containing 921 // context would be the nested class (when the lambda is defined in one); 922 // If the class is not complete, then the lambda is being used in an 923 // ill-formed fashion (such as to specify the width of a bit-field, or 924 // in an array-bound) - in which case we still want to return the 925 // lexically containing DC (which could be a nested class). 926 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 927 DC = DC->getLexicalParent(); 928 929 // A function not defined within a class will always return to its 930 // lexical context. 931 if (!isa<CXXRecordDecl>(DC)) 932 return DC; 933 934 // A C++ inline method/friend is parsed *after* the topmost class 935 // it was declared in is fully parsed ("complete"); the topmost 936 // class is the context we need to return to. 937 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 938 DC = RD; 939 940 // Return the declaration context of the topmost class the inline method is 941 // declared in. 942 return DC; 943 } 944 945 return DC->getLexicalParent(); 946 } 947 948 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 949 assert(getContainingDC(DC) == CurContext && 950 "The next DeclContext should be lexically contained in the current one."); 951 CurContext = DC; 952 S->setEntity(DC); 953 } 954 955 void Sema::PopDeclContext() { 956 assert(CurContext && "DeclContext imbalance!"); 957 958 CurContext = getContainingDC(CurContext); 959 assert(CurContext && "Popped translation unit!"); 960 } 961 962 /// EnterDeclaratorContext - Used when we must lookup names in the context 963 /// of a declarator's nested name specifier. 964 /// 965 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 966 // C++0x [basic.lookup.unqual]p13: 967 // A name used in the definition of a static data member of class 968 // X (after the qualified-id of the static member) is looked up as 969 // if the name was used in a member function of X. 970 // C++0x [basic.lookup.unqual]p14: 971 // If a variable member of a namespace is defined outside of the 972 // scope of its namespace then any name used in the definition of 973 // the variable member (after the declarator-id) is looked up as 974 // if the definition of the variable member occurred in its 975 // namespace. 976 // Both of these imply that we should push a scope whose context 977 // is the semantic context of the declaration. We can't use 978 // PushDeclContext here because that context is not necessarily 979 // lexically contained in the current context. Fortunately, 980 // the containing scope should have the appropriate information. 981 982 assert(!S->getEntity() && "scope already has entity"); 983 984 #ifndef NDEBUG 985 Scope *Ancestor = S->getParent(); 986 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 987 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 988 #endif 989 990 CurContext = DC; 991 S->setEntity(DC); 992 } 993 994 void Sema::ExitDeclaratorContext(Scope *S) { 995 assert(S->getEntity() == CurContext && "Context imbalance!"); 996 997 // Switch back to the lexical context. The safety of this is 998 // enforced by an assert in EnterDeclaratorContext. 999 Scope *Ancestor = S->getParent(); 1000 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1001 CurContext = Ancestor->getEntity(); 1002 1003 // We don't need to do anything with the scope, which is going to 1004 // disappear. 1005 } 1006 1007 1008 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1009 // We assume that the caller has already called 1010 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1011 FunctionDecl *FD = D->getAsFunction(); 1012 if (!FD) 1013 return; 1014 1015 // Same implementation as PushDeclContext, but enters the context 1016 // from the lexical parent, rather than the top-level class. 1017 assert(CurContext == FD->getLexicalParent() && 1018 "The next DeclContext should be lexically contained in the current one."); 1019 CurContext = FD; 1020 S->setEntity(CurContext); 1021 1022 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1023 ParmVarDecl *Param = FD->getParamDecl(P); 1024 // If the parameter has an identifier, then add it to the scope 1025 if (Param->getIdentifier()) { 1026 S->AddDecl(Param); 1027 IdResolver.AddDecl(Param); 1028 } 1029 } 1030 } 1031 1032 1033 void Sema::ActOnExitFunctionContext() { 1034 // Same implementation as PopDeclContext, but returns to the lexical parent, 1035 // rather than the top-level class. 1036 assert(CurContext && "DeclContext imbalance!"); 1037 CurContext = CurContext->getLexicalParent(); 1038 assert(CurContext && "Popped translation unit!"); 1039 } 1040 1041 1042 /// \brief Determine whether we allow overloading of the function 1043 /// PrevDecl with another declaration. 1044 /// 1045 /// This routine determines whether overloading is possible, not 1046 /// whether some new function is actually an overload. It will return 1047 /// true in C++ (where we can always provide overloads) or, as an 1048 /// extension, in C when the previous function is already an 1049 /// overloaded function declaration or has the "overloadable" 1050 /// attribute. 1051 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1052 ASTContext &Context) { 1053 if (Context.getLangOpts().CPlusPlus) 1054 return true; 1055 1056 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1057 return true; 1058 1059 return (Previous.getResultKind() == LookupResult::Found 1060 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1061 } 1062 1063 /// Add this decl to the scope shadowed decl chains. 1064 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1065 // Move up the scope chain until we find the nearest enclosing 1066 // non-transparent context. The declaration will be introduced into this 1067 // scope. 1068 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1069 S = S->getParent(); 1070 1071 // Add scoped declarations into their context, so that they can be 1072 // found later. Declarations without a context won't be inserted 1073 // into any context. 1074 if (AddToContext) 1075 CurContext->addDecl(D); 1076 1077 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1078 // are function-local declarations. 1079 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1080 !D->getDeclContext()->getRedeclContext()->Equals( 1081 D->getLexicalDeclContext()->getRedeclContext()) && 1082 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1083 return; 1084 1085 // Template instantiations should also not be pushed into scope. 1086 if (isa<FunctionDecl>(D) && 1087 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1088 return; 1089 1090 // If this replaces anything in the current scope, 1091 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1092 IEnd = IdResolver.end(); 1093 for (; I != IEnd; ++I) { 1094 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1095 S->RemoveDecl(*I); 1096 IdResolver.RemoveDecl(*I); 1097 1098 // Should only need to replace one decl. 1099 break; 1100 } 1101 } 1102 1103 S->AddDecl(D); 1104 1105 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1106 // Implicitly-generated labels may end up getting generated in an order that 1107 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1108 // the label at the appropriate place in the identifier chain. 1109 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1110 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1111 if (IDC == CurContext) { 1112 if (!S->isDeclScope(*I)) 1113 continue; 1114 } else if (IDC->Encloses(CurContext)) 1115 break; 1116 } 1117 1118 IdResolver.InsertDeclAfter(I, D); 1119 } else { 1120 IdResolver.AddDecl(D); 1121 } 1122 } 1123 1124 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1125 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1126 TUScope->AddDecl(D); 1127 } 1128 1129 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1130 bool AllowInlineNamespace) { 1131 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1132 } 1133 1134 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1135 DeclContext *TargetDC = DC->getPrimaryContext(); 1136 do { 1137 if (DeclContext *ScopeDC = S->getEntity()) 1138 if (ScopeDC->getPrimaryContext() == TargetDC) 1139 return S; 1140 } while ((S = S->getParent())); 1141 1142 return nullptr; 1143 } 1144 1145 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1146 DeclContext*, 1147 ASTContext&); 1148 1149 /// Filters out lookup results that don't fall within the given scope 1150 /// as determined by isDeclInScope. 1151 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1152 bool ConsiderLinkage, 1153 bool AllowInlineNamespace) { 1154 LookupResult::Filter F = R.makeFilter(); 1155 while (F.hasNext()) { 1156 NamedDecl *D = F.next(); 1157 1158 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1159 continue; 1160 1161 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1162 continue; 1163 1164 F.erase(); 1165 } 1166 1167 F.done(); 1168 } 1169 1170 static bool isUsingDecl(NamedDecl *D) { 1171 return isa<UsingShadowDecl>(D) || 1172 isa<UnresolvedUsingTypenameDecl>(D) || 1173 isa<UnresolvedUsingValueDecl>(D); 1174 } 1175 1176 /// Removes using shadow declarations from the lookup results. 1177 static void RemoveUsingDecls(LookupResult &R) { 1178 LookupResult::Filter F = R.makeFilter(); 1179 while (F.hasNext()) 1180 if (isUsingDecl(F.next())) 1181 F.erase(); 1182 1183 F.done(); 1184 } 1185 1186 /// \brief Check for this common pattern: 1187 /// @code 1188 /// class S { 1189 /// S(const S&); // DO NOT IMPLEMENT 1190 /// void operator=(const S&); // DO NOT IMPLEMENT 1191 /// }; 1192 /// @endcode 1193 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1194 // FIXME: Should check for private access too but access is set after we get 1195 // the decl here. 1196 if (D->doesThisDeclarationHaveABody()) 1197 return false; 1198 1199 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1200 return CD->isCopyConstructor(); 1201 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1202 return Method->isCopyAssignmentOperator(); 1203 return false; 1204 } 1205 1206 // We need this to handle 1207 // 1208 // typedef struct { 1209 // void *foo() { return 0; } 1210 // } A; 1211 // 1212 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1213 // for example. If 'A', foo will have external linkage. If we have '*A', 1214 // foo will have no linkage. Since we can't know until we get to the end 1215 // of the typedef, this function finds out if D might have non-external linkage. 1216 // Callers should verify at the end of the TU if it D has external linkage or 1217 // not. 1218 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1219 const DeclContext *DC = D->getDeclContext(); 1220 while (!DC->isTranslationUnit()) { 1221 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1222 if (!RD->hasNameForLinkage()) 1223 return true; 1224 } 1225 DC = DC->getParent(); 1226 } 1227 1228 return !D->isExternallyVisible(); 1229 } 1230 1231 // FIXME: This needs to be refactored; some other isInMainFile users want 1232 // these semantics. 1233 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1234 if (S.TUKind != TU_Complete) 1235 return false; 1236 return S.SourceMgr.isInMainFile(Loc); 1237 } 1238 1239 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1240 assert(D); 1241 1242 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1243 return false; 1244 1245 // Ignore all entities declared within templates, and out-of-line definitions 1246 // of members of class templates. 1247 if (D->getDeclContext()->isDependentContext() || 1248 D->getLexicalDeclContext()->isDependentContext()) 1249 return false; 1250 1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1252 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1253 return false; 1254 1255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1256 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1257 return false; 1258 } else { 1259 // 'static inline' functions are defined in headers; don't warn. 1260 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1261 return false; 1262 } 1263 1264 if (FD->doesThisDeclarationHaveABody() && 1265 Context.DeclMustBeEmitted(FD)) 1266 return false; 1267 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1268 // Constants and utility variables are defined in headers with internal 1269 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1270 // like "inline".) 1271 if (!isMainFileLoc(*this, VD->getLocation())) 1272 return false; 1273 1274 if (Context.DeclMustBeEmitted(VD)) 1275 return false; 1276 1277 if (VD->isStaticDataMember() && 1278 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1279 return false; 1280 } else { 1281 return false; 1282 } 1283 1284 // Only warn for unused decls internal to the translation unit. 1285 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1286 // for inline functions defined in the main source file, for instance. 1287 return mightHaveNonExternalLinkage(D); 1288 } 1289 1290 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1291 if (!D) 1292 return; 1293 1294 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1295 const FunctionDecl *First = FD->getFirstDecl(); 1296 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1297 return; // First should already be in the vector. 1298 } 1299 1300 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1301 const VarDecl *First = VD->getFirstDecl(); 1302 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1303 return; // First should already be in the vector. 1304 } 1305 1306 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1307 UnusedFileScopedDecls.push_back(D); 1308 } 1309 1310 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1311 if (D->isInvalidDecl()) 1312 return false; 1313 1314 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1315 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1316 return false; 1317 1318 if (isa<LabelDecl>(D)) 1319 return true; 1320 1321 // White-list anything that isn't a local variable. 1322 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1323 !D->getDeclContext()->isFunctionOrMethod()) 1324 return false; 1325 1326 // Types of valid local variables should be complete, so this should succeed. 1327 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1328 1329 // White-list anything with an __attribute__((unused)) type. 1330 QualType Ty = VD->getType(); 1331 1332 // Only look at the outermost level of typedef. 1333 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1334 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1335 return false; 1336 } 1337 1338 // If we failed to complete the type for some reason, or if the type is 1339 // dependent, don't diagnose the variable. 1340 if (Ty->isIncompleteType() || Ty->isDependentType()) 1341 return false; 1342 1343 if (const TagType *TT = Ty->getAs<TagType>()) { 1344 const TagDecl *Tag = TT->getDecl(); 1345 if (Tag->hasAttr<UnusedAttr>()) 1346 return false; 1347 1348 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1349 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1350 return false; 1351 1352 if (const Expr *Init = VD->getInit()) { 1353 if (const ExprWithCleanups *Cleanups = 1354 dyn_cast<ExprWithCleanups>(Init)) 1355 Init = Cleanups->getSubExpr(); 1356 const CXXConstructExpr *Construct = 1357 dyn_cast<CXXConstructExpr>(Init); 1358 if (Construct && !Construct->isElidable()) { 1359 CXXConstructorDecl *CD = Construct->getConstructor(); 1360 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1361 return false; 1362 } 1363 } 1364 } 1365 } 1366 1367 // TODO: __attribute__((unused)) templates? 1368 } 1369 1370 return true; 1371 } 1372 1373 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1374 FixItHint &Hint) { 1375 if (isa<LabelDecl>(D)) { 1376 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1377 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1378 if (AfterColon.isInvalid()) 1379 return; 1380 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1381 getCharRange(D->getLocStart(), AfterColon)); 1382 } 1383 return; 1384 } 1385 1386 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1387 /// unless they are marked attr(unused). 1388 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1389 if (!ShouldDiagnoseUnusedDecl(D)) 1390 return; 1391 1392 FixItHint Hint; 1393 GenerateFixForUnusedDecl(D, Context, Hint); 1394 1395 unsigned DiagID; 1396 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1397 DiagID = diag::warn_unused_exception_param; 1398 else if (isa<LabelDecl>(D)) 1399 DiagID = diag::warn_unused_label; 1400 else 1401 DiagID = diag::warn_unused_variable; 1402 1403 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1404 } 1405 1406 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1407 // Verify that we have no forward references left. If so, there was a goto 1408 // or address of a label taken, but no definition of it. Label fwd 1409 // definitions are indicated with a null substmt. 1410 if (L->getStmt() == nullptr) 1411 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1412 } 1413 1414 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1415 S->mergeNRVOIntoParent(); 1416 1417 if (S->decl_empty()) return; 1418 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1419 "Scope shouldn't contain decls!"); 1420 1421 for (auto *TmpD : S->decls()) { 1422 assert(TmpD && "This decl didn't get pushed??"); 1423 1424 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1425 NamedDecl *D = cast<NamedDecl>(TmpD); 1426 1427 if (!D->getDeclName()) continue; 1428 1429 // Diagnose unused variables in this scope. 1430 if (!S->hasUnrecoverableErrorOccurred()) 1431 DiagnoseUnusedDecl(D); 1432 1433 // If this was a forward reference to a label, verify it was defined. 1434 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1435 CheckPoppedLabel(LD, *this); 1436 1437 // Remove this name from our lexical scope. 1438 IdResolver.RemoveDecl(D); 1439 } 1440 } 1441 1442 /// \brief Look for an Objective-C class in the translation unit. 1443 /// 1444 /// \param Id The name of the Objective-C class we're looking for. If 1445 /// typo-correction fixes this name, the Id will be updated 1446 /// to the fixed name. 1447 /// 1448 /// \param IdLoc The location of the name in the translation unit. 1449 /// 1450 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1451 /// if there is no class with the given name. 1452 /// 1453 /// \returns The declaration of the named Objective-C class, or NULL if the 1454 /// class could not be found. 1455 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1456 SourceLocation IdLoc, 1457 bool DoTypoCorrection) { 1458 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1459 // creation from this context. 1460 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1461 1462 if (!IDecl && DoTypoCorrection) { 1463 // Perform typo correction at the given location, but only if we 1464 // find an Objective-C class name. 1465 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1466 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1467 LookupOrdinaryName, TUScope, nullptr, 1468 Validator, CTK_ErrorRecovery)) { 1469 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1470 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1471 Id = IDecl->getIdentifier(); 1472 } 1473 } 1474 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1475 // This routine must always return a class definition, if any. 1476 if (Def && Def->getDefinition()) 1477 Def = Def->getDefinition(); 1478 return Def; 1479 } 1480 1481 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1482 /// from S, where a non-field would be declared. This routine copes 1483 /// with the difference between C and C++ scoping rules in structs and 1484 /// unions. For example, the following code is well-formed in C but 1485 /// ill-formed in C++: 1486 /// @code 1487 /// struct S6 { 1488 /// enum { BAR } e; 1489 /// }; 1490 /// 1491 /// void test_S6() { 1492 /// struct S6 a; 1493 /// a.e = BAR; 1494 /// } 1495 /// @endcode 1496 /// For the declaration of BAR, this routine will return a different 1497 /// scope. The scope S will be the scope of the unnamed enumeration 1498 /// within S6. In C++, this routine will return the scope associated 1499 /// with S6, because the enumeration's scope is a transparent 1500 /// context but structures can contain non-field names. In C, this 1501 /// routine will return the translation unit scope, since the 1502 /// enumeration's scope is a transparent context and structures cannot 1503 /// contain non-field names. 1504 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1505 while (((S->getFlags() & Scope::DeclScope) == 0) || 1506 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1507 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1508 S = S->getParent(); 1509 return S; 1510 } 1511 1512 /// \brief Looks up the declaration of "struct objc_super" and 1513 /// saves it for later use in building builtin declaration of 1514 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1515 /// pre-existing declaration exists no action takes place. 1516 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1517 IdentifierInfo *II) { 1518 if (!II->isStr("objc_msgSendSuper")) 1519 return; 1520 ASTContext &Context = ThisSema.Context; 1521 1522 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1523 SourceLocation(), Sema::LookupTagName); 1524 ThisSema.LookupName(Result, S); 1525 if (Result.getResultKind() == LookupResult::Found) 1526 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1527 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1528 } 1529 1530 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1531 /// file scope. lazily create a decl for it. ForRedeclaration is true 1532 /// if we're creating this built-in in anticipation of redeclaring the 1533 /// built-in. 1534 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1535 Scope *S, bool ForRedeclaration, 1536 SourceLocation Loc) { 1537 LookupPredefedObjCSuperType(*this, S, II); 1538 1539 Builtin::ID BID = (Builtin::ID)bid; 1540 1541 ASTContext::GetBuiltinTypeError Error; 1542 QualType R = Context.GetBuiltinType(BID, Error); 1543 switch (Error) { 1544 case ASTContext::GE_None: 1545 // Okay 1546 break; 1547 1548 case ASTContext::GE_Missing_stdio: 1549 if (ForRedeclaration) 1550 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1551 << Context.BuiltinInfo.GetName(BID); 1552 return nullptr; 1553 1554 case ASTContext::GE_Missing_setjmp: 1555 if (ForRedeclaration) 1556 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1557 << Context.BuiltinInfo.GetName(BID); 1558 return nullptr; 1559 1560 case ASTContext::GE_Missing_ucontext: 1561 if (ForRedeclaration) 1562 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1563 << Context.BuiltinInfo.GetName(BID); 1564 return nullptr; 1565 } 1566 1567 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1568 Diag(Loc, diag::ext_implicit_lib_function_decl) 1569 << Context.BuiltinInfo.GetName(BID) 1570 << R; 1571 if (Context.BuiltinInfo.getHeaderName(BID) && 1572 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1573 Diag(Loc, diag::note_please_include_header) 1574 << Context.BuiltinInfo.getHeaderName(BID) 1575 << Context.BuiltinInfo.GetName(BID); 1576 } 1577 1578 DeclContext *Parent = Context.getTranslationUnitDecl(); 1579 if (getLangOpts().CPlusPlus) { 1580 LinkageSpecDecl *CLinkageDecl = 1581 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1582 LinkageSpecDecl::lang_c, false); 1583 CLinkageDecl->setImplicit(); 1584 Parent->addDecl(CLinkageDecl); 1585 Parent = CLinkageDecl; 1586 } 1587 1588 FunctionDecl *New = FunctionDecl::Create(Context, 1589 Parent, 1590 Loc, Loc, II, R, /*TInfo=*/nullptr, 1591 SC_Extern, 1592 false, 1593 /*hasPrototype=*/true); 1594 New->setImplicit(); 1595 1596 // Create Decl objects for each parameter, adding them to the 1597 // FunctionDecl. 1598 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1599 SmallVector<ParmVarDecl*, 16> Params; 1600 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1601 ParmVarDecl *parm = 1602 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1603 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1604 SC_None, nullptr); 1605 parm->setScopeInfo(0, i); 1606 Params.push_back(parm); 1607 } 1608 New->setParams(Params); 1609 } 1610 1611 AddKnownFunctionAttributes(New); 1612 RegisterLocallyScopedExternCDecl(New, S); 1613 1614 // TUScope is the translation-unit scope to insert this function into. 1615 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1616 // relate Scopes to DeclContexts, and probably eliminate CurContext 1617 // entirely, but we're not there yet. 1618 DeclContext *SavedContext = CurContext; 1619 CurContext = Parent; 1620 PushOnScopeChains(New, TUScope); 1621 CurContext = SavedContext; 1622 return New; 1623 } 1624 1625 /// \brief Filter out any previous declarations that the given declaration 1626 /// should not consider because they are not permitted to conflict, e.g., 1627 /// because they come from hidden sub-modules and do not refer to the same 1628 /// entity. 1629 static void filterNonConflictingPreviousDecls(ASTContext &context, 1630 NamedDecl *decl, 1631 LookupResult &previous){ 1632 // This is only interesting when modules are enabled. 1633 if (!context.getLangOpts().Modules) 1634 return; 1635 1636 // Empty sets are uninteresting. 1637 if (previous.empty()) 1638 return; 1639 1640 LookupResult::Filter filter = previous.makeFilter(); 1641 while (filter.hasNext()) { 1642 NamedDecl *old = filter.next(); 1643 1644 // Non-hidden declarations are never ignored. 1645 if (!old->isHidden()) 1646 continue; 1647 1648 if (!old->isExternallyVisible()) 1649 filter.erase(); 1650 } 1651 1652 filter.done(); 1653 } 1654 1655 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1656 QualType OldType; 1657 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1658 OldType = OldTypedef->getUnderlyingType(); 1659 else 1660 OldType = Context.getTypeDeclType(Old); 1661 QualType NewType = New->getUnderlyingType(); 1662 1663 if (NewType->isVariablyModifiedType()) { 1664 // Must not redefine a typedef with a variably-modified type. 1665 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1666 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1667 << Kind << NewType; 1668 if (Old->getLocation().isValid()) 1669 Diag(Old->getLocation(), diag::note_previous_definition); 1670 New->setInvalidDecl(); 1671 return true; 1672 } 1673 1674 if (OldType != NewType && 1675 !OldType->isDependentType() && 1676 !NewType->isDependentType() && 1677 !Context.hasSameType(OldType, NewType)) { 1678 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1679 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1680 << Kind << NewType << OldType; 1681 if (Old->getLocation().isValid()) 1682 Diag(Old->getLocation(), diag::note_previous_definition); 1683 New->setInvalidDecl(); 1684 return true; 1685 } 1686 return false; 1687 } 1688 1689 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1690 /// same name and scope as a previous declaration 'Old'. Figure out 1691 /// how to resolve this situation, merging decls or emitting 1692 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1693 /// 1694 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1695 // If the new decl is known invalid already, don't bother doing any 1696 // merging checks. 1697 if (New->isInvalidDecl()) return; 1698 1699 // Allow multiple definitions for ObjC built-in typedefs. 1700 // FIXME: Verify the underlying types are equivalent! 1701 if (getLangOpts().ObjC1) { 1702 const IdentifierInfo *TypeID = New->getIdentifier(); 1703 switch (TypeID->getLength()) { 1704 default: break; 1705 case 2: 1706 { 1707 if (!TypeID->isStr("id")) 1708 break; 1709 QualType T = New->getUnderlyingType(); 1710 if (!T->isPointerType()) 1711 break; 1712 if (!T->isVoidPointerType()) { 1713 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1714 if (!PT->isStructureType()) 1715 break; 1716 } 1717 Context.setObjCIdRedefinitionType(T); 1718 // Install the built-in type for 'id', ignoring the current definition. 1719 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1720 return; 1721 } 1722 case 5: 1723 if (!TypeID->isStr("Class")) 1724 break; 1725 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1726 // Install the built-in type for 'Class', ignoring the current definition. 1727 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1728 return; 1729 case 3: 1730 if (!TypeID->isStr("SEL")) 1731 break; 1732 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1733 // Install the built-in type for 'SEL', ignoring the current definition. 1734 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1735 return; 1736 } 1737 // Fall through - the typedef name was not a builtin type. 1738 } 1739 1740 // Verify the old decl was also a type. 1741 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1742 if (!Old) { 1743 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1744 << New->getDeclName(); 1745 1746 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1747 if (OldD->getLocation().isValid()) 1748 Diag(OldD->getLocation(), diag::note_previous_definition); 1749 1750 return New->setInvalidDecl(); 1751 } 1752 1753 // If the old declaration is invalid, just give up here. 1754 if (Old->isInvalidDecl()) 1755 return New->setInvalidDecl(); 1756 1757 // If the typedef types are not identical, reject them in all languages and 1758 // with any extensions enabled. 1759 if (isIncompatibleTypedef(Old, New)) 1760 return; 1761 1762 // The types match. Link up the redeclaration chain and merge attributes if 1763 // the old declaration was a typedef. 1764 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1765 New->setPreviousDecl(Typedef); 1766 mergeDeclAttributes(New, Old); 1767 } 1768 1769 if (getLangOpts().MicrosoftExt) 1770 return; 1771 1772 if (getLangOpts().CPlusPlus) { 1773 // C++ [dcl.typedef]p2: 1774 // In a given non-class scope, a typedef specifier can be used to 1775 // redefine the name of any type declared in that scope to refer 1776 // to the type to which it already refers. 1777 if (!isa<CXXRecordDecl>(CurContext)) 1778 return; 1779 1780 // C++0x [dcl.typedef]p4: 1781 // In a given class scope, a typedef specifier can be used to redefine 1782 // any class-name declared in that scope that is not also a typedef-name 1783 // to refer to the type to which it already refers. 1784 // 1785 // This wording came in via DR424, which was a correction to the 1786 // wording in DR56, which accidentally banned code like: 1787 // 1788 // struct S { 1789 // typedef struct A { } A; 1790 // }; 1791 // 1792 // in the C++03 standard. We implement the C++0x semantics, which 1793 // allow the above but disallow 1794 // 1795 // struct S { 1796 // typedef int I; 1797 // typedef int I; 1798 // }; 1799 // 1800 // since that was the intent of DR56. 1801 if (!isa<TypedefNameDecl>(Old)) 1802 return; 1803 1804 Diag(New->getLocation(), diag::err_redefinition) 1805 << New->getDeclName(); 1806 Diag(Old->getLocation(), diag::note_previous_definition); 1807 return New->setInvalidDecl(); 1808 } 1809 1810 // Modules always permit redefinition of typedefs, as does C11. 1811 if (getLangOpts().Modules || getLangOpts().C11) 1812 return; 1813 1814 // If we have a redefinition of a typedef in C, emit a warning. This warning 1815 // is normally mapped to an error, but can be controlled with 1816 // -Wtypedef-redefinition. If either the original or the redefinition is 1817 // in a system header, don't emit this for compatibility with GCC. 1818 if (getDiagnostics().getSuppressSystemWarnings() && 1819 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1820 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1821 return; 1822 1823 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1824 << New->getDeclName(); 1825 Diag(Old->getLocation(), diag::note_previous_definition); 1826 return; 1827 } 1828 1829 /// DeclhasAttr - returns true if decl Declaration already has the target 1830 /// attribute. 1831 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1832 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1833 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1834 for (const auto *i : D->attrs()) 1835 if (i->getKind() == A->getKind()) { 1836 if (Ann) { 1837 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1838 return true; 1839 continue; 1840 } 1841 // FIXME: Don't hardcode this check 1842 if (OA && isa<OwnershipAttr>(i)) 1843 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1844 return true; 1845 } 1846 1847 return false; 1848 } 1849 1850 static bool isAttributeTargetADefinition(Decl *D) { 1851 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1852 return VD->isThisDeclarationADefinition(); 1853 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1854 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1855 return true; 1856 } 1857 1858 /// Merge alignment attributes from \p Old to \p New, taking into account the 1859 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1860 /// 1861 /// \return \c true if any attributes were added to \p New. 1862 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1863 // Look for alignas attributes on Old, and pick out whichever attribute 1864 // specifies the strictest alignment requirement. 1865 AlignedAttr *OldAlignasAttr = nullptr; 1866 AlignedAttr *OldStrictestAlignAttr = nullptr; 1867 unsigned OldAlign = 0; 1868 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 1869 // FIXME: We have no way of representing inherited dependent alignments 1870 // in a case like: 1871 // template<int A, int B> struct alignas(A) X; 1872 // template<int A, int B> struct alignas(B) X {}; 1873 // For now, we just ignore any alignas attributes which are not on the 1874 // definition in such a case. 1875 if (I->isAlignmentDependent()) 1876 return false; 1877 1878 if (I->isAlignas()) 1879 OldAlignasAttr = I; 1880 1881 unsigned Align = I->getAlignment(S.Context); 1882 if (Align > OldAlign) { 1883 OldAlign = Align; 1884 OldStrictestAlignAttr = I; 1885 } 1886 } 1887 1888 // Look for alignas attributes on New. 1889 AlignedAttr *NewAlignasAttr = nullptr; 1890 unsigned NewAlign = 0; 1891 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1892 if (I->isAlignmentDependent()) 1893 return false; 1894 1895 if (I->isAlignas()) 1896 NewAlignasAttr = I; 1897 1898 unsigned Align = I->getAlignment(S.Context); 1899 if (Align > NewAlign) 1900 NewAlign = Align; 1901 } 1902 1903 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1904 // Both declarations have 'alignas' attributes. We require them to match. 1905 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1906 // fall short. (If two declarations both have alignas, they must both match 1907 // every definition, and so must match each other if there is a definition.) 1908 1909 // If either declaration only contains 'alignas(0)' specifiers, then it 1910 // specifies the natural alignment for the type. 1911 if (OldAlign == 0 || NewAlign == 0) { 1912 QualType Ty; 1913 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1914 Ty = VD->getType(); 1915 else 1916 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1917 1918 if (OldAlign == 0) 1919 OldAlign = S.Context.getTypeAlign(Ty); 1920 if (NewAlign == 0) 1921 NewAlign = S.Context.getTypeAlign(Ty); 1922 } 1923 1924 if (OldAlign != NewAlign) { 1925 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1926 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1927 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1928 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1929 } 1930 } 1931 1932 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1933 // C++11 [dcl.align]p6: 1934 // if any declaration of an entity has an alignment-specifier, 1935 // every defining declaration of that entity shall specify an 1936 // equivalent alignment. 1937 // C11 6.7.5/7: 1938 // If the definition of an object does not have an alignment 1939 // specifier, any other declaration of that object shall also 1940 // have no alignment specifier. 1941 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1942 << OldAlignasAttr; 1943 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1944 << OldAlignasAttr; 1945 } 1946 1947 bool AnyAdded = false; 1948 1949 // Ensure we have an attribute representing the strictest alignment. 1950 if (OldAlign > NewAlign) { 1951 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1952 Clone->setInherited(true); 1953 New->addAttr(Clone); 1954 AnyAdded = true; 1955 } 1956 1957 // Ensure we have an alignas attribute if the old declaration had one. 1958 if (OldAlignasAttr && !NewAlignasAttr && 1959 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1960 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1961 Clone->setInherited(true); 1962 New->addAttr(Clone); 1963 AnyAdded = true; 1964 } 1965 1966 return AnyAdded; 1967 } 1968 1969 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 1970 const InheritableAttr *Attr, bool Override) { 1971 InheritableAttr *NewAttr = nullptr; 1972 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1973 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 1974 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1975 AA->getIntroduced(), AA->getDeprecated(), 1976 AA->getObsoleted(), AA->getUnavailable(), 1977 AA->getMessage(), Override, 1978 AttrSpellingListIndex); 1979 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 1980 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1981 AttrSpellingListIndex); 1982 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1983 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1984 AttrSpellingListIndex); 1985 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1986 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1987 AttrSpellingListIndex); 1988 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1989 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1990 AttrSpellingListIndex); 1991 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 1992 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1993 FA->getFormatIdx(), FA->getFirstArg(), 1994 AttrSpellingListIndex); 1995 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 1996 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1997 AttrSpellingListIndex); 1998 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1999 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2000 AttrSpellingListIndex, 2001 IA->getSemanticSpelling()); 2002 else if (isa<AlignedAttr>(Attr)) 2003 // AlignedAttrs are handled separately, because we need to handle all 2004 // such attributes on a declaration at the same time. 2005 NewAttr = nullptr; 2006 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2007 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2008 2009 if (NewAttr) { 2010 NewAttr->setInherited(true); 2011 D->addAttr(NewAttr); 2012 return true; 2013 } 2014 2015 return false; 2016 } 2017 2018 static const Decl *getDefinition(const Decl *D) { 2019 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2020 return TD->getDefinition(); 2021 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2022 const VarDecl *Def = VD->getDefinition(); 2023 if (Def) 2024 return Def; 2025 return VD->getActingDefinition(); 2026 } 2027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2028 const FunctionDecl* Def; 2029 if (FD->isDefined(Def)) 2030 return Def; 2031 } 2032 return nullptr; 2033 } 2034 2035 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2036 for (const auto *Attribute : D->attrs()) 2037 if (Attribute->getKind() == Kind) 2038 return true; 2039 return false; 2040 } 2041 2042 /// checkNewAttributesAfterDef - If we already have a definition, check that 2043 /// there are no new attributes in this declaration. 2044 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2045 if (!New->hasAttrs()) 2046 return; 2047 2048 const Decl *Def = getDefinition(Old); 2049 if (!Def || Def == New) 2050 return; 2051 2052 AttrVec &NewAttributes = New->getAttrs(); 2053 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2054 const Attr *NewAttribute = NewAttributes[I]; 2055 2056 if (isa<AliasAttr>(NewAttribute)) { 2057 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2058 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2059 else { 2060 VarDecl *VD = cast<VarDecl>(New); 2061 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2062 VarDecl::TentativeDefinition 2063 ? diag::err_alias_after_tentative 2064 : diag::err_redefinition; 2065 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2066 S.Diag(Def->getLocation(), diag::note_previous_definition); 2067 VD->setInvalidDecl(); 2068 } 2069 ++I; 2070 continue; 2071 } 2072 2073 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2074 // Tentative definitions are only interesting for the alias check above. 2075 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2076 ++I; 2077 continue; 2078 } 2079 } 2080 2081 if (hasAttribute(Def, NewAttribute->getKind())) { 2082 ++I; 2083 continue; // regular attr merging will take care of validating this. 2084 } 2085 2086 if (isa<C11NoReturnAttr>(NewAttribute)) { 2087 // C's _Noreturn is allowed to be added to a function after it is defined. 2088 ++I; 2089 continue; 2090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2091 if (AA->isAlignas()) { 2092 // C++11 [dcl.align]p6: 2093 // if any declaration of an entity has an alignment-specifier, 2094 // every defining declaration of that entity shall specify an 2095 // equivalent alignment. 2096 // C11 6.7.5/7: 2097 // If the definition of an object does not have an alignment 2098 // specifier, any other declaration of that object shall also 2099 // have no alignment specifier. 2100 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2101 << AA; 2102 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2103 << AA; 2104 NewAttributes.erase(NewAttributes.begin() + I); 2105 --E; 2106 continue; 2107 } 2108 } 2109 2110 S.Diag(NewAttribute->getLocation(), 2111 diag::warn_attribute_precede_definition); 2112 S.Diag(Def->getLocation(), diag::note_previous_definition); 2113 NewAttributes.erase(NewAttributes.begin() + I); 2114 --E; 2115 } 2116 } 2117 2118 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2119 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2120 AvailabilityMergeKind AMK) { 2121 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2122 UsedAttr *NewAttr = OldAttr->clone(Context); 2123 NewAttr->setInherited(true); 2124 New->addAttr(NewAttr); 2125 } 2126 2127 if (!Old->hasAttrs() && !New->hasAttrs()) 2128 return; 2129 2130 // attributes declared post-definition are currently ignored 2131 checkNewAttributesAfterDef(*this, New, Old); 2132 2133 if (!Old->hasAttrs()) 2134 return; 2135 2136 bool foundAny = New->hasAttrs(); 2137 2138 // Ensure that any moving of objects within the allocated map is done before 2139 // we process them. 2140 if (!foundAny) New->setAttrs(AttrVec()); 2141 2142 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2143 bool Override = false; 2144 // Ignore deprecated/unavailable/availability attributes if requested. 2145 if (isa<DeprecatedAttr>(I) || 2146 isa<UnavailableAttr>(I) || 2147 isa<AvailabilityAttr>(I)) { 2148 switch (AMK) { 2149 case AMK_None: 2150 continue; 2151 2152 case AMK_Redeclaration: 2153 break; 2154 2155 case AMK_Override: 2156 Override = true; 2157 break; 2158 } 2159 } 2160 2161 // Already handled. 2162 if (isa<UsedAttr>(I)) 2163 continue; 2164 2165 if (mergeDeclAttribute(*this, New, I, Override)) 2166 foundAny = true; 2167 } 2168 2169 if (mergeAlignedAttrs(*this, New, Old)) 2170 foundAny = true; 2171 2172 if (!foundAny) New->dropAttrs(); 2173 } 2174 2175 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2176 /// to the new one. 2177 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2178 const ParmVarDecl *oldDecl, 2179 Sema &S) { 2180 // C++11 [dcl.attr.depend]p2: 2181 // The first declaration of a function shall specify the 2182 // carries_dependency attribute for its declarator-id if any declaration 2183 // of the function specifies the carries_dependency attribute. 2184 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2185 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2186 S.Diag(CDA->getLocation(), 2187 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2188 // Find the first declaration of the parameter. 2189 // FIXME: Should we build redeclaration chains for function parameters? 2190 const FunctionDecl *FirstFD = 2191 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2192 const ParmVarDecl *FirstVD = 2193 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2194 S.Diag(FirstVD->getLocation(), 2195 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2196 } 2197 2198 if (!oldDecl->hasAttrs()) 2199 return; 2200 2201 bool foundAny = newDecl->hasAttrs(); 2202 2203 // Ensure that any moving of objects within the allocated map is 2204 // done before we process them. 2205 if (!foundAny) newDecl->setAttrs(AttrVec()); 2206 2207 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2208 if (!DeclHasAttr(newDecl, I)) { 2209 InheritableAttr *newAttr = 2210 cast<InheritableParamAttr>(I->clone(S.Context)); 2211 newAttr->setInherited(true); 2212 newDecl->addAttr(newAttr); 2213 foundAny = true; 2214 } 2215 } 2216 2217 if (!foundAny) newDecl->dropAttrs(); 2218 } 2219 2220 namespace { 2221 2222 /// Used in MergeFunctionDecl to keep track of function parameters in 2223 /// C. 2224 struct GNUCompatibleParamWarning { 2225 ParmVarDecl *OldParm; 2226 ParmVarDecl *NewParm; 2227 QualType PromotedType; 2228 }; 2229 2230 } 2231 2232 /// getSpecialMember - get the special member enum for a method. 2233 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2234 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2235 if (Ctor->isDefaultConstructor()) 2236 return Sema::CXXDefaultConstructor; 2237 2238 if (Ctor->isCopyConstructor()) 2239 return Sema::CXXCopyConstructor; 2240 2241 if (Ctor->isMoveConstructor()) 2242 return Sema::CXXMoveConstructor; 2243 } else if (isa<CXXDestructorDecl>(MD)) { 2244 return Sema::CXXDestructor; 2245 } else if (MD->isCopyAssignmentOperator()) { 2246 return Sema::CXXCopyAssignment; 2247 } else if (MD->isMoveAssignmentOperator()) { 2248 return Sema::CXXMoveAssignment; 2249 } 2250 2251 return Sema::CXXInvalid; 2252 } 2253 2254 // Determine whether the previous declaration was a definition, implicit 2255 // declaration, or a declaration. 2256 template <typename T> 2257 static std::pair<diag::kind, SourceLocation> 2258 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2259 diag::kind PrevDiag; 2260 SourceLocation OldLocation = Old->getLocation(); 2261 if (Old->isThisDeclarationADefinition()) 2262 PrevDiag = diag::note_previous_definition; 2263 else if (Old->isImplicit()) { 2264 PrevDiag = diag::note_previous_implicit_declaration; 2265 if (OldLocation.isInvalid()) 2266 OldLocation = New->getLocation(); 2267 } else 2268 PrevDiag = diag::note_previous_declaration; 2269 return std::make_pair(PrevDiag, OldLocation); 2270 } 2271 2272 /// canRedefineFunction - checks if a function can be redefined. Currently, 2273 /// only extern inline functions can be redefined, and even then only in 2274 /// GNU89 mode. 2275 static bool canRedefineFunction(const FunctionDecl *FD, 2276 const LangOptions& LangOpts) { 2277 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2278 !LangOpts.CPlusPlus && 2279 FD->isInlineSpecified() && 2280 FD->getStorageClass() == SC_Extern); 2281 } 2282 2283 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2284 const AttributedType *AT = T->getAs<AttributedType>(); 2285 while (AT && !AT->isCallingConv()) 2286 AT = AT->getModifiedType()->getAs<AttributedType>(); 2287 return AT; 2288 } 2289 2290 template <typename T> 2291 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2292 const DeclContext *DC = Old->getDeclContext(); 2293 if (DC->isRecord()) 2294 return false; 2295 2296 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2297 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2298 return true; 2299 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2300 return true; 2301 return false; 2302 } 2303 2304 /// MergeFunctionDecl - We just parsed a function 'New' from 2305 /// declarator D which has the same name and scope as a previous 2306 /// declaration 'Old'. Figure out how to resolve this situation, 2307 /// merging decls or emitting diagnostics as appropriate. 2308 /// 2309 /// In C++, New and Old must be declarations that are not 2310 /// overloaded. Use IsOverload to determine whether New and Old are 2311 /// overloaded, and to select the Old declaration that New should be 2312 /// merged with. 2313 /// 2314 /// Returns true if there was an error, false otherwise. 2315 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2316 Scope *S, bool MergeTypeWithOld) { 2317 // Verify the old decl was also a function. 2318 FunctionDecl *Old = OldD->getAsFunction(); 2319 if (!Old) { 2320 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2321 if (New->getFriendObjectKind()) { 2322 Diag(New->getLocation(), diag::err_using_decl_friend); 2323 Diag(Shadow->getTargetDecl()->getLocation(), 2324 diag::note_using_decl_target); 2325 Diag(Shadow->getUsingDecl()->getLocation(), 2326 diag::note_using_decl) << 0; 2327 return true; 2328 } 2329 2330 // C++11 [namespace.udecl]p14: 2331 // If a function declaration in namespace scope or block scope has the 2332 // same name and the same parameter-type-list as a function introduced 2333 // by a using-declaration, and the declarations do not declare the same 2334 // function, the program is ill-formed. 2335 2336 // Check whether the two declarations might declare the same function. 2337 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2338 if (Old && 2339 !Old->getDeclContext()->getRedeclContext()->Equals( 2340 New->getDeclContext()->getRedeclContext()) && 2341 !(Old->isExternC() && New->isExternC())) 2342 Old = nullptr; 2343 2344 if (!Old) { 2345 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2346 Diag(Shadow->getTargetDecl()->getLocation(), 2347 diag::note_using_decl_target); 2348 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2349 return true; 2350 } 2351 OldD = Old; 2352 } else { 2353 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2354 << New->getDeclName(); 2355 Diag(OldD->getLocation(), diag::note_previous_definition); 2356 return true; 2357 } 2358 } 2359 2360 // If the old declaration is invalid, just give up here. 2361 if (Old->isInvalidDecl()) 2362 return true; 2363 2364 diag::kind PrevDiag; 2365 SourceLocation OldLocation; 2366 std::tie(PrevDiag, OldLocation) = 2367 getNoteDiagForInvalidRedeclaration(Old, New); 2368 2369 // Don't complain about this if we're in GNU89 mode and the old function 2370 // is an extern inline function. 2371 // Don't complain about specializations. They are not supposed to have 2372 // storage classes. 2373 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2374 New->getStorageClass() == SC_Static && 2375 Old->hasExternalFormalLinkage() && 2376 !New->getTemplateSpecializationInfo() && 2377 !canRedefineFunction(Old, getLangOpts())) { 2378 if (getLangOpts().MicrosoftExt) { 2379 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2380 Diag(OldLocation, PrevDiag); 2381 } else { 2382 Diag(New->getLocation(), diag::err_static_non_static) << New; 2383 Diag(OldLocation, PrevDiag); 2384 return true; 2385 } 2386 } 2387 2388 2389 // If a function is first declared with a calling convention, but is later 2390 // declared or defined without one, all following decls assume the calling 2391 // convention of the first. 2392 // 2393 // It's OK if a function is first declared without a calling convention, 2394 // but is later declared or defined with the default calling convention. 2395 // 2396 // To test if either decl has an explicit calling convention, we look for 2397 // AttributedType sugar nodes on the type as written. If they are missing or 2398 // were canonicalized away, we assume the calling convention was implicit. 2399 // 2400 // Note also that we DO NOT return at this point, because we still have 2401 // other tests to run. 2402 QualType OldQType = Context.getCanonicalType(Old->getType()); 2403 QualType NewQType = Context.getCanonicalType(New->getType()); 2404 const FunctionType *OldType = cast<FunctionType>(OldQType); 2405 const FunctionType *NewType = cast<FunctionType>(NewQType); 2406 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2407 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2408 bool RequiresAdjustment = false; 2409 2410 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2411 FunctionDecl *First = Old->getFirstDecl(); 2412 const FunctionType *FT = 2413 First->getType().getCanonicalType()->castAs<FunctionType>(); 2414 FunctionType::ExtInfo FI = FT->getExtInfo(); 2415 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2416 if (!NewCCExplicit) { 2417 // Inherit the CC from the previous declaration if it was specified 2418 // there but not here. 2419 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2420 RequiresAdjustment = true; 2421 } else { 2422 // Calling conventions aren't compatible, so complain. 2423 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2424 Diag(New->getLocation(), diag::err_cconv_change) 2425 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2426 << !FirstCCExplicit 2427 << (!FirstCCExplicit ? "" : 2428 FunctionType::getNameForCallConv(FI.getCC())); 2429 2430 // Put the note on the first decl, since it is the one that matters. 2431 Diag(First->getLocation(), diag::note_previous_declaration); 2432 return true; 2433 } 2434 } 2435 2436 // FIXME: diagnose the other way around? 2437 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2438 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2439 RequiresAdjustment = true; 2440 } 2441 2442 // Merge regparm attribute. 2443 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2444 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2445 if (NewTypeInfo.getHasRegParm()) { 2446 Diag(New->getLocation(), diag::err_regparm_mismatch) 2447 << NewType->getRegParmType() 2448 << OldType->getRegParmType(); 2449 Diag(OldLocation, diag::note_previous_declaration); 2450 return true; 2451 } 2452 2453 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2454 RequiresAdjustment = true; 2455 } 2456 2457 // Merge ns_returns_retained attribute. 2458 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2459 if (NewTypeInfo.getProducesResult()) { 2460 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2461 Diag(OldLocation, diag::note_previous_declaration); 2462 return true; 2463 } 2464 2465 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2466 RequiresAdjustment = true; 2467 } 2468 2469 if (RequiresAdjustment) { 2470 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2471 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2472 New->setType(QualType(AdjustedType, 0)); 2473 NewQType = Context.getCanonicalType(New->getType()); 2474 NewType = cast<FunctionType>(NewQType); 2475 } 2476 2477 // If this redeclaration makes the function inline, we may need to add it to 2478 // UndefinedButUsed. 2479 if (!Old->isInlined() && New->isInlined() && 2480 !New->hasAttr<GNUInlineAttr>() && 2481 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2482 Old->isUsed(false) && 2483 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2484 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2485 SourceLocation())); 2486 2487 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2488 // about it. 2489 if (New->hasAttr<GNUInlineAttr>() && 2490 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2491 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2492 } 2493 2494 if (getLangOpts().CPlusPlus) { 2495 // (C++98 13.1p2): 2496 // Certain function declarations cannot be overloaded: 2497 // -- Function declarations that differ only in the return type 2498 // cannot be overloaded. 2499 2500 // Go back to the type source info to compare the declared return types, 2501 // per C++1y [dcl.type.auto]p13: 2502 // Redeclarations or specializations of a function or function template 2503 // with a declared return type that uses a placeholder type shall also 2504 // use that placeholder, not a deduced type. 2505 QualType OldDeclaredReturnType = 2506 (Old->getTypeSourceInfo() 2507 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2508 : OldType)->getReturnType(); 2509 QualType NewDeclaredReturnType = 2510 (New->getTypeSourceInfo() 2511 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2512 : NewType)->getReturnType(); 2513 QualType ResQT; 2514 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2515 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2516 New->isLocalExternDecl())) { 2517 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2518 OldDeclaredReturnType->isObjCObjectPointerType()) 2519 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2520 if (ResQT.isNull()) { 2521 if (New->isCXXClassMember() && New->isOutOfLine()) 2522 Diag(New->getLocation(), 2523 diag::err_member_def_does_not_match_ret_type) << New; 2524 else 2525 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2526 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2527 return true; 2528 } 2529 else 2530 NewQType = ResQT; 2531 } 2532 2533 QualType OldReturnType = OldType->getReturnType(); 2534 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2535 if (OldReturnType != NewReturnType) { 2536 // If this function has a deduced return type and has already been 2537 // defined, copy the deduced value from the old declaration. 2538 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2539 if (OldAT && OldAT->isDeduced()) { 2540 New->setType( 2541 SubstAutoType(New->getType(), 2542 OldAT->isDependentType() ? Context.DependentTy 2543 : OldAT->getDeducedType())); 2544 NewQType = Context.getCanonicalType( 2545 SubstAutoType(NewQType, 2546 OldAT->isDependentType() ? Context.DependentTy 2547 : OldAT->getDeducedType())); 2548 } 2549 } 2550 2551 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2552 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2553 if (OldMethod && NewMethod) { 2554 // Preserve triviality. 2555 NewMethod->setTrivial(OldMethod->isTrivial()); 2556 2557 // MSVC allows explicit template specialization at class scope: 2558 // 2 CXXMethodDecls referring to the same function will be injected. 2559 // We don't want a redeclaration error. 2560 bool IsClassScopeExplicitSpecialization = 2561 OldMethod->isFunctionTemplateSpecialization() && 2562 NewMethod->isFunctionTemplateSpecialization(); 2563 bool isFriend = NewMethod->getFriendObjectKind(); 2564 2565 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2566 !IsClassScopeExplicitSpecialization) { 2567 // -- Member function declarations with the same name and the 2568 // same parameter types cannot be overloaded if any of them 2569 // is a static member function declaration. 2570 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2571 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2572 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2573 return true; 2574 } 2575 2576 // C++ [class.mem]p1: 2577 // [...] A member shall not be declared twice in the 2578 // member-specification, except that a nested class or member 2579 // class template can be declared and then later defined. 2580 if (ActiveTemplateInstantiations.empty()) { 2581 unsigned NewDiag; 2582 if (isa<CXXConstructorDecl>(OldMethod)) 2583 NewDiag = diag::err_constructor_redeclared; 2584 else if (isa<CXXDestructorDecl>(NewMethod)) 2585 NewDiag = diag::err_destructor_redeclared; 2586 else if (isa<CXXConversionDecl>(NewMethod)) 2587 NewDiag = diag::err_conv_function_redeclared; 2588 else 2589 NewDiag = diag::err_member_redeclared; 2590 2591 Diag(New->getLocation(), NewDiag); 2592 } else { 2593 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2594 << New << New->getType(); 2595 } 2596 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2597 2598 // Complain if this is an explicit declaration of a special 2599 // member that was initially declared implicitly. 2600 // 2601 // As an exception, it's okay to befriend such methods in order 2602 // to permit the implicit constructor/destructor/operator calls. 2603 } else if (OldMethod->isImplicit()) { 2604 if (isFriend) { 2605 NewMethod->setImplicit(); 2606 } else { 2607 Diag(NewMethod->getLocation(), 2608 diag::err_definition_of_implicitly_declared_member) 2609 << New << getSpecialMember(OldMethod); 2610 return true; 2611 } 2612 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2613 Diag(NewMethod->getLocation(), 2614 diag::err_definition_of_explicitly_defaulted_member) 2615 << getSpecialMember(OldMethod); 2616 return true; 2617 } 2618 } 2619 2620 // C++11 [dcl.attr.noreturn]p1: 2621 // The first declaration of a function shall specify the noreturn 2622 // attribute if any declaration of that function specifies the noreturn 2623 // attribute. 2624 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2625 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2626 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2627 Diag(Old->getFirstDecl()->getLocation(), 2628 diag::note_noreturn_missing_first_decl); 2629 } 2630 2631 // C++11 [dcl.attr.depend]p2: 2632 // The first declaration of a function shall specify the 2633 // carries_dependency attribute for its declarator-id if any declaration 2634 // of the function specifies the carries_dependency attribute. 2635 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2636 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2637 Diag(CDA->getLocation(), 2638 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2639 Diag(Old->getFirstDecl()->getLocation(), 2640 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2641 } 2642 2643 // (C++98 8.3.5p3): 2644 // All declarations for a function shall agree exactly in both the 2645 // return type and the parameter-type-list. 2646 // We also want to respect all the extended bits except noreturn. 2647 2648 // noreturn should now match unless the old type info didn't have it. 2649 QualType OldQTypeForComparison = OldQType; 2650 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2651 assert(OldQType == QualType(OldType, 0)); 2652 const FunctionType *OldTypeForComparison 2653 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2654 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2655 assert(OldQTypeForComparison.isCanonical()); 2656 } 2657 2658 if (haveIncompatibleLanguageLinkages(Old, New)) { 2659 // As a special case, retain the language linkage from previous 2660 // declarations of a friend function as an extension. 2661 // 2662 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2663 // and is useful because there's otherwise no way to specify language 2664 // linkage within class scope. 2665 // 2666 // Check cautiously as the friend object kind isn't yet complete. 2667 if (New->getFriendObjectKind() != Decl::FOK_None) { 2668 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2669 Diag(OldLocation, PrevDiag); 2670 } else { 2671 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2672 Diag(OldLocation, PrevDiag); 2673 return true; 2674 } 2675 } 2676 2677 if (OldQTypeForComparison == NewQType) 2678 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2679 2680 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2681 New->isLocalExternDecl()) { 2682 // It's OK if we couldn't merge types for a local function declaraton 2683 // if either the old or new type is dependent. We'll merge the types 2684 // when we instantiate the function. 2685 return false; 2686 } 2687 2688 // Fall through for conflicting redeclarations and redefinitions. 2689 } 2690 2691 // C: Function types need to be compatible, not identical. This handles 2692 // duplicate function decls like "void f(int); void f(enum X);" properly. 2693 if (!getLangOpts().CPlusPlus && 2694 Context.typesAreCompatible(OldQType, NewQType)) { 2695 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2696 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2697 const FunctionProtoType *OldProto = nullptr; 2698 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2699 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2700 // The old declaration provided a function prototype, but the 2701 // new declaration does not. Merge in the prototype. 2702 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2703 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2704 NewQType = 2705 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2706 OldProto->getExtProtoInfo()); 2707 New->setType(NewQType); 2708 New->setHasInheritedPrototype(); 2709 2710 // Synthesize parameters with the same types. 2711 SmallVector<ParmVarDecl*, 16> Params; 2712 for (const auto &ParamType : OldProto->param_types()) { 2713 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2714 SourceLocation(), nullptr, 2715 ParamType, /*TInfo=*/nullptr, 2716 SC_None, nullptr); 2717 Param->setScopeInfo(0, Params.size()); 2718 Param->setImplicit(); 2719 Params.push_back(Param); 2720 } 2721 2722 New->setParams(Params); 2723 } 2724 2725 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2726 } 2727 2728 // GNU C permits a K&R definition to follow a prototype declaration 2729 // if the declared types of the parameters in the K&R definition 2730 // match the types in the prototype declaration, even when the 2731 // promoted types of the parameters from the K&R definition differ 2732 // from the types in the prototype. GCC then keeps the types from 2733 // the prototype. 2734 // 2735 // If a variadic prototype is followed by a non-variadic K&R definition, 2736 // the K&R definition becomes variadic. This is sort of an edge case, but 2737 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2738 // C99 6.9.1p8. 2739 if (!getLangOpts().CPlusPlus && 2740 Old->hasPrototype() && !New->hasPrototype() && 2741 New->getType()->getAs<FunctionProtoType>() && 2742 Old->getNumParams() == New->getNumParams()) { 2743 SmallVector<QualType, 16> ArgTypes; 2744 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2745 const FunctionProtoType *OldProto 2746 = Old->getType()->getAs<FunctionProtoType>(); 2747 const FunctionProtoType *NewProto 2748 = New->getType()->getAs<FunctionProtoType>(); 2749 2750 // Determine whether this is the GNU C extension. 2751 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2752 NewProto->getReturnType()); 2753 bool LooseCompatible = !MergedReturn.isNull(); 2754 for (unsigned Idx = 0, End = Old->getNumParams(); 2755 LooseCompatible && Idx != End; ++Idx) { 2756 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2757 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2758 if (Context.typesAreCompatible(OldParm->getType(), 2759 NewProto->getParamType(Idx))) { 2760 ArgTypes.push_back(NewParm->getType()); 2761 } else if (Context.typesAreCompatible(OldParm->getType(), 2762 NewParm->getType(), 2763 /*CompareUnqualified=*/true)) { 2764 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2765 NewProto->getParamType(Idx) }; 2766 Warnings.push_back(Warn); 2767 ArgTypes.push_back(NewParm->getType()); 2768 } else 2769 LooseCompatible = false; 2770 } 2771 2772 if (LooseCompatible) { 2773 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2774 Diag(Warnings[Warn].NewParm->getLocation(), 2775 diag::ext_param_promoted_not_compatible_with_prototype) 2776 << Warnings[Warn].PromotedType 2777 << Warnings[Warn].OldParm->getType(); 2778 if (Warnings[Warn].OldParm->getLocation().isValid()) 2779 Diag(Warnings[Warn].OldParm->getLocation(), 2780 diag::note_previous_declaration); 2781 } 2782 2783 if (MergeTypeWithOld) 2784 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2785 OldProto->getExtProtoInfo())); 2786 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2787 } 2788 2789 // Fall through to diagnose conflicting types. 2790 } 2791 2792 // A function that has already been declared has been redeclared or 2793 // defined with a different type; show an appropriate diagnostic. 2794 2795 // If the previous declaration was an implicitly-generated builtin 2796 // declaration, then at the very least we should use a specialized note. 2797 unsigned BuiltinID; 2798 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2799 // If it's actually a library-defined builtin function like 'malloc' 2800 // or 'printf', just warn about the incompatible redeclaration. 2801 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2802 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2803 Diag(OldLocation, diag::note_previous_builtin_declaration) 2804 << Old << Old->getType(); 2805 2806 // If this is a global redeclaration, just forget hereafter 2807 // about the "builtin-ness" of the function. 2808 // 2809 // Doing this for local extern declarations is problematic. If 2810 // the builtin declaration remains visible, a second invalid 2811 // local declaration will produce a hard error; if it doesn't 2812 // remain visible, a single bogus local redeclaration (which is 2813 // actually only a warning) could break all the downstream code. 2814 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2815 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2816 2817 return false; 2818 } 2819 2820 PrevDiag = diag::note_previous_builtin_declaration; 2821 } 2822 2823 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2824 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2825 return true; 2826 } 2827 2828 /// \brief Completes the merge of two function declarations that are 2829 /// known to be compatible. 2830 /// 2831 /// This routine handles the merging of attributes and other 2832 /// properties of function declarations from the old declaration to 2833 /// the new declaration, once we know that New is in fact a 2834 /// redeclaration of Old. 2835 /// 2836 /// \returns false 2837 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2838 Scope *S, bool MergeTypeWithOld) { 2839 // Merge the attributes 2840 mergeDeclAttributes(New, Old); 2841 2842 // Merge "pure" flag. 2843 if (Old->isPure()) 2844 New->setPure(); 2845 2846 // Merge "used" flag. 2847 if (Old->getMostRecentDecl()->isUsed(false)) 2848 New->setIsUsed(); 2849 2850 // Merge attributes from the parameters. These can mismatch with K&R 2851 // declarations. 2852 if (New->getNumParams() == Old->getNumParams()) 2853 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2854 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2855 *this); 2856 2857 if (getLangOpts().CPlusPlus) 2858 return MergeCXXFunctionDecl(New, Old, S); 2859 2860 // Merge the function types so the we get the composite types for the return 2861 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2862 // was visible. 2863 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2864 if (!Merged.isNull() && MergeTypeWithOld) 2865 New->setType(Merged); 2866 2867 return false; 2868 } 2869 2870 2871 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2872 ObjCMethodDecl *oldMethod) { 2873 2874 // Merge the attributes, including deprecated/unavailable 2875 AvailabilityMergeKind MergeKind = 2876 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2877 : AMK_Override; 2878 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2879 2880 // Merge attributes from the parameters. 2881 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2882 oe = oldMethod->param_end(); 2883 for (ObjCMethodDecl::param_iterator 2884 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2885 ni != ne && oi != oe; ++ni, ++oi) 2886 mergeParamDeclAttributes(*ni, *oi, *this); 2887 2888 CheckObjCMethodOverride(newMethod, oldMethod); 2889 } 2890 2891 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2892 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2893 /// emitting diagnostics as appropriate. 2894 /// 2895 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2896 /// to here in AddInitializerToDecl. We can't check them before the initializer 2897 /// is attached. 2898 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2899 bool MergeTypeWithOld) { 2900 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2901 return; 2902 2903 QualType MergedT; 2904 if (getLangOpts().CPlusPlus) { 2905 if (New->getType()->isUndeducedType()) { 2906 // We don't know what the new type is until the initializer is attached. 2907 return; 2908 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2909 // These could still be something that needs exception specs checked. 2910 return MergeVarDeclExceptionSpecs(New, Old); 2911 } 2912 // C++ [basic.link]p10: 2913 // [...] the types specified by all declarations referring to a given 2914 // object or function shall be identical, except that declarations for an 2915 // array object can specify array types that differ by the presence or 2916 // absence of a major array bound (8.3.4). 2917 else if (Old->getType()->isIncompleteArrayType() && 2918 New->getType()->isArrayType()) { 2919 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2920 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2921 if (Context.hasSameType(OldArray->getElementType(), 2922 NewArray->getElementType())) 2923 MergedT = New->getType(); 2924 } else if (Old->getType()->isArrayType() && 2925 New->getType()->isIncompleteArrayType()) { 2926 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2927 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2928 if (Context.hasSameType(OldArray->getElementType(), 2929 NewArray->getElementType())) 2930 MergedT = Old->getType(); 2931 } else if (New->getType()->isObjCObjectPointerType() && 2932 Old->getType()->isObjCObjectPointerType()) { 2933 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2934 Old->getType()); 2935 } 2936 } else { 2937 // C 6.2.7p2: 2938 // All declarations that refer to the same object or function shall have 2939 // compatible type. 2940 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2941 } 2942 if (MergedT.isNull()) { 2943 // It's OK if we couldn't merge types if either type is dependent, for a 2944 // block-scope variable. In other cases (static data members of class 2945 // templates, variable templates, ...), we require the types to be 2946 // equivalent. 2947 // FIXME: The C++ standard doesn't say anything about this. 2948 if ((New->getType()->isDependentType() || 2949 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2950 // If the old type was dependent, we can't merge with it, so the new type 2951 // becomes dependent for now. We'll reproduce the original type when we 2952 // instantiate the TypeSourceInfo for the variable. 2953 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2954 New->setType(Context.DependentTy); 2955 return; 2956 } 2957 2958 // FIXME: Even if this merging succeeds, some other non-visible declaration 2959 // of this variable might have an incompatible type. For instance: 2960 // 2961 // extern int arr[]; 2962 // void f() { extern int arr[2]; } 2963 // void g() { extern int arr[3]; } 2964 // 2965 // Neither C nor C++ requires a diagnostic for this, but we should still try 2966 // to diagnose it. 2967 Diag(New->getLocation(), diag::err_redefinition_different_type) 2968 << New->getDeclName() << New->getType() << Old->getType(); 2969 Diag(Old->getLocation(), diag::note_previous_definition); 2970 return New->setInvalidDecl(); 2971 } 2972 2973 // Don't actually update the type on the new declaration if the old 2974 // declaration was an extern declaration in a different scope. 2975 if (MergeTypeWithOld) 2976 New->setType(MergedT); 2977 } 2978 2979 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2980 LookupResult &Previous) { 2981 // C11 6.2.7p4: 2982 // For an identifier with internal or external linkage declared 2983 // in a scope in which a prior declaration of that identifier is 2984 // visible, if the prior declaration specifies internal or 2985 // external linkage, the type of the identifier at the later 2986 // declaration becomes the composite type. 2987 // 2988 // If the variable isn't visible, we do not merge with its type. 2989 if (Previous.isShadowed()) 2990 return false; 2991 2992 if (S.getLangOpts().CPlusPlus) { 2993 // C++11 [dcl.array]p3: 2994 // If there is a preceding declaration of the entity in the same 2995 // scope in which the bound was specified, an omitted array bound 2996 // is taken to be the same as in that earlier declaration. 2997 return NewVD->isPreviousDeclInSameBlockScope() || 2998 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2999 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3000 } else { 3001 // If the old declaration was function-local, don't merge with its 3002 // type unless we're in the same function. 3003 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3004 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3005 } 3006 } 3007 3008 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3009 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3010 /// situation, merging decls or emitting diagnostics as appropriate. 3011 /// 3012 /// Tentative definition rules (C99 6.9.2p2) are checked by 3013 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3014 /// definitions here, since the initializer hasn't been attached. 3015 /// 3016 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3017 // If the new decl is already invalid, don't do any other checking. 3018 if (New->isInvalidDecl()) 3019 return; 3020 3021 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3022 3023 // Verify the old decl was also a variable or variable template. 3024 VarDecl *Old = nullptr; 3025 VarTemplateDecl *OldTemplate = nullptr; 3026 if (Previous.isSingleResult()) { 3027 if (NewTemplate) { 3028 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3029 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3030 } else 3031 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3032 } 3033 if (!Old) { 3034 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3035 << New->getDeclName(); 3036 Diag(Previous.getRepresentativeDecl()->getLocation(), 3037 diag::note_previous_definition); 3038 return New->setInvalidDecl(); 3039 } 3040 3041 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3042 return; 3043 3044 // Ensure the template parameters are compatible. 3045 if (NewTemplate && 3046 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3047 OldTemplate->getTemplateParameters(), 3048 /*Complain=*/true, TPL_TemplateMatch)) 3049 return; 3050 3051 // C++ [class.mem]p1: 3052 // A member shall not be declared twice in the member-specification [...] 3053 // 3054 // Here, we need only consider static data members. 3055 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3056 Diag(New->getLocation(), diag::err_duplicate_member) 3057 << New->getIdentifier(); 3058 Diag(Old->getLocation(), diag::note_previous_declaration); 3059 New->setInvalidDecl(); 3060 } 3061 3062 mergeDeclAttributes(New, Old); 3063 // Warn if an already-declared variable is made a weak_import in a subsequent 3064 // declaration 3065 if (New->hasAttr<WeakImportAttr>() && 3066 Old->getStorageClass() == SC_None && 3067 !Old->hasAttr<WeakImportAttr>()) { 3068 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3069 Diag(Old->getLocation(), diag::note_previous_definition); 3070 // Remove weak_import attribute on new declaration. 3071 New->dropAttr<WeakImportAttr>(); 3072 } 3073 3074 // Merge the types. 3075 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3076 3077 if (New->isInvalidDecl()) 3078 return; 3079 3080 diag::kind PrevDiag; 3081 SourceLocation OldLocation; 3082 std::tie(PrevDiag, OldLocation) = 3083 getNoteDiagForInvalidRedeclaration(Old, New); 3084 3085 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3086 if (New->getStorageClass() == SC_Static && 3087 !New->isStaticDataMember() && 3088 Old->hasExternalFormalLinkage()) { 3089 if (getLangOpts().MicrosoftExt) { 3090 Diag(New->getLocation(), diag::ext_static_non_static) 3091 << New->getDeclName(); 3092 Diag(OldLocation, PrevDiag); 3093 } else { 3094 Diag(New->getLocation(), diag::err_static_non_static) 3095 << New->getDeclName(); 3096 Diag(OldLocation, PrevDiag); 3097 return New->setInvalidDecl(); 3098 } 3099 } 3100 // C99 6.2.2p4: 3101 // For an identifier declared with the storage-class specifier 3102 // extern in a scope in which a prior declaration of that 3103 // identifier is visible,23) if the prior declaration specifies 3104 // internal or external linkage, the linkage of the identifier at 3105 // the later declaration is the same as the linkage specified at 3106 // the prior declaration. If no prior declaration is visible, or 3107 // if the prior declaration specifies no linkage, then the 3108 // identifier has external linkage. 3109 if (New->hasExternalStorage() && Old->hasLinkage()) 3110 /* Okay */; 3111 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3112 !New->isStaticDataMember() && 3113 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3114 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3115 Diag(OldLocation, PrevDiag); 3116 return New->setInvalidDecl(); 3117 } 3118 3119 // Check if extern is followed by non-extern and vice-versa. 3120 if (New->hasExternalStorage() && 3121 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3122 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3123 Diag(OldLocation, PrevDiag); 3124 return New->setInvalidDecl(); 3125 } 3126 if (Old->hasLinkage() && New->isLocalVarDecl() && 3127 !New->hasExternalStorage()) { 3128 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3129 Diag(OldLocation, PrevDiag); 3130 return New->setInvalidDecl(); 3131 } 3132 3133 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3134 3135 // FIXME: The test for external storage here seems wrong? We still 3136 // need to check for mismatches. 3137 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3138 // Don't complain about out-of-line definitions of static members. 3139 !(Old->getLexicalDeclContext()->isRecord() && 3140 !New->getLexicalDeclContext()->isRecord())) { 3141 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3142 Diag(OldLocation, PrevDiag); 3143 return New->setInvalidDecl(); 3144 } 3145 3146 if (New->getTLSKind() != Old->getTLSKind()) { 3147 if (!Old->getTLSKind()) { 3148 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3149 Diag(OldLocation, PrevDiag); 3150 } else if (!New->getTLSKind()) { 3151 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3152 Diag(OldLocation, PrevDiag); 3153 } else { 3154 // Do not allow redeclaration to change the variable between requiring 3155 // static and dynamic initialization. 3156 // FIXME: GCC allows this, but uses the TLS keyword on the first 3157 // declaration to determine the kind. Do we need to be compatible here? 3158 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3159 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3160 Diag(OldLocation, PrevDiag); 3161 } 3162 } 3163 3164 // C++ doesn't have tentative definitions, so go right ahead and check here. 3165 const VarDecl *Def; 3166 if (getLangOpts().CPlusPlus && 3167 New->isThisDeclarationADefinition() == VarDecl::Definition && 3168 (Def = Old->getDefinition())) { 3169 Diag(New->getLocation(), diag::err_redefinition) << New; 3170 Diag(Def->getLocation(), diag::note_previous_definition); 3171 New->setInvalidDecl(); 3172 return; 3173 } 3174 3175 if (haveIncompatibleLanguageLinkages(Old, New)) { 3176 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3177 Diag(OldLocation, PrevDiag); 3178 New->setInvalidDecl(); 3179 return; 3180 } 3181 3182 // Merge "used" flag. 3183 if (Old->getMostRecentDecl()->isUsed(false)) 3184 New->setIsUsed(); 3185 3186 // Keep a chain of previous declarations. 3187 New->setPreviousDecl(Old); 3188 if (NewTemplate) 3189 NewTemplate->setPreviousDecl(OldTemplate); 3190 3191 // Inherit access appropriately. 3192 New->setAccess(Old->getAccess()); 3193 if (NewTemplate) 3194 NewTemplate->setAccess(New->getAccess()); 3195 } 3196 3197 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3198 /// no declarator (e.g. "struct foo;") is parsed. 3199 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3200 DeclSpec &DS) { 3201 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3202 } 3203 3204 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3205 if (!S.Context.getLangOpts().CPlusPlus) 3206 return; 3207 3208 if (isa<CXXRecordDecl>(Tag->getParent())) { 3209 // If this tag is the direct child of a class, number it if 3210 // it is anonymous. 3211 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3212 return; 3213 MangleNumberingContext &MCtx = 3214 S.Context.getManglingNumberContext(Tag->getParent()); 3215 S.Context.setManglingNumber( 3216 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3217 return; 3218 } 3219 3220 // If this tag isn't a direct child of a class, number it if it is local. 3221 Decl *ManglingContextDecl; 3222 if (MangleNumberingContext *MCtx = 3223 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3224 ManglingContextDecl)) { 3225 S.Context.setManglingNumber( 3226 Tag, 3227 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3228 } 3229 } 3230 3231 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3232 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3233 /// parameters to cope with template friend declarations. 3234 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3235 DeclSpec &DS, 3236 MultiTemplateParamsArg TemplateParams, 3237 bool IsExplicitInstantiation) { 3238 Decl *TagD = nullptr; 3239 TagDecl *Tag = nullptr; 3240 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3241 DS.getTypeSpecType() == DeclSpec::TST_struct || 3242 DS.getTypeSpecType() == DeclSpec::TST_interface || 3243 DS.getTypeSpecType() == DeclSpec::TST_union || 3244 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3245 TagD = DS.getRepAsDecl(); 3246 3247 if (!TagD) // We probably had an error 3248 return nullptr; 3249 3250 // Note that the above type specs guarantee that the 3251 // type rep is a Decl, whereas in many of the others 3252 // it's a Type. 3253 if (isa<TagDecl>(TagD)) 3254 Tag = cast<TagDecl>(TagD); 3255 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3256 Tag = CTD->getTemplatedDecl(); 3257 } 3258 3259 if (Tag) { 3260 HandleTagNumbering(*this, Tag, S); 3261 Tag->setFreeStanding(); 3262 if (Tag->isInvalidDecl()) 3263 return Tag; 3264 } 3265 3266 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3267 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3268 // or incomplete types shall not be restrict-qualified." 3269 if (TypeQuals & DeclSpec::TQ_restrict) 3270 Diag(DS.getRestrictSpecLoc(), 3271 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3272 << DS.getSourceRange(); 3273 } 3274 3275 if (DS.isConstexprSpecified()) { 3276 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3277 // and definitions of functions and variables. 3278 if (Tag) 3279 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3280 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3281 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3282 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3283 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3284 else 3285 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3286 // Don't emit warnings after this error. 3287 return TagD; 3288 } 3289 3290 DiagnoseFunctionSpecifiers(DS); 3291 3292 if (DS.isFriendSpecified()) { 3293 // If we're dealing with a decl but not a TagDecl, assume that 3294 // whatever routines created it handled the friendship aspect. 3295 if (TagD && !Tag) 3296 return nullptr; 3297 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3298 } 3299 3300 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3301 bool IsExplicitSpecialization = 3302 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3303 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3304 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3305 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3306 // nested-name-specifier unless it is an explicit instantiation 3307 // or an explicit specialization. 3308 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3309 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3310 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3311 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3312 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3313 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3314 << SS.getRange(); 3315 return nullptr; 3316 } 3317 3318 // Track whether this decl-specifier declares anything. 3319 bool DeclaresAnything = true; 3320 3321 // Handle anonymous struct definitions. 3322 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3323 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3324 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3325 if (getLangOpts().CPlusPlus || 3326 Record->getDeclContext()->isRecord()) 3327 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3328 3329 DeclaresAnything = false; 3330 } 3331 } 3332 3333 // Check for Microsoft C extension: anonymous struct member. 3334 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3335 CurContext->isRecord() && 3336 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3337 // Handle 2 kinds of anonymous struct: 3338 // struct STRUCT; 3339 // and 3340 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3341 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3342 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3343 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3344 DS.getRepAsType().get()->isStructureType())) { 3345 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3346 << DS.getSourceRange(); 3347 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3348 } 3349 } 3350 3351 // Skip all the checks below if we have a type error. 3352 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3353 (TagD && TagD->isInvalidDecl())) 3354 return TagD; 3355 3356 if (getLangOpts().CPlusPlus && 3357 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3358 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3359 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3360 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3361 DeclaresAnything = false; 3362 3363 if (!DS.isMissingDeclaratorOk()) { 3364 // Customize diagnostic for a typedef missing a name. 3365 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3366 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3367 << DS.getSourceRange(); 3368 else 3369 DeclaresAnything = false; 3370 } 3371 3372 if (DS.isModulePrivateSpecified() && 3373 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3374 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3375 << Tag->getTagKind() 3376 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3377 3378 ActOnDocumentableDecl(TagD); 3379 3380 // C 6.7/2: 3381 // A declaration [...] shall declare at least a declarator [...], a tag, 3382 // or the members of an enumeration. 3383 // C++ [dcl.dcl]p3: 3384 // [If there are no declarators], and except for the declaration of an 3385 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3386 // names into the program, or shall redeclare a name introduced by a 3387 // previous declaration. 3388 if (!DeclaresAnything) { 3389 // In C, we allow this as a (popular) extension / bug. Don't bother 3390 // producing further diagnostics for redundant qualifiers after this. 3391 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3392 return TagD; 3393 } 3394 3395 // C++ [dcl.stc]p1: 3396 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3397 // init-declarator-list of the declaration shall not be empty. 3398 // C++ [dcl.fct.spec]p1: 3399 // If a cv-qualifier appears in a decl-specifier-seq, the 3400 // init-declarator-list of the declaration shall not be empty. 3401 // 3402 // Spurious qualifiers here appear to be valid in C. 3403 unsigned DiagID = diag::warn_standalone_specifier; 3404 if (getLangOpts().CPlusPlus) 3405 DiagID = diag::ext_standalone_specifier; 3406 3407 // Note that a linkage-specification sets a storage class, but 3408 // 'extern "C" struct foo;' is actually valid and not theoretically 3409 // useless. 3410 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3411 if (SCS == DeclSpec::SCS_mutable) 3412 // Since mutable is not a viable storage class specifier in C, there is 3413 // no reason to treat it as an extension. Instead, diagnose as an error. 3414 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3415 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3416 Diag(DS.getStorageClassSpecLoc(), DiagID) 3417 << DeclSpec::getSpecifierName(SCS); 3418 } 3419 3420 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3421 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3422 << DeclSpec::getSpecifierName(TSCS); 3423 if (DS.getTypeQualifiers()) { 3424 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3425 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3426 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3427 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3428 // Restrict is covered above. 3429 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3430 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3431 } 3432 3433 // Warn about ignored type attributes, for example: 3434 // __attribute__((aligned)) struct A; 3435 // Attributes should be placed after tag to apply to type declaration. 3436 if (!DS.getAttributes().empty()) { 3437 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3438 if (TypeSpecType == DeclSpec::TST_class || 3439 TypeSpecType == DeclSpec::TST_struct || 3440 TypeSpecType == DeclSpec::TST_interface || 3441 TypeSpecType == DeclSpec::TST_union || 3442 TypeSpecType == DeclSpec::TST_enum) { 3443 AttributeList* attrs = DS.getAttributes().getList(); 3444 while (attrs) { 3445 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3446 << attrs->getName() 3447 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3448 TypeSpecType == DeclSpec::TST_struct ? 1 : 3449 TypeSpecType == DeclSpec::TST_union ? 2 : 3450 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3451 attrs = attrs->getNext(); 3452 } 3453 } 3454 } 3455 3456 return TagD; 3457 } 3458 3459 /// We are trying to inject an anonymous member into the given scope; 3460 /// check if there's an existing declaration that can't be overloaded. 3461 /// 3462 /// \return true if this is a forbidden redeclaration 3463 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3464 Scope *S, 3465 DeclContext *Owner, 3466 DeclarationName Name, 3467 SourceLocation NameLoc, 3468 unsigned diagnostic) { 3469 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3470 Sema::ForRedeclaration); 3471 if (!SemaRef.LookupName(R, S)) return false; 3472 3473 if (R.getAsSingle<TagDecl>()) 3474 return false; 3475 3476 // Pick a representative declaration. 3477 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3478 assert(PrevDecl && "Expected a non-null Decl"); 3479 3480 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3481 return false; 3482 3483 SemaRef.Diag(NameLoc, diagnostic) << Name; 3484 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3485 3486 return true; 3487 } 3488 3489 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3490 /// anonymous struct or union AnonRecord into the owning context Owner 3491 /// and scope S. This routine will be invoked just after we realize 3492 /// that an unnamed union or struct is actually an anonymous union or 3493 /// struct, e.g., 3494 /// 3495 /// @code 3496 /// union { 3497 /// int i; 3498 /// float f; 3499 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3500 /// // f into the surrounding scope.x 3501 /// @endcode 3502 /// 3503 /// This routine is recursive, injecting the names of nested anonymous 3504 /// structs/unions into the owning context and scope as well. 3505 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3506 DeclContext *Owner, 3507 RecordDecl *AnonRecord, 3508 AccessSpecifier AS, 3509 SmallVectorImpl<NamedDecl *> &Chaining, 3510 bool MSAnonStruct) { 3511 unsigned diagKind 3512 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3513 : diag::err_anonymous_struct_member_redecl; 3514 3515 bool Invalid = false; 3516 3517 // Look every FieldDecl and IndirectFieldDecl with a name. 3518 for (auto *D : AnonRecord->decls()) { 3519 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3520 cast<NamedDecl>(D)->getDeclName()) { 3521 ValueDecl *VD = cast<ValueDecl>(D); 3522 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3523 VD->getLocation(), diagKind)) { 3524 // C++ [class.union]p2: 3525 // The names of the members of an anonymous union shall be 3526 // distinct from the names of any other entity in the 3527 // scope in which the anonymous union is declared. 3528 Invalid = true; 3529 } else { 3530 // C++ [class.union]p2: 3531 // For the purpose of name lookup, after the anonymous union 3532 // definition, the members of the anonymous union are 3533 // considered to have been defined in the scope in which the 3534 // anonymous union is declared. 3535 unsigned OldChainingSize = Chaining.size(); 3536 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3537 for (auto *PI : IF->chain()) 3538 Chaining.push_back(PI); 3539 else 3540 Chaining.push_back(VD); 3541 3542 assert(Chaining.size() >= 2); 3543 NamedDecl **NamedChain = 3544 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3545 for (unsigned i = 0; i < Chaining.size(); i++) 3546 NamedChain[i] = Chaining[i]; 3547 3548 IndirectFieldDecl* IndirectField = 3549 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3550 VD->getIdentifier(), VD->getType(), 3551 NamedChain, Chaining.size()); 3552 3553 IndirectField->setAccess(AS); 3554 IndirectField->setImplicit(); 3555 SemaRef.PushOnScopeChains(IndirectField, S); 3556 3557 // That includes picking up the appropriate access specifier. 3558 if (AS != AS_none) IndirectField->setAccess(AS); 3559 3560 Chaining.resize(OldChainingSize); 3561 } 3562 } 3563 } 3564 3565 return Invalid; 3566 } 3567 3568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3569 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3570 /// illegal input values are mapped to SC_None. 3571 static StorageClass 3572 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3573 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3574 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3575 "Parser allowed 'typedef' as storage class VarDecl."); 3576 switch (StorageClassSpec) { 3577 case DeclSpec::SCS_unspecified: return SC_None; 3578 case DeclSpec::SCS_extern: 3579 if (DS.isExternInLinkageSpec()) 3580 return SC_None; 3581 return SC_Extern; 3582 case DeclSpec::SCS_static: return SC_Static; 3583 case DeclSpec::SCS_auto: return SC_Auto; 3584 case DeclSpec::SCS_register: return SC_Register; 3585 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3586 // Illegal SCSs map to None: error reporting is up to the caller. 3587 case DeclSpec::SCS_mutable: // Fall through. 3588 case DeclSpec::SCS_typedef: return SC_None; 3589 } 3590 llvm_unreachable("unknown storage class specifier"); 3591 } 3592 3593 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3594 assert(Record->hasInClassInitializer()); 3595 3596 for (const auto *I : Record->decls()) { 3597 const auto *FD = dyn_cast<FieldDecl>(I); 3598 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3599 FD = IFD->getAnonField(); 3600 if (FD && FD->hasInClassInitializer()) 3601 return FD->getLocation(); 3602 } 3603 3604 llvm_unreachable("couldn't find in-class initializer"); 3605 } 3606 3607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3608 SourceLocation DefaultInitLoc) { 3609 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3610 return; 3611 3612 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3613 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3614 } 3615 3616 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3617 CXXRecordDecl *AnonUnion) { 3618 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3619 return; 3620 3621 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3622 } 3623 3624 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3625 /// anonymous structure or union. Anonymous unions are a C++ feature 3626 /// (C++ [class.union]) and a C11 feature; anonymous structures 3627 /// are a C11 feature and GNU C++ extension. 3628 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3629 AccessSpecifier AS, 3630 RecordDecl *Record, 3631 const PrintingPolicy &Policy) { 3632 DeclContext *Owner = Record->getDeclContext(); 3633 3634 // Diagnose whether this anonymous struct/union is an extension. 3635 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3636 Diag(Record->getLocation(), diag::ext_anonymous_union); 3637 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3638 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3639 else if (!Record->isUnion() && !getLangOpts().C11) 3640 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3641 3642 // C and C++ require different kinds of checks for anonymous 3643 // structs/unions. 3644 bool Invalid = false; 3645 if (getLangOpts().CPlusPlus) { 3646 const char *PrevSpec = nullptr; 3647 unsigned DiagID; 3648 if (Record->isUnion()) { 3649 // C++ [class.union]p6: 3650 // Anonymous unions declared in a named namespace or in the 3651 // global namespace shall be declared static. 3652 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3653 (isa<TranslationUnitDecl>(Owner) || 3654 (isa<NamespaceDecl>(Owner) && 3655 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3656 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3657 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3658 3659 // Recover by adding 'static'. 3660 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3661 PrevSpec, DiagID, Policy); 3662 } 3663 // C++ [class.union]p6: 3664 // A storage class is not allowed in a declaration of an 3665 // anonymous union in a class scope. 3666 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3667 isa<RecordDecl>(Owner)) { 3668 Diag(DS.getStorageClassSpecLoc(), 3669 diag::err_anonymous_union_with_storage_spec) 3670 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3671 3672 // Recover by removing the storage specifier. 3673 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3674 SourceLocation(), 3675 PrevSpec, DiagID, Context.getPrintingPolicy()); 3676 } 3677 } 3678 3679 // Ignore const/volatile/restrict qualifiers. 3680 if (DS.getTypeQualifiers()) { 3681 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3682 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3683 << Record->isUnion() << "const" 3684 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3685 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3686 Diag(DS.getVolatileSpecLoc(), 3687 diag::ext_anonymous_struct_union_qualified) 3688 << Record->isUnion() << "volatile" 3689 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3690 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3691 Diag(DS.getRestrictSpecLoc(), 3692 diag::ext_anonymous_struct_union_qualified) 3693 << Record->isUnion() << "restrict" 3694 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3695 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3696 Diag(DS.getAtomicSpecLoc(), 3697 diag::ext_anonymous_struct_union_qualified) 3698 << Record->isUnion() << "_Atomic" 3699 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3700 3701 DS.ClearTypeQualifiers(); 3702 } 3703 3704 // C++ [class.union]p2: 3705 // The member-specification of an anonymous union shall only 3706 // define non-static data members. [Note: nested types and 3707 // functions cannot be declared within an anonymous union. ] 3708 for (auto *Mem : Record->decls()) { 3709 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3710 // C++ [class.union]p3: 3711 // An anonymous union shall not have private or protected 3712 // members (clause 11). 3713 assert(FD->getAccess() != AS_none); 3714 if (FD->getAccess() != AS_public) { 3715 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3716 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3717 Invalid = true; 3718 } 3719 3720 // C++ [class.union]p1 3721 // An object of a class with a non-trivial constructor, a non-trivial 3722 // copy constructor, a non-trivial destructor, or a non-trivial copy 3723 // assignment operator cannot be a member of a union, nor can an 3724 // array of such objects. 3725 if (CheckNontrivialField(FD)) 3726 Invalid = true; 3727 } else if (Mem->isImplicit()) { 3728 // Any implicit members are fine. 3729 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3730 // This is a type that showed up in an 3731 // elaborated-type-specifier inside the anonymous struct or 3732 // union, but which actually declares a type outside of the 3733 // anonymous struct or union. It's okay. 3734 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3735 if (!MemRecord->isAnonymousStructOrUnion() && 3736 MemRecord->getDeclName()) { 3737 // Visual C++ allows type definition in anonymous struct or union. 3738 if (getLangOpts().MicrosoftExt) 3739 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3740 << (int)Record->isUnion(); 3741 else { 3742 // This is a nested type declaration. 3743 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3744 << (int)Record->isUnion(); 3745 Invalid = true; 3746 } 3747 } else { 3748 // This is an anonymous type definition within another anonymous type. 3749 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3750 // not part of standard C++. 3751 Diag(MemRecord->getLocation(), 3752 diag::ext_anonymous_record_with_anonymous_type) 3753 << (int)Record->isUnion(); 3754 } 3755 } else if (isa<AccessSpecDecl>(Mem)) { 3756 // Any access specifier is fine. 3757 } else if (isa<StaticAssertDecl>(Mem)) { 3758 // In C++1z, static_assert declarations are also fine. 3759 } else { 3760 // We have something that isn't a non-static data 3761 // member. Complain about it. 3762 unsigned DK = diag::err_anonymous_record_bad_member; 3763 if (isa<TypeDecl>(Mem)) 3764 DK = diag::err_anonymous_record_with_type; 3765 else if (isa<FunctionDecl>(Mem)) 3766 DK = diag::err_anonymous_record_with_function; 3767 else if (isa<VarDecl>(Mem)) 3768 DK = diag::err_anonymous_record_with_static; 3769 3770 // Visual C++ allows type definition in anonymous struct or union. 3771 if (getLangOpts().MicrosoftExt && 3772 DK == diag::err_anonymous_record_with_type) 3773 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3774 << (int)Record->isUnion(); 3775 else { 3776 Diag(Mem->getLocation(), DK) 3777 << (int)Record->isUnion(); 3778 Invalid = true; 3779 } 3780 } 3781 } 3782 3783 // C++11 [class.union]p8 (DR1460): 3784 // At most one variant member of a union may have a 3785 // brace-or-equal-initializer. 3786 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3787 Owner->isRecord()) 3788 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3789 cast<CXXRecordDecl>(Record)); 3790 } 3791 3792 if (!Record->isUnion() && !Owner->isRecord()) { 3793 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3794 << (int)getLangOpts().CPlusPlus; 3795 Invalid = true; 3796 } 3797 3798 // Mock up a declarator. 3799 Declarator Dc(DS, Declarator::MemberContext); 3800 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3801 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3802 3803 // Create a declaration for this anonymous struct/union. 3804 NamedDecl *Anon = nullptr; 3805 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3806 Anon = FieldDecl::Create(Context, OwningClass, 3807 DS.getLocStart(), 3808 Record->getLocation(), 3809 /*IdentifierInfo=*/nullptr, 3810 Context.getTypeDeclType(Record), 3811 TInfo, 3812 /*BitWidth=*/nullptr, /*Mutable=*/false, 3813 /*InitStyle=*/ICIS_NoInit); 3814 Anon->setAccess(AS); 3815 if (getLangOpts().CPlusPlus) 3816 FieldCollector->Add(cast<FieldDecl>(Anon)); 3817 } else { 3818 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3819 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3820 if (SCSpec == DeclSpec::SCS_mutable) { 3821 // mutable can only appear on non-static class members, so it's always 3822 // an error here 3823 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3824 Invalid = true; 3825 SC = SC_None; 3826 } 3827 3828 Anon = VarDecl::Create(Context, Owner, 3829 DS.getLocStart(), 3830 Record->getLocation(), /*IdentifierInfo=*/nullptr, 3831 Context.getTypeDeclType(Record), 3832 TInfo, SC); 3833 3834 // Default-initialize the implicit variable. This initialization will be 3835 // trivial in almost all cases, except if a union member has an in-class 3836 // initializer: 3837 // union { int n = 0; }; 3838 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3839 } 3840 Anon->setImplicit(); 3841 3842 // Mark this as an anonymous struct/union type. 3843 Record->setAnonymousStructOrUnion(true); 3844 3845 // Add the anonymous struct/union object to the current 3846 // context. We'll be referencing this object when we refer to one of 3847 // its members. 3848 Owner->addDecl(Anon); 3849 3850 // Inject the members of the anonymous struct/union into the owning 3851 // context and into the identifier resolver chain for name lookup 3852 // purposes. 3853 SmallVector<NamedDecl*, 2> Chain; 3854 Chain.push_back(Anon); 3855 3856 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3857 Chain, false)) 3858 Invalid = true; 3859 3860 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3861 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3862 Decl *ManglingContextDecl; 3863 if (MangleNumberingContext *MCtx = 3864 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3865 ManglingContextDecl)) { 3866 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3867 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3868 } 3869 } 3870 } 3871 3872 if (Invalid) 3873 Anon->setInvalidDecl(); 3874 3875 return Anon; 3876 } 3877 3878 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3879 /// Microsoft C anonymous structure. 3880 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3881 /// Example: 3882 /// 3883 /// struct A { int a; }; 3884 /// struct B { struct A; int b; }; 3885 /// 3886 /// void foo() { 3887 /// B var; 3888 /// var.a = 3; 3889 /// } 3890 /// 3891 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3892 RecordDecl *Record) { 3893 3894 // If there is no Record, get the record via the typedef. 3895 if (!Record) 3896 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3897 3898 // Mock up a declarator. 3899 Declarator Dc(DS, Declarator::TypeNameContext); 3900 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3901 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3902 3903 // Create a declaration for this anonymous struct. 3904 NamedDecl *Anon = FieldDecl::Create(Context, 3905 cast<RecordDecl>(CurContext), 3906 DS.getLocStart(), 3907 DS.getLocStart(), 3908 /*IdentifierInfo=*/nullptr, 3909 Context.getTypeDeclType(Record), 3910 TInfo, 3911 /*BitWidth=*/nullptr, /*Mutable=*/false, 3912 /*InitStyle=*/ICIS_NoInit); 3913 Anon->setImplicit(); 3914 3915 // Add the anonymous struct object to the current context. 3916 CurContext->addDecl(Anon); 3917 3918 // Inject the members of the anonymous struct into the current 3919 // context and into the identifier resolver chain for name lookup 3920 // purposes. 3921 SmallVector<NamedDecl*, 2> Chain; 3922 Chain.push_back(Anon); 3923 3924 RecordDecl *RecordDef = Record->getDefinition(); 3925 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3926 RecordDef, AS_none, 3927 Chain, true)) 3928 Anon->setInvalidDecl(); 3929 3930 return Anon; 3931 } 3932 3933 /// GetNameForDeclarator - Determine the full declaration name for the 3934 /// given Declarator. 3935 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3936 return GetNameFromUnqualifiedId(D.getName()); 3937 } 3938 3939 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3940 DeclarationNameInfo 3941 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3942 DeclarationNameInfo NameInfo; 3943 NameInfo.setLoc(Name.StartLocation); 3944 3945 switch (Name.getKind()) { 3946 3947 case UnqualifiedId::IK_ImplicitSelfParam: 3948 case UnqualifiedId::IK_Identifier: 3949 NameInfo.setName(Name.Identifier); 3950 NameInfo.setLoc(Name.StartLocation); 3951 return NameInfo; 3952 3953 case UnqualifiedId::IK_OperatorFunctionId: 3954 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3955 Name.OperatorFunctionId.Operator)); 3956 NameInfo.setLoc(Name.StartLocation); 3957 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3958 = Name.OperatorFunctionId.SymbolLocations[0]; 3959 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3960 = Name.EndLocation.getRawEncoding(); 3961 return NameInfo; 3962 3963 case UnqualifiedId::IK_LiteralOperatorId: 3964 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3965 Name.Identifier)); 3966 NameInfo.setLoc(Name.StartLocation); 3967 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3968 return NameInfo; 3969 3970 case UnqualifiedId::IK_ConversionFunctionId: { 3971 TypeSourceInfo *TInfo; 3972 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3973 if (Ty.isNull()) 3974 return DeclarationNameInfo(); 3975 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3976 Context.getCanonicalType(Ty))); 3977 NameInfo.setLoc(Name.StartLocation); 3978 NameInfo.setNamedTypeInfo(TInfo); 3979 return NameInfo; 3980 } 3981 3982 case UnqualifiedId::IK_ConstructorName: { 3983 TypeSourceInfo *TInfo; 3984 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3985 if (Ty.isNull()) 3986 return DeclarationNameInfo(); 3987 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3988 Context.getCanonicalType(Ty))); 3989 NameInfo.setLoc(Name.StartLocation); 3990 NameInfo.setNamedTypeInfo(TInfo); 3991 return NameInfo; 3992 } 3993 3994 case UnqualifiedId::IK_ConstructorTemplateId: { 3995 // In well-formed code, we can only have a constructor 3996 // template-id that refers to the current context, so go there 3997 // to find the actual type being constructed. 3998 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3999 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4000 return DeclarationNameInfo(); 4001 4002 // Determine the type of the class being constructed. 4003 QualType CurClassType = Context.getTypeDeclType(CurClass); 4004 4005 // FIXME: Check two things: that the template-id names the same type as 4006 // CurClassType, and that the template-id does not occur when the name 4007 // was qualified. 4008 4009 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4010 Context.getCanonicalType(CurClassType))); 4011 NameInfo.setLoc(Name.StartLocation); 4012 // FIXME: should we retrieve TypeSourceInfo? 4013 NameInfo.setNamedTypeInfo(nullptr); 4014 return NameInfo; 4015 } 4016 4017 case UnqualifiedId::IK_DestructorName: { 4018 TypeSourceInfo *TInfo; 4019 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4020 if (Ty.isNull()) 4021 return DeclarationNameInfo(); 4022 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4023 Context.getCanonicalType(Ty))); 4024 NameInfo.setLoc(Name.StartLocation); 4025 NameInfo.setNamedTypeInfo(TInfo); 4026 return NameInfo; 4027 } 4028 4029 case UnqualifiedId::IK_TemplateId: { 4030 TemplateName TName = Name.TemplateId->Template.get(); 4031 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4032 return Context.getNameForTemplate(TName, TNameLoc); 4033 } 4034 4035 } // switch (Name.getKind()) 4036 4037 llvm_unreachable("Unknown name kind"); 4038 } 4039 4040 static QualType getCoreType(QualType Ty) { 4041 do { 4042 if (Ty->isPointerType() || Ty->isReferenceType()) 4043 Ty = Ty->getPointeeType(); 4044 else if (Ty->isArrayType()) 4045 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4046 else 4047 return Ty.withoutLocalFastQualifiers(); 4048 } while (true); 4049 } 4050 4051 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4052 /// and Definition have "nearly" matching parameters. This heuristic is 4053 /// used to improve diagnostics in the case where an out-of-line function 4054 /// definition doesn't match any declaration within the class or namespace. 4055 /// Also sets Params to the list of indices to the parameters that differ 4056 /// between the declaration and the definition. If hasSimilarParameters 4057 /// returns true and Params is empty, then all of the parameters match. 4058 static bool hasSimilarParameters(ASTContext &Context, 4059 FunctionDecl *Declaration, 4060 FunctionDecl *Definition, 4061 SmallVectorImpl<unsigned> &Params) { 4062 Params.clear(); 4063 if (Declaration->param_size() != Definition->param_size()) 4064 return false; 4065 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4066 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4067 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4068 4069 // The parameter types are identical 4070 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4071 continue; 4072 4073 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4074 QualType DefParamBaseTy = getCoreType(DefParamTy); 4075 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4076 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4077 4078 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4079 (DeclTyName && DeclTyName == DefTyName)) 4080 Params.push_back(Idx); 4081 else // The two parameters aren't even close 4082 return false; 4083 } 4084 4085 return true; 4086 } 4087 4088 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4089 /// declarator needs to be rebuilt in the current instantiation. 4090 /// Any bits of declarator which appear before the name are valid for 4091 /// consideration here. That's specifically the type in the decl spec 4092 /// and the base type in any member-pointer chunks. 4093 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4094 DeclarationName Name) { 4095 // The types we specifically need to rebuild are: 4096 // - typenames, typeofs, and decltypes 4097 // - types which will become injected class names 4098 // Of course, we also need to rebuild any type referencing such a 4099 // type. It's safest to just say "dependent", but we call out a 4100 // few cases here. 4101 4102 DeclSpec &DS = D.getMutableDeclSpec(); 4103 switch (DS.getTypeSpecType()) { 4104 case DeclSpec::TST_typename: 4105 case DeclSpec::TST_typeofType: 4106 case DeclSpec::TST_underlyingType: 4107 case DeclSpec::TST_atomic: { 4108 // Grab the type from the parser. 4109 TypeSourceInfo *TSI = nullptr; 4110 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4111 if (T.isNull() || !T->isDependentType()) break; 4112 4113 // Make sure there's a type source info. This isn't really much 4114 // of a waste; most dependent types should have type source info 4115 // attached already. 4116 if (!TSI) 4117 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4118 4119 // Rebuild the type in the current instantiation. 4120 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4121 if (!TSI) return true; 4122 4123 // Store the new type back in the decl spec. 4124 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4125 DS.UpdateTypeRep(LocType); 4126 break; 4127 } 4128 4129 case DeclSpec::TST_decltype: 4130 case DeclSpec::TST_typeofExpr: { 4131 Expr *E = DS.getRepAsExpr(); 4132 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4133 if (Result.isInvalid()) return true; 4134 DS.UpdateExprRep(Result.get()); 4135 break; 4136 } 4137 4138 default: 4139 // Nothing to do for these decl specs. 4140 break; 4141 } 4142 4143 // It doesn't matter what order we do this in. 4144 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4145 DeclaratorChunk &Chunk = D.getTypeObject(I); 4146 4147 // The only type information in the declarator which can come 4148 // before the declaration name is the base type of a member 4149 // pointer. 4150 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4151 continue; 4152 4153 // Rebuild the scope specifier in-place. 4154 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4155 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4156 return true; 4157 } 4158 4159 return false; 4160 } 4161 4162 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4163 D.setFunctionDefinitionKind(FDK_Declaration); 4164 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4165 4166 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4167 Dcl && Dcl->getDeclContext()->isFileContext()) 4168 Dcl->setTopLevelDeclInObjCContainer(); 4169 4170 return Dcl; 4171 } 4172 4173 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4174 /// If T is the name of a class, then each of the following shall have a 4175 /// name different from T: 4176 /// - every static data member of class T; 4177 /// - every member function of class T 4178 /// - every member of class T that is itself a type; 4179 /// \returns true if the declaration name violates these rules. 4180 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4181 DeclarationNameInfo NameInfo) { 4182 DeclarationName Name = NameInfo.getName(); 4183 4184 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4185 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4186 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4187 return true; 4188 } 4189 4190 return false; 4191 } 4192 4193 /// \brief Diagnose a declaration whose declarator-id has the given 4194 /// nested-name-specifier. 4195 /// 4196 /// \param SS The nested-name-specifier of the declarator-id. 4197 /// 4198 /// \param DC The declaration context to which the nested-name-specifier 4199 /// resolves. 4200 /// 4201 /// \param Name The name of the entity being declared. 4202 /// 4203 /// \param Loc The location of the name of the entity being declared. 4204 /// 4205 /// \returns true if we cannot safely recover from this error, false otherwise. 4206 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4207 DeclarationName Name, 4208 SourceLocation Loc) { 4209 DeclContext *Cur = CurContext; 4210 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4211 Cur = Cur->getParent(); 4212 4213 // If the user provided a superfluous scope specifier that refers back to the 4214 // class in which the entity is already declared, diagnose and ignore it. 4215 // 4216 // class X { 4217 // void X::f(); 4218 // }; 4219 // 4220 // Note, it was once ill-formed to give redundant qualification in all 4221 // contexts, but that rule was removed by DR482. 4222 if (Cur->Equals(DC)) { 4223 if (Cur->isRecord()) { 4224 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4225 : diag::err_member_extra_qualification) 4226 << Name << FixItHint::CreateRemoval(SS.getRange()); 4227 SS.clear(); 4228 } else { 4229 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4230 } 4231 return false; 4232 } 4233 4234 // Check whether the qualifying scope encloses the scope of the original 4235 // declaration. 4236 if (!Cur->Encloses(DC)) { 4237 if (Cur->isRecord()) 4238 Diag(Loc, diag::err_member_qualification) 4239 << Name << SS.getRange(); 4240 else if (isa<TranslationUnitDecl>(DC)) 4241 Diag(Loc, diag::err_invalid_declarator_global_scope) 4242 << Name << SS.getRange(); 4243 else if (isa<FunctionDecl>(Cur)) 4244 Diag(Loc, diag::err_invalid_declarator_in_function) 4245 << Name << SS.getRange(); 4246 else if (isa<BlockDecl>(Cur)) 4247 Diag(Loc, diag::err_invalid_declarator_in_block) 4248 << Name << SS.getRange(); 4249 else 4250 Diag(Loc, diag::err_invalid_declarator_scope) 4251 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4252 4253 return true; 4254 } 4255 4256 if (Cur->isRecord()) { 4257 // Cannot qualify members within a class. 4258 Diag(Loc, diag::err_member_qualification) 4259 << Name << SS.getRange(); 4260 SS.clear(); 4261 4262 // C++ constructors and destructors with incorrect scopes can break 4263 // our AST invariants by having the wrong underlying types. If 4264 // that's the case, then drop this declaration entirely. 4265 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4266 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4267 !Context.hasSameType(Name.getCXXNameType(), 4268 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4269 return true; 4270 4271 return false; 4272 } 4273 4274 // C++11 [dcl.meaning]p1: 4275 // [...] "The nested-name-specifier of the qualified declarator-id shall 4276 // not begin with a decltype-specifer" 4277 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4278 while (SpecLoc.getPrefix()) 4279 SpecLoc = SpecLoc.getPrefix(); 4280 if (dyn_cast_or_null<DecltypeType>( 4281 SpecLoc.getNestedNameSpecifier()->getAsType())) 4282 Diag(Loc, diag::err_decltype_in_declarator) 4283 << SpecLoc.getTypeLoc().getSourceRange(); 4284 4285 return false; 4286 } 4287 4288 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4289 MultiTemplateParamsArg TemplateParamLists) { 4290 // TODO: consider using NameInfo for diagnostic. 4291 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4292 DeclarationName Name = NameInfo.getName(); 4293 4294 // All of these full declarators require an identifier. If it doesn't have 4295 // one, the ParsedFreeStandingDeclSpec action should be used. 4296 if (!Name) { 4297 if (!D.isInvalidType()) // Reject this if we think it is valid. 4298 Diag(D.getDeclSpec().getLocStart(), 4299 diag::err_declarator_need_ident) 4300 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4301 return nullptr; 4302 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4303 return nullptr; 4304 4305 // The scope passed in may not be a decl scope. Zip up the scope tree until 4306 // we find one that is. 4307 while ((S->getFlags() & Scope::DeclScope) == 0 || 4308 (S->getFlags() & Scope::TemplateParamScope) != 0) 4309 S = S->getParent(); 4310 4311 DeclContext *DC = CurContext; 4312 if (D.getCXXScopeSpec().isInvalid()) 4313 D.setInvalidType(); 4314 else if (D.getCXXScopeSpec().isSet()) { 4315 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4316 UPPC_DeclarationQualifier)) 4317 return nullptr; 4318 4319 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4320 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4321 if (!DC || isa<EnumDecl>(DC)) { 4322 // If we could not compute the declaration context, it's because the 4323 // declaration context is dependent but does not refer to a class, 4324 // class template, or class template partial specialization. Complain 4325 // and return early, to avoid the coming semantic disaster. 4326 Diag(D.getIdentifierLoc(), 4327 diag::err_template_qualified_declarator_no_match) 4328 << D.getCXXScopeSpec().getScopeRep() 4329 << D.getCXXScopeSpec().getRange(); 4330 return nullptr; 4331 } 4332 bool IsDependentContext = DC->isDependentContext(); 4333 4334 if (!IsDependentContext && 4335 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4336 return nullptr; 4337 4338 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4339 Diag(D.getIdentifierLoc(), 4340 diag::err_member_def_undefined_record) 4341 << Name << DC << D.getCXXScopeSpec().getRange(); 4342 D.setInvalidType(); 4343 } else if (!D.getDeclSpec().isFriendSpecified()) { 4344 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4345 Name, D.getIdentifierLoc())) { 4346 if (DC->isRecord()) 4347 return nullptr; 4348 4349 D.setInvalidType(); 4350 } 4351 } 4352 4353 // Check whether we need to rebuild the type of the given 4354 // declaration in the current instantiation. 4355 if (EnteringContext && IsDependentContext && 4356 TemplateParamLists.size() != 0) { 4357 ContextRAII SavedContext(*this, DC); 4358 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4359 D.setInvalidType(); 4360 } 4361 } 4362 4363 if (DiagnoseClassNameShadow(DC, NameInfo)) 4364 // If this is a typedef, we'll end up spewing multiple diagnostics. 4365 // Just return early; it's safer. 4366 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4367 return nullptr; 4368 4369 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4370 QualType R = TInfo->getType(); 4371 4372 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4373 UPPC_DeclarationType)) 4374 D.setInvalidType(); 4375 4376 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4377 ForRedeclaration); 4378 4379 // See if this is a redefinition of a variable in the same scope. 4380 if (!D.getCXXScopeSpec().isSet()) { 4381 bool IsLinkageLookup = false; 4382 bool CreateBuiltins = false; 4383 4384 // If the declaration we're planning to build will be a function 4385 // or object with linkage, then look for another declaration with 4386 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4387 // 4388 // If the declaration we're planning to build will be declared with 4389 // external linkage in the translation unit, create any builtin with 4390 // the same name. 4391 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4392 /* Do nothing*/; 4393 else if (CurContext->isFunctionOrMethod() && 4394 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4395 R->isFunctionType())) { 4396 IsLinkageLookup = true; 4397 CreateBuiltins = 4398 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4399 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4400 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4401 CreateBuiltins = true; 4402 4403 if (IsLinkageLookup) 4404 Previous.clear(LookupRedeclarationWithLinkage); 4405 4406 LookupName(Previous, S, CreateBuiltins); 4407 } else { // Something like "int foo::x;" 4408 LookupQualifiedName(Previous, DC); 4409 4410 // C++ [dcl.meaning]p1: 4411 // When the declarator-id is qualified, the declaration shall refer to a 4412 // previously declared member of the class or namespace to which the 4413 // qualifier refers (or, in the case of a namespace, of an element of the 4414 // inline namespace set of that namespace (7.3.1)) or to a specialization 4415 // thereof; [...] 4416 // 4417 // Note that we already checked the context above, and that we do not have 4418 // enough information to make sure that Previous contains the declaration 4419 // we want to match. For example, given: 4420 // 4421 // class X { 4422 // void f(); 4423 // void f(float); 4424 // }; 4425 // 4426 // void X::f(int) { } // ill-formed 4427 // 4428 // In this case, Previous will point to the overload set 4429 // containing the two f's declared in X, but neither of them 4430 // matches. 4431 4432 // C++ [dcl.meaning]p1: 4433 // [...] the member shall not merely have been introduced by a 4434 // using-declaration in the scope of the class or namespace nominated by 4435 // the nested-name-specifier of the declarator-id. 4436 RemoveUsingDecls(Previous); 4437 } 4438 4439 if (Previous.isSingleResult() && 4440 Previous.getFoundDecl()->isTemplateParameter()) { 4441 // Maybe we will complain about the shadowed template parameter. 4442 if (!D.isInvalidType()) 4443 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4444 Previous.getFoundDecl()); 4445 4446 // Just pretend that we didn't see the previous declaration. 4447 Previous.clear(); 4448 } 4449 4450 // In C++, the previous declaration we find might be a tag type 4451 // (class or enum). In this case, the new declaration will hide the 4452 // tag type. Note that this does does not apply if we're declaring a 4453 // typedef (C++ [dcl.typedef]p4). 4454 if (Previous.isSingleTagDecl() && 4455 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4456 Previous.clear(); 4457 4458 // Check that there are no default arguments other than in the parameters 4459 // of a function declaration (C++ only). 4460 if (getLangOpts().CPlusPlus) 4461 CheckExtraCXXDefaultArguments(D); 4462 4463 NamedDecl *New; 4464 4465 bool AddToScope = true; 4466 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4467 if (TemplateParamLists.size()) { 4468 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4469 return nullptr; 4470 } 4471 4472 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4473 } else if (R->isFunctionType()) { 4474 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4475 TemplateParamLists, 4476 AddToScope); 4477 } else { 4478 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4479 AddToScope); 4480 } 4481 4482 if (!New) 4483 return nullptr; 4484 4485 // If this has an identifier and is not an invalid redeclaration or 4486 // function template specialization, add it to the scope stack. 4487 if (New->getDeclName() && AddToScope && 4488 !(D.isRedeclaration() && New->isInvalidDecl())) { 4489 // Only make a locally-scoped extern declaration visible if it is the first 4490 // declaration of this entity. Qualified lookup for such an entity should 4491 // only find this declaration if there is no visible declaration of it. 4492 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4493 PushOnScopeChains(New, S, AddToContext); 4494 if (!AddToContext) 4495 CurContext->addHiddenDecl(New); 4496 } 4497 4498 return New; 4499 } 4500 4501 /// Helper method to turn variable array types into constant array 4502 /// types in certain situations which would otherwise be errors (for 4503 /// GCC compatibility). 4504 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4505 ASTContext &Context, 4506 bool &SizeIsNegative, 4507 llvm::APSInt &Oversized) { 4508 // This method tries to turn a variable array into a constant 4509 // array even when the size isn't an ICE. This is necessary 4510 // for compatibility with code that depends on gcc's buggy 4511 // constant expression folding, like struct {char x[(int)(char*)2];} 4512 SizeIsNegative = false; 4513 Oversized = 0; 4514 4515 if (T->isDependentType()) 4516 return QualType(); 4517 4518 QualifierCollector Qs; 4519 const Type *Ty = Qs.strip(T); 4520 4521 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4522 QualType Pointee = PTy->getPointeeType(); 4523 QualType FixedType = 4524 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4525 Oversized); 4526 if (FixedType.isNull()) return FixedType; 4527 FixedType = Context.getPointerType(FixedType); 4528 return Qs.apply(Context, FixedType); 4529 } 4530 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4531 QualType Inner = PTy->getInnerType(); 4532 QualType FixedType = 4533 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4534 Oversized); 4535 if (FixedType.isNull()) return FixedType; 4536 FixedType = Context.getParenType(FixedType); 4537 return Qs.apply(Context, FixedType); 4538 } 4539 4540 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4541 if (!VLATy) 4542 return QualType(); 4543 // FIXME: We should probably handle this case 4544 if (VLATy->getElementType()->isVariablyModifiedType()) 4545 return QualType(); 4546 4547 llvm::APSInt Res; 4548 if (!VLATy->getSizeExpr() || 4549 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4550 return QualType(); 4551 4552 // Check whether the array size is negative. 4553 if (Res.isSigned() && Res.isNegative()) { 4554 SizeIsNegative = true; 4555 return QualType(); 4556 } 4557 4558 // Check whether the array is too large to be addressed. 4559 unsigned ActiveSizeBits 4560 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4561 Res); 4562 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4563 Oversized = Res; 4564 return QualType(); 4565 } 4566 4567 return Context.getConstantArrayType(VLATy->getElementType(), 4568 Res, ArrayType::Normal, 0); 4569 } 4570 4571 static void 4572 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4573 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4574 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4575 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4576 DstPTL.getPointeeLoc()); 4577 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4578 return; 4579 } 4580 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4581 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4582 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4583 DstPTL.getInnerLoc()); 4584 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4585 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4586 return; 4587 } 4588 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4589 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4590 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4591 TypeLoc DstElemTL = DstATL.getElementLoc(); 4592 DstElemTL.initializeFullCopy(SrcElemTL); 4593 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4594 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4595 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4596 } 4597 4598 /// Helper method to turn variable array types into constant array 4599 /// types in certain situations which would otherwise be errors (for 4600 /// GCC compatibility). 4601 static TypeSourceInfo* 4602 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4603 ASTContext &Context, 4604 bool &SizeIsNegative, 4605 llvm::APSInt &Oversized) { 4606 QualType FixedTy 4607 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4608 SizeIsNegative, Oversized); 4609 if (FixedTy.isNull()) 4610 return nullptr; 4611 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4612 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4613 FixedTInfo->getTypeLoc()); 4614 return FixedTInfo; 4615 } 4616 4617 /// \brief Register the given locally-scoped extern "C" declaration so 4618 /// that it can be found later for redeclarations. We include any extern "C" 4619 /// declaration that is not visible in the translation unit here, not just 4620 /// function-scope declarations. 4621 void 4622 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4623 if (!getLangOpts().CPlusPlus && 4624 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4625 // Don't need to track declarations in the TU in C. 4626 return; 4627 4628 // Note that we have a locally-scoped external with this name. 4629 // FIXME: There can be multiple such declarations if they are functions marked 4630 // __attribute__((overloadable)) declared in function scope in C. 4631 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4632 } 4633 4634 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4635 if (ExternalSource) { 4636 // Load locally-scoped external decls from the external source. 4637 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4638 SmallVector<NamedDecl *, 4> Decls; 4639 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4640 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4641 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4642 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4643 if (Pos == LocallyScopedExternCDecls.end()) 4644 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4645 } 4646 } 4647 4648 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4649 return D ? D->getMostRecentDecl() : nullptr; 4650 } 4651 4652 /// \brief Diagnose function specifiers on a declaration of an identifier that 4653 /// does not identify a function. 4654 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4655 // FIXME: We should probably indicate the identifier in question to avoid 4656 // confusion for constructs like "inline int a(), b;" 4657 if (DS.isInlineSpecified()) 4658 Diag(DS.getInlineSpecLoc(), 4659 diag::err_inline_non_function); 4660 4661 if (DS.isVirtualSpecified()) 4662 Diag(DS.getVirtualSpecLoc(), 4663 diag::err_virtual_non_function); 4664 4665 if (DS.isExplicitSpecified()) 4666 Diag(DS.getExplicitSpecLoc(), 4667 diag::err_explicit_non_function); 4668 4669 if (DS.isNoreturnSpecified()) 4670 Diag(DS.getNoreturnSpecLoc(), 4671 diag::err_noreturn_non_function); 4672 } 4673 4674 NamedDecl* 4675 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4676 TypeSourceInfo *TInfo, LookupResult &Previous) { 4677 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4678 if (D.getCXXScopeSpec().isSet()) { 4679 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4680 << D.getCXXScopeSpec().getRange(); 4681 D.setInvalidType(); 4682 // Pretend we didn't see the scope specifier. 4683 DC = CurContext; 4684 Previous.clear(); 4685 } 4686 4687 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4688 4689 if (D.getDeclSpec().isConstexprSpecified()) 4690 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4691 << 1; 4692 4693 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4694 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4695 << D.getName().getSourceRange(); 4696 return nullptr; 4697 } 4698 4699 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4700 if (!NewTD) return nullptr; 4701 4702 // Handle attributes prior to checking for duplicates in MergeVarDecl 4703 ProcessDeclAttributes(S, NewTD, D); 4704 4705 CheckTypedefForVariablyModifiedType(S, NewTD); 4706 4707 bool Redeclaration = D.isRedeclaration(); 4708 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4709 D.setRedeclaration(Redeclaration); 4710 return ND; 4711 } 4712 4713 void 4714 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4715 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4716 // then it shall have block scope. 4717 // Note that variably modified types must be fixed before merging the decl so 4718 // that redeclarations will match. 4719 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4720 QualType T = TInfo->getType(); 4721 if (T->isVariablyModifiedType()) { 4722 getCurFunction()->setHasBranchProtectedScope(); 4723 4724 if (S->getFnParent() == nullptr) { 4725 bool SizeIsNegative; 4726 llvm::APSInt Oversized; 4727 TypeSourceInfo *FixedTInfo = 4728 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4729 SizeIsNegative, 4730 Oversized); 4731 if (FixedTInfo) { 4732 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4733 NewTD->setTypeSourceInfo(FixedTInfo); 4734 } else { 4735 if (SizeIsNegative) 4736 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4737 else if (T->isVariableArrayType()) 4738 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4739 else if (Oversized.getBoolValue()) 4740 Diag(NewTD->getLocation(), diag::err_array_too_large) 4741 << Oversized.toString(10); 4742 else 4743 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4744 NewTD->setInvalidDecl(); 4745 } 4746 } 4747 } 4748 } 4749 4750 4751 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4752 /// declares a typedef-name, either using the 'typedef' type specifier or via 4753 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4754 NamedDecl* 4755 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4756 LookupResult &Previous, bool &Redeclaration) { 4757 // Merge the decl with the existing one if appropriate. If the decl is 4758 // in an outer scope, it isn't the same thing. 4759 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4760 /*AllowInlineNamespace*/false); 4761 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4762 if (!Previous.empty()) { 4763 Redeclaration = true; 4764 MergeTypedefNameDecl(NewTD, Previous); 4765 } 4766 4767 // If this is the C FILE type, notify the AST context. 4768 if (IdentifierInfo *II = NewTD->getIdentifier()) 4769 if (!NewTD->isInvalidDecl() && 4770 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4771 if (II->isStr("FILE")) 4772 Context.setFILEDecl(NewTD); 4773 else if (II->isStr("jmp_buf")) 4774 Context.setjmp_bufDecl(NewTD); 4775 else if (II->isStr("sigjmp_buf")) 4776 Context.setsigjmp_bufDecl(NewTD); 4777 else if (II->isStr("ucontext_t")) 4778 Context.setucontext_tDecl(NewTD); 4779 } 4780 4781 return NewTD; 4782 } 4783 4784 /// \brief Determines whether the given declaration is an out-of-scope 4785 /// previous declaration. 4786 /// 4787 /// This routine should be invoked when name lookup has found a 4788 /// previous declaration (PrevDecl) that is not in the scope where a 4789 /// new declaration by the same name is being introduced. If the new 4790 /// declaration occurs in a local scope, previous declarations with 4791 /// linkage may still be considered previous declarations (C99 4792 /// 6.2.2p4-5, C++ [basic.link]p6). 4793 /// 4794 /// \param PrevDecl the previous declaration found by name 4795 /// lookup 4796 /// 4797 /// \param DC the context in which the new declaration is being 4798 /// declared. 4799 /// 4800 /// \returns true if PrevDecl is an out-of-scope previous declaration 4801 /// for a new delcaration with the same name. 4802 static bool 4803 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4804 ASTContext &Context) { 4805 if (!PrevDecl) 4806 return false; 4807 4808 if (!PrevDecl->hasLinkage()) 4809 return false; 4810 4811 if (Context.getLangOpts().CPlusPlus) { 4812 // C++ [basic.link]p6: 4813 // If there is a visible declaration of an entity with linkage 4814 // having the same name and type, ignoring entities declared 4815 // outside the innermost enclosing namespace scope, the block 4816 // scope declaration declares that same entity and receives the 4817 // linkage of the previous declaration. 4818 DeclContext *OuterContext = DC->getRedeclContext(); 4819 if (!OuterContext->isFunctionOrMethod()) 4820 // This rule only applies to block-scope declarations. 4821 return false; 4822 4823 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4824 if (PrevOuterContext->isRecord()) 4825 // We found a member function: ignore it. 4826 return false; 4827 4828 // Find the innermost enclosing namespace for the new and 4829 // previous declarations. 4830 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4831 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4832 4833 // The previous declaration is in a different namespace, so it 4834 // isn't the same function. 4835 if (!OuterContext->Equals(PrevOuterContext)) 4836 return false; 4837 } 4838 4839 return true; 4840 } 4841 4842 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4843 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4844 if (!SS.isSet()) return; 4845 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4846 } 4847 4848 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4849 QualType type = decl->getType(); 4850 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4851 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4852 // Various kinds of declaration aren't allowed to be __autoreleasing. 4853 unsigned kind = -1U; 4854 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4855 if (var->hasAttr<BlocksAttr>()) 4856 kind = 0; // __block 4857 else if (!var->hasLocalStorage()) 4858 kind = 1; // global 4859 } else if (isa<ObjCIvarDecl>(decl)) { 4860 kind = 3; // ivar 4861 } else if (isa<FieldDecl>(decl)) { 4862 kind = 2; // field 4863 } 4864 4865 if (kind != -1U) { 4866 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4867 << kind; 4868 } 4869 } else if (lifetime == Qualifiers::OCL_None) { 4870 // Try to infer lifetime. 4871 if (!type->isObjCLifetimeType()) 4872 return false; 4873 4874 lifetime = type->getObjCARCImplicitLifetime(); 4875 type = Context.getLifetimeQualifiedType(type, lifetime); 4876 decl->setType(type); 4877 } 4878 4879 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4880 // Thread-local variables cannot have lifetime. 4881 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4882 var->getTLSKind()) { 4883 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4884 << var->getType(); 4885 return true; 4886 } 4887 } 4888 4889 return false; 4890 } 4891 4892 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4893 // Ensure that an auto decl is deduced otherwise the checks below might cache 4894 // the wrong linkage. 4895 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4896 4897 // 'weak' only applies to declarations with external linkage. 4898 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4899 if (!ND.isExternallyVisible()) { 4900 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4901 ND.dropAttr<WeakAttr>(); 4902 } 4903 } 4904 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4905 if (ND.isExternallyVisible()) { 4906 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4907 ND.dropAttr<WeakRefAttr>(); 4908 } 4909 } 4910 4911 // 'selectany' only applies to externally visible varable declarations. 4912 // It does not apply to functions. 4913 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4914 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4915 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4916 ND.dropAttr<SelectAnyAttr>(); 4917 } 4918 } 4919 4920 // dll attributes require external linkage. 4921 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 4922 if (!ND.isExternallyVisible()) { 4923 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4924 << &ND << Attr; 4925 ND.setInvalidDecl(); 4926 } 4927 } 4928 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 4929 if (!ND.isExternallyVisible()) { 4930 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4931 << &ND << Attr; 4932 ND.setInvalidDecl(); 4933 } 4934 } 4935 } 4936 4937 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 4938 NamedDecl *NewDecl, 4939 bool IsSpecialization) { 4940 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 4941 OldDecl = OldTD->getTemplatedDecl(); 4942 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 4943 NewDecl = NewTD->getTemplatedDecl(); 4944 4945 if (!OldDecl || !NewDecl) 4946 return; 4947 4948 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 4949 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 4950 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 4951 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 4952 4953 // dllimport and dllexport are inheritable attributes so we have to exclude 4954 // inherited attribute instances. 4955 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 4956 (NewExportAttr && !NewExportAttr->isInherited()); 4957 4958 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 4959 // the only exception being explicit specializations. 4960 // Implicitly generated declarations are also excluded for now because there 4961 // is no other way to switch these to use dllimport or dllexport. 4962 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 4963 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 4964 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration) 4965 << NewDecl 4966 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 4967 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4968 NewDecl->setInvalidDecl(); 4969 return; 4970 } 4971 4972 // A redeclaration is not allowed to drop a dllimport attribute, the only 4973 // exception being inline function definitions. 4974 // NB: MSVC converts such a declaration to dllexport. 4975 bool IsInline = false, IsStaticDataMember = false; 4976 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 4977 // Ignore static data because out-of-line definitions are diagnosed 4978 // separately. 4979 IsStaticDataMember = VD->isStaticDataMember(); 4980 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) 4981 IsInline = FD->isInlined(); 4982 4983 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember) { 4984 S.Diag(NewDecl->getLocation(), 4985 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4986 << NewDecl << OldImportAttr; 4987 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4988 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 4989 OldDecl->dropAttr<DLLImportAttr>(); 4990 NewDecl->dropAttr<DLLImportAttr>(); 4991 } 4992 } 4993 4994 /// Given that we are within the definition of the given function, 4995 /// will that definition behave like C99's 'inline', where the 4996 /// definition is discarded except for optimization purposes? 4997 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4998 // Try to avoid calling GetGVALinkageForFunction. 4999 5000 // All cases of this require the 'inline' keyword. 5001 if (!FD->isInlined()) return false; 5002 5003 // This is only possible in C++ with the gnu_inline attribute. 5004 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5005 return false; 5006 5007 // Okay, go ahead and call the relatively-more-expensive function. 5008 5009 #ifndef NDEBUG 5010 // AST quite reasonably asserts that it's working on a function 5011 // definition. We don't really have a way to tell it that we're 5012 // currently defining the function, so just lie to it in +Asserts 5013 // builds. This is an awful hack. 5014 FD->setLazyBody(1); 5015 #endif 5016 5017 bool isC99Inline = 5018 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5019 5020 #ifndef NDEBUG 5021 FD->setLazyBody(0); 5022 #endif 5023 5024 return isC99Inline; 5025 } 5026 5027 /// Determine whether a variable is extern "C" prior to attaching 5028 /// an initializer. We can't just call isExternC() here, because that 5029 /// will also compute and cache whether the declaration is externally 5030 /// visible, which might change when we attach the initializer. 5031 /// 5032 /// This can only be used if the declaration is known to not be a 5033 /// redeclaration of an internal linkage declaration. 5034 /// 5035 /// For instance: 5036 /// 5037 /// auto x = []{}; 5038 /// 5039 /// Attaching the initializer here makes this declaration not externally 5040 /// visible, because its type has internal linkage. 5041 /// 5042 /// FIXME: This is a hack. 5043 template<typename T> 5044 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5045 if (S.getLangOpts().CPlusPlus) { 5046 // In C++, the overloadable attribute negates the effects of extern "C". 5047 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5048 return false; 5049 } 5050 return D->isExternC(); 5051 } 5052 5053 static bool shouldConsiderLinkage(const VarDecl *VD) { 5054 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5055 if (DC->isFunctionOrMethod()) 5056 return VD->hasExternalStorage(); 5057 if (DC->isFileContext()) 5058 return true; 5059 if (DC->isRecord()) 5060 return false; 5061 llvm_unreachable("Unexpected context"); 5062 } 5063 5064 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5065 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5066 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5067 return true; 5068 if (DC->isRecord()) 5069 return false; 5070 llvm_unreachable("Unexpected context"); 5071 } 5072 5073 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5074 AttributeList::Kind Kind) { 5075 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5076 if (L->getKind() == Kind) 5077 return true; 5078 return false; 5079 } 5080 5081 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5082 AttributeList::Kind Kind) { 5083 // Check decl attributes on the DeclSpec. 5084 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5085 return true; 5086 5087 // Walk the declarator structure, checking decl attributes that were in a type 5088 // position to the decl itself. 5089 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5090 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5091 return true; 5092 } 5093 5094 // Finally, check attributes on the decl itself. 5095 return hasParsedAttr(S, PD.getAttributes(), Kind); 5096 } 5097 5098 /// Adjust the \c DeclContext for a function or variable that might be a 5099 /// function-local external declaration. 5100 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5101 if (!DC->isFunctionOrMethod()) 5102 return false; 5103 5104 // If this is a local extern function or variable declared within a function 5105 // template, don't add it into the enclosing namespace scope until it is 5106 // instantiated; it might have a dependent type right now. 5107 if (DC->isDependentContext()) 5108 return true; 5109 5110 // C++11 [basic.link]p7: 5111 // When a block scope declaration of an entity with linkage is not found to 5112 // refer to some other declaration, then that entity is a member of the 5113 // innermost enclosing namespace. 5114 // 5115 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5116 // semantically-enclosing namespace, not a lexically-enclosing one. 5117 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5118 DC = DC->getParent(); 5119 return true; 5120 } 5121 5122 NamedDecl * 5123 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5124 TypeSourceInfo *TInfo, LookupResult &Previous, 5125 MultiTemplateParamsArg TemplateParamLists, 5126 bool &AddToScope) { 5127 QualType R = TInfo->getType(); 5128 DeclarationName Name = GetNameForDeclarator(D).getName(); 5129 5130 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5131 VarDecl::StorageClass SC = 5132 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5133 5134 // dllimport globals without explicit storage class are treated as extern. We 5135 // have to change the storage class this early to get the right DeclContext. 5136 if (SC == SC_None && !DC->isRecord() && 5137 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5138 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5139 SC = SC_Extern; 5140 5141 DeclContext *OriginalDC = DC; 5142 bool IsLocalExternDecl = SC == SC_Extern && 5143 adjustContextForLocalExternDecl(DC); 5144 5145 if (getLangOpts().OpenCL) { 5146 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5147 QualType NR = R; 5148 while (NR->isPointerType()) { 5149 if (NR->isFunctionPointerType()) { 5150 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5151 D.setInvalidType(); 5152 break; 5153 } 5154 NR = NR->getPointeeType(); 5155 } 5156 5157 if (!getOpenCLOptions().cl_khr_fp16) { 5158 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5159 // half array type (unless the cl_khr_fp16 extension is enabled). 5160 if (Context.getBaseElementType(R)->isHalfType()) { 5161 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5162 D.setInvalidType(); 5163 } 5164 } 5165 } 5166 5167 if (SCSpec == DeclSpec::SCS_mutable) { 5168 // mutable can only appear on non-static class members, so it's always 5169 // an error here 5170 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5171 D.setInvalidType(); 5172 SC = SC_None; 5173 } 5174 5175 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5176 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5177 D.getDeclSpec().getStorageClassSpecLoc())) { 5178 // In C++11, the 'register' storage class specifier is deprecated. 5179 // Suppress the warning in system macros, it's used in macros in some 5180 // popular C system headers, such as in glibc's htonl() macro. 5181 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5182 diag::warn_deprecated_register) 5183 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5184 } 5185 5186 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5187 if (!II) { 5188 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5189 << Name; 5190 return nullptr; 5191 } 5192 5193 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5194 5195 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5196 // C99 6.9p2: The storage-class specifiers auto and register shall not 5197 // appear in the declaration specifiers in an external declaration. 5198 // Global Register+Asm is a GNU extension we support. 5199 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5200 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5201 D.setInvalidType(); 5202 } 5203 } 5204 5205 if (getLangOpts().OpenCL) { 5206 // Set up the special work-group-local storage class for variables in the 5207 // OpenCL __local address space. 5208 if (R.getAddressSpace() == LangAS::opencl_local) { 5209 SC = SC_OpenCLWorkGroupLocal; 5210 } 5211 5212 // OpenCL v1.2 s6.9.b p4: 5213 // The sampler type cannot be used with the __local and __global address 5214 // space qualifiers. 5215 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5216 R.getAddressSpace() == LangAS::opencl_global)) { 5217 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5218 } 5219 5220 // OpenCL 1.2 spec, p6.9 r: 5221 // The event type cannot be used to declare a program scope variable. 5222 // The event type cannot be used with the __local, __constant and __global 5223 // address space qualifiers. 5224 if (R->isEventT()) { 5225 if (S->getParent() == nullptr) { 5226 Diag(D.getLocStart(), diag::err_event_t_global_var); 5227 D.setInvalidType(); 5228 } 5229 5230 if (R.getAddressSpace()) { 5231 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5232 D.setInvalidType(); 5233 } 5234 } 5235 } 5236 5237 bool IsExplicitSpecialization = false; 5238 bool IsVariableTemplateSpecialization = false; 5239 bool IsPartialSpecialization = false; 5240 bool IsVariableTemplate = false; 5241 VarDecl *NewVD = nullptr; 5242 VarTemplateDecl *NewTemplate = nullptr; 5243 TemplateParameterList *TemplateParams = nullptr; 5244 if (!getLangOpts().CPlusPlus) { 5245 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5246 D.getIdentifierLoc(), II, 5247 R, TInfo, SC); 5248 5249 if (D.isInvalidType()) 5250 NewVD->setInvalidDecl(); 5251 } else { 5252 bool Invalid = false; 5253 5254 if (DC->isRecord() && !CurContext->isRecord()) { 5255 // This is an out-of-line definition of a static data member. 5256 switch (SC) { 5257 case SC_None: 5258 break; 5259 case SC_Static: 5260 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5261 diag::err_static_out_of_line) 5262 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5263 break; 5264 case SC_Auto: 5265 case SC_Register: 5266 case SC_Extern: 5267 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5268 // to names of variables declared in a block or to function parameters. 5269 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5270 // of class members 5271 5272 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5273 diag::err_storage_class_for_static_member) 5274 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5275 break; 5276 case SC_PrivateExtern: 5277 llvm_unreachable("C storage class in c++!"); 5278 case SC_OpenCLWorkGroupLocal: 5279 llvm_unreachable("OpenCL storage class in c++!"); 5280 } 5281 } 5282 5283 if (SC == SC_Static && CurContext->isRecord()) { 5284 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5285 if (RD->isLocalClass()) 5286 Diag(D.getIdentifierLoc(), 5287 diag::err_static_data_member_not_allowed_in_local_class) 5288 << Name << RD->getDeclName(); 5289 5290 // C++98 [class.union]p1: If a union contains a static data member, 5291 // the program is ill-formed. C++11 drops this restriction. 5292 if (RD->isUnion()) 5293 Diag(D.getIdentifierLoc(), 5294 getLangOpts().CPlusPlus11 5295 ? diag::warn_cxx98_compat_static_data_member_in_union 5296 : diag::ext_static_data_member_in_union) << Name; 5297 // We conservatively disallow static data members in anonymous structs. 5298 else if (!RD->getDeclName()) 5299 Diag(D.getIdentifierLoc(), 5300 diag::err_static_data_member_not_allowed_in_anon_struct) 5301 << Name << RD->isUnion(); 5302 } 5303 } 5304 5305 // Match up the template parameter lists with the scope specifier, then 5306 // determine whether we have a template or a template specialization. 5307 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5308 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5309 D.getCXXScopeSpec(), 5310 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5311 ? D.getName().TemplateId 5312 : nullptr, 5313 TemplateParamLists, 5314 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5315 5316 if (TemplateParams) { 5317 if (!TemplateParams->size() && 5318 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5319 // There is an extraneous 'template<>' for this variable. Complain 5320 // about it, but allow the declaration of the variable. 5321 Diag(TemplateParams->getTemplateLoc(), 5322 diag::err_template_variable_noparams) 5323 << II 5324 << SourceRange(TemplateParams->getTemplateLoc(), 5325 TemplateParams->getRAngleLoc()); 5326 TemplateParams = nullptr; 5327 } else { 5328 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5329 // This is an explicit specialization or a partial specialization. 5330 // FIXME: Check that we can declare a specialization here. 5331 IsVariableTemplateSpecialization = true; 5332 IsPartialSpecialization = TemplateParams->size() > 0; 5333 } else { // if (TemplateParams->size() > 0) 5334 // This is a template declaration. 5335 IsVariableTemplate = true; 5336 5337 // Check that we can declare a template here. 5338 if (CheckTemplateDeclScope(S, TemplateParams)) 5339 return nullptr; 5340 5341 // Only C++1y supports variable templates (N3651). 5342 Diag(D.getIdentifierLoc(), 5343 getLangOpts().CPlusPlus1y 5344 ? diag::warn_cxx11_compat_variable_template 5345 : diag::ext_variable_template); 5346 } 5347 } 5348 } else { 5349 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5350 "should have a 'template<>' for this decl"); 5351 } 5352 5353 if (IsVariableTemplateSpecialization) { 5354 SourceLocation TemplateKWLoc = 5355 TemplateParamLists.size() > 0 5356 ? TemplateParamLists[0]->getTemplateLoc() 5357 : SourceLocation(); 5358 DeclResult Res = ActOnVarTemplateSpecialization( 5359 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5360 IsPartialSpecialization); 5361 if (Res.isInvalid()) 5362 return nullptr; 5363 NewVD = cast<VarDecl>(Res.get()); 5364 AddToScope = false; 5365 } else 5366 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5367 D.getIdentifierLoc(), II, R, TInfo, SC); 5368 5369 // If this is supposed to be a variable template, create it as such. 5370 if (IsVariableTemplate) { 5371 NewTemplate = 5372 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5373 TemplateParams, NewVD); 5374 NewVD->setDescribedVarTemplate(NewTemplate); 5375 } 5376 5377 // If this decl has an auto type in need of deduction, make a note of the 5378 // Decl so we can diagnose uses of it in its own initializer. 5379 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5380 ParsingInitForAutoVars.insert(NewVD); 5381 5382 if (D.isInvalidType() || Invalid) { 5383 NewVD->setInvalidDecl(); 5384 if (NewTemplate) 5385 NewTemplate->setInvalidDecl(); 5386 } 5387 5388 SetNestedNameSpecifier(NewVD, D); 5389 5390 // If we have any template parameter lists that don't directly belong to 5391 // the variable (matching the scope specifier), store them. 5392 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5393 if (TemplateParamLists.size() > VDTemplateParamLists) 5394 NewVD->setTemplateParameterListsInfo( 5395 Context, TemplateParamLists.size() - VDTemplateParamLists, 5396 TemplateParamLists.data()); 5397 5398 if (D.getDeclSpec().isConstexprSpecified()) 5399 NewVD->setConstexpr(true); 5400 } 5401 5402 // Set the lexical context. If the declarator has a C++ scope specifier, the 5403 // lexical context will be different from the semantic context. 5404 NewVD->setLexicalDeclContext(CurContext); 5405 if (NewTemplate) 5406 NewTemplate->setLexicalDeclContext(CurContext); 5407 5408 if (IsLocalExternDecl) 5409 NewVD->setLocalExternDecl(); 5410 5411 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5412 if (NewVD->hasLocalStorage()) { 5413 // C++11 [dcl.stc]p4: 5414 // When thread_local is applied to a variable of block scope the 5415 // storage-class-specifier static is implied if it does not appear 5416 // explicitly. 5417 // Core issue: 'static' is not implied if the variable is declared 5418 // 'extern'. 5419 if (SCSpec == DeclSpec::SCS_unspecified && 5420 TSCS == DeclSpec::TSCS_thread_local && 5421 DC->isFunctionOrMethod()) 5422 NewVD->setTSCSpec(TSCS); 5423 else 5424 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5425 diag::err_thread_non_global) 5426 << DeclSpec::getSpecifierName(TSCS); 5427 } else if (!Context.getTargetInfo().isTLSSupported()) 5428 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5429 diag::err_thread_unsupported); 5430 else 5431 NewVD->setTSCSpec(TSCS); 5432 } 5433 5434 // C99 6.7.4p3 5435 // An inline definition of a function with external linkage shall 5436 // not contain a definition of a modifiable object with static or 5437 // thread storage duration... 5438 // We only apply this when the function is required to be defined 5439 // elsewhere, i.e. when the function is not 'extern inline'. Note 5440 // that a local variable with thread storage duration still has to 5441 // be marked 'static'. Also note that it's possible to get these 5442 // semantics in C++ using __attribute__((gnu_inline)). 5443 if (SC == SC_Static && S->getFnParent() != nullptr && 5444 !NewVD->getType().isConstQualified()) { 5445 FunctionDecl *CurFD = getCurFunctionDecl(); 5446 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5447 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5448 diag::warn_static_local_in_extern_inline); 5449 MaybeSuggestAddingStaticToDecl(CurFD); 5450 } 5451 } 5452 5453 if (D.getDeclSpec().isModulePrivateSpecified()) { 5454 if (IsVariableTemplateSpecialization) 5455 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5456 << (IsPartialSpecialization ? 1 : 0) 5457 << FixItHint::CreateRemoval( 5458 D.getDeclSpec().getModulePrivateSpecLoc()); 5459 else if (IsExplicitSpecialization) 5460 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5461 << 2 5462 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5463 else if (NewVD->hasLocalStorage()) 5464 Diag(NewVD->getLocation(), diag::err_module_private_local) 5465 << 0 << NewVD->getDeclName() 5466 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5467 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5468 else { 5469 NewVD->setModulePrivate(); 5470 if (NewTemplate) 5471 NewTemplate->setModulePrivate(); 5472 } 5473 } 5474 5475 // Handle attributes prior to checking for duplicates in MergeVarDecl 5476 ProcessDeclAttributes(S, NewVD, D); 5477 5478 if (getLangOpts().CUDA) { 5479 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5480 // storage [duration]." 5481 if (SC == SC_None && S->getFnParent() != nullptr && 5482 (NewVD->hasAttr<CUDASharedAttr>() || 5483 NewVD->hasAttr<CUDAConstantAttr>())) { 5484 NewVD->setStorageClass(SC_Static); 5485 } 5486 } 5487 5488 // Ensure that dllimport globals without explicit storage class are treated as 5489 // extern. The storage class is set above using parsed attributes. Now we can 5490 // check the VarDecl itself. 5491 assert(!NewVD->hasAttr<DLLImportAttr>() || 5492 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5493 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5494 5495 // In auto-retain/release, infer strong retension for variables of 5496 // retainable type. 5497 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5498 NewVD->setInvalidDecl(); 5499 5500 // Handle GNU asm-label extension (encoded as an attribute). 5501 if (Expr *E = (Expr*)D.getAsmLabel()) { 5502 // The parser guarantees this is a string. 5503 StringLiteral *SE = cast<StringLiteral>(E); 5504 StringRef Label = SE->getString(); 5505 if (S->getFnParent() != nullptr) { 5506 switch (SC) { 5507 case SC_None: 5508 case SC_Auto: 5509 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5510 break; 5511 case SC_Register: 5512 // Local Named register 5513 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5514 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5515 break; 5516 case SC_Static: 5517 case SC_Extern: 5518 case SC_PrivateExtern: 5519 case SC_OpenCLWorkGroupLocal: 5520 break; 5521 } 5522 } else if (SC == SC_Register) { 5523 // Global Named register 5524 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5525 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5526 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5527 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5528 NewVD->setInvalidDecl(true); 5529 } 5530 } 5531 5532 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5533 Context, Label, 0)); 5534 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5535 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5536 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5537 if (I != ExtnameUndeclaredIdentifiers.end()) { 5538 NewVD->addAttr(I->second); 5539 ExtnameUndeclaredIdentifiers.erase(I); 5540 } 5541 } 5542 5543 // Diagnose shadowed variables before filtering for scope. 5544 if (D.getCXXScopeSpec().isEmpty()) 5545 CheckShadow(S, NewVD, Previous); 5546 5547 // Don't consider existing declarations that are in a different 5548 // scope and are out-of-semantic-context declarations (if the new 5549 // declaration has linkage). 5550 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5551 D.getCXXScopeSpec().isNotEmpty() || 5552 IsExplicitSpecialization || 5553 IsVariableTemplateSpecialization); 5554 5555 // Check whether the previous declaration is in the same block scope. This 5556 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5557 if (getLangOpts().CPlusPlus && 5558 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5559 NewVD->setPreviousDeclInSameBlockScope( 5560 Previous.isSingleResult() && !Previous.isShadowed() && 5561 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5562 5563 if (!getLangOpts().CPlusPlus) { 5564 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5565 } else { 5566 // If this is an explicit specialization of a static data member, check it. 5567 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5568 CheckMemberSpecialization(NewVD, Previous)) 5569 NewVD->setInvalidDecl(); 5570 5571 // Merge the decl with the existing one if appropriate. 5572 if (!Previous.empty()) { 5573 if (Previous.isSingleResult() && 5574 isa<FieldDecl>(Previous.getFoundDecl()) && 5575 D.getCXXScopeSpec().isSet()) { 5576 // The user tried to define a non-static data member 5577 // out-of-line (C++ [dcl.meaning]p1). 5578 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5579 << D.getCXXScopeSpec().getRange(); 5580 Previous.clear(); 5581 NewVD->setInvalidDecl(); 5582 } 5583 } else if (D.getCXXScopeSpec().isSet()) { 5584 // No previous declaration in the qualifying scope. 5585 Diag(D.getIdentifierLoc(), diag::err_no_member) 5586 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5587 << D.getCXXScopeSpec().getRange(); 5588 NewVD->setInvalidDecl(); 5589 } 5590 5591 if (!IsVariableTemplateSpecialization) 5592 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5593 5594 if (NewTemplate) { 5595 VarTemplateDecl *PrevVarTemplate = 5596 NewVD->getPreviousDecl() 5597 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5598 : nullptr; 5599 5600 // Check the template parameter list of this declaration, possibly 5601 // merging in the template parameter list from the previous variable 5602 // template declaration. 5603 if (CheckTemplateParameterList( 5604 TemplateParams, 5605 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5606 : nullptr, 5607 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5608 DC->isDependentContext()) 5609 ? TPC_ClassTemplateMember 5610 : TPC_VarTemplate)) 5611 NewVD->setInvalidDecl(); 5612 5613 // If we are providing an explicit specialization of a static variable 5614 // template, make a note of that. 5615 if (PrevVarTemplate && 5616 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5617 PrevVarTemplate->setMemberSpecialization(); 5618 } 5619 } 5620 5621 ProcessPragmaWeak(S, NewVD); 5622 5623 // If this is the first declaration of an extern C variable, update 5624 // the map of such variables. 5625 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5626 isIncompleteDeclExternC(*this, NewVD)) 5627 RegisterLocallyScopedExternCDecl(NewVD, S); 5628 5629 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5630 Decl *ManglingContextDecl; 5631 if (MangleNumberingContext *MCtx = 5632 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5633 ManglingContextDecl)) { 5634 Context.setManglingNumber( 5635 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5636 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5637 } 5638 } 5639 5640 if (D.isRedeclaration() && !Previous.empty()) { 5641 checkDLLAttributeRedeclaration( 5642 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5643 IsExplicitSpecialization); 5644 } 5645 5646 if (NewTemplate) { 5647 if (NewVD->isInvalidDecl()) 5648 NewTemplate->setInvalidDecl(); 5649 ActOnDocumentableDecl(NewTemplate); 5650 return NewTemplate; 5651 } 5652 5653 return NewVD; 5654 } 5655 5656 /// \brief Diagnose variable or built-in function shadowing. Implements 5657 /// -Wshadow. 5658 /// 5659 /// This method is called whenever a VarDecl is added to a "useful" 5660 /// scope. 5661 /// 5662 /// \param S the scope in which the shadowing name is being declared 5663 /// \param R the lookup of the name 5664 /// 5665 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5666 // Return if warning is ignored. 5667 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5668 return; 5669 5670 // Don't diagnose declarations at file scope. 5671 if (D->hasGlobalStorage()) 5672 return; 5673 5674 DeclContext *NewDC = D->getDeclContext(); 5675 5676 // Only diagnose if we're shadowing an unambiguous field or variable. 5677 if (R.getResultKind() != LookupResult::Found) 5678 return; 5679 5680 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5681 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5682 return; 5683 5684 // Fields are not shadowed by variables in C++ static methods. 5685 if (isa<FieldDecl>(ShadowedDecl)) 5686 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5687 if (MD->isStatic()) 5688 return; 5689 5690 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5691 if (shadowedVar->isExternC()) { 5692 // For shadowing external vars, make sure that we point to the global 5693 // declaration, not a locally scoped extern declaration. 5694 for (auto I : shadowedVar->redecls()) 5695 if (I->isFileVarDecl()) { 5696 ShadowedDecl = I; 5697 break; 5698 } 5699 } 5700 5701 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5702 5703 // Only warn about certain kinds of shadowing for class members. 5704 if (NewDC && NewDC->isRecord()) { 5705 // In particular, don't warn about shadowing non-class members. 5706 if (!OldDC->isRecord()) 5707 return; 5708 5709 // TODO: should we warn about static data members shadowing 5710 // static data members from base classes? 5711 5712 // TODO: don't diagnose for inaccessible shadowed members. 5713 // This is hard to do perfectly because we might friend the 5714 // shadowing context, but that's just a false negative. 5715 } 5716 5717 // Determine what kind of declaration we're shadowing. 5718 unsigned Kind; 5719 if (isa<RecordDecl>(OldDC)) { 5720 if (isa<FieldDecl>(ShadowedDecl)) 5721 Kind = 3; // field 5722 else 5723 Kind = 2; // static data member 5724 } else if (OldDC->isFileContext()) 5725 Kind = 1; // global 5726 else 5727 Kind = 0; // local 5728 5729 DeclarationName Name = R.getLookupName(); 5730 5731 // Emit warning and note. 5732 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5733 return; 5734 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5735 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5736 } 5737 5738 /// \brief Check -Wshadow without the advantage of a previous lookup. 5739 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5740 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 5741 return; 5742 5743 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5744 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5745 LookupName(R, S); 5746 CheckShadow(S, D, R); 5747 } 5748 5749 /// Check for conflict between this global or extern "C" declaration and 5750 /// previous global or extern "C" declarations. This is only used in C++. 5751 template<typename T> 5752 static bool checkGlobalOrExternCConflict( 5753 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5754 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5755 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5756 5757 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5758 // The common case: this global doesn't conflict with any extern "C" 5759 // declaration. 5760 return false; 5761 } 5762 5763 if (Prev) { 5764 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5765 // Both the old and new declarations have C language linkage. This is a 5766 // redeclaration. 5767 Previous.clear(); 5768 Previous.addDecl(Prev); 5769 return true; 5770 } 5771 5772 // This is a global, non-extern "C" declaration, and there is a previous 5773 // non-global extern "C" declaration. Diagnose if this is a variable 5774 // declaration. 5775 if (!isa<VarDecl>(ND)) 5776 return false; 5777 } else { 5778 // The declaration is extern "C". Check for any declaration in the 5779 // translation unit which might conflict. 5780 if (IsGlobal) { 5781 // We have already performed the lookup into the translation unit. 5782 IsGlobal = false; 5783 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5784 I != E; ++I) { 5785 if (isa<VarDecl>(*I)) { 5786 Prev = *I; 5787 break; 5788 } 5789 } 5790 } else { 5791 DeclContext::lookup_result R = 5792 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5793 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5794 I != E; ++I) { 5795 if (isa<VarDecl>(*I)) { 5796 Prev = *I; 5797 break; 5798 } 5799 // FIXME: If we have any other entity with this name in global scope, 5800 // the declaration is ill-formed, but that is a defect: it breaks the 5801 // 'stat' hack, for instance. Only variables can have mangled name 5802 // clashes with extern "C" declarations, so only they deserve a 5803 // diagnostic. 5804 } 5805 } 5806 5807 if (!Prev) 5808 return false; 5809 } 5810 5811 // Use the first declaration's location to ensure we point at something which 5812 // is lexically inside an extern "C" linkage-spec. 5813 assert(Prev && "should have found a previous declaration to diagnose"); 5814 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5815 Prev = FD->getFirstDecl(); 5816 else 5817 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5818 5819 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5820 << IsGlobal << ND; 5821 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5822 << IsGlobal; 5823 return false; 5824 } 5825 5826 /// Apply special rules for handling extern "C" declarations. Returns \c true 5827 /// if we have found that this is a redeclaration of some prior entity. 5828 /// 5829 /// Per C++ [dcl.link]p6: 5830 /// Two declarations [for a function or variable] with C language linkage 5831 /// with the same name that appear in different scopes refer to the same 5832 /// [entity]. An entity with C language linkage shall not be declared with 5833 /// the same name as an entity in global scope. 5834 template<typename T> 5835 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5836 LookupResult &Previous) { 5837 if (!S.getLangOpts().CPlusPlus) { 5838 // In C, when declaring a global variable, look for a corresponding 'extern' 5839 // variable declared in function scope. We don't need this in C++, because 5840 // we find local extern decls in the surrounding file-scope DeclContext. 5841 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5842 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5843 Previous.clear(); 5844 Previous.addDecl(Prev); 5845 return true; 5846 } 5847 } 5848 return false; 5849 } 5850 5851 // A declaration in the translation unit can conflict with an extern "C" 5852 // declaration. 5853 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5854 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5855 5856 // An extern "C" declaration can conflict with a declaration in the 5857 // translation unit or can be a redeclaration of an extern "C" declaration 5858 // in another scope. 5859 if (isIncompleteDeclExternC(S,ND)) 5860 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5861 5862 // Neither global nor extern "C": nothing to do. 5863 return false; 5864 } 5865 5866 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5867 // If the decl is already known invalid, don't check it. 5868 if (NewVD->isInvalidDecl()) 5869 return; 5870 5871 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5872 QualType T = TInfo->getType(); 5873 5874 // Defer checking an 'auto' type until its initializer is attached. 5875 if (T->isUndeducedType()) 5876 return; 5877 5878 if (NewVD->hasAttrs()) 5879 CheckAlignasUnderalignment(NewVD); 5880 5881 if (T->isObjCObjectType()) { 5882 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5883 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5884 T = Context.getObjCObjectPointerType(T); 5885 NewVD->setType(T); 5886 } 5887 5888 // Emit an error if an address space was applied to decl with local storage. 5889 // This includes arrays of objects with address space qualifiers, but not 5890 // automatic variables that point to other address spaces. 5891 // ISO/IEC TR 18037 S5.1.2 5892 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5893 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5894 NewVD->setInvalidDecl(); 5895 return; 5896 } 5897 5898 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5899 // __constant address space. 5900 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5901 && T.getAddressSpace() != LangAS::opencl_constant 5902 && !T->isSamplerT()){ 5903 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5904 NewVD->setInvalidDecl(); 5905 return; 5906 } 5907 5908 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5909 // scope. 5910 if ((getLangOpts().OpenCLVersion >= 120) 5911 && NewVD->isStaticLocal()) { 5912 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5913 NewVD->setInvalidDecl(); 5914 return; 5915 } 5916 5917 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5918 && !NewVD->hasAttr<BlocksAttr>()) { 5919 if (getLangOpts().getGC() != LangOptions::NonGC) 5920 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5921 else { 5922 assert(!getLangOpts().ObjCAutoRefCount); 5923 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5924 } 5925 } 5926 5927 bool isVM = T->isVariablyModifiedType(); 5928 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5929 NewVD->hasAttr<BlocksAttr>()) 5930 getCurFunction()->setHasBranchProtectedScope(); 5931 5932 if ((isVM && NewVD->hasLinkage()) || 5933 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5934 bool SizeIsNegative; 5935 llvm::APSInt Oversized; 5936 TypeSourceInfo *FixedTInfo = 5937 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5938 SizeIsNegative, Oversized); 5939 if (!FixedTInfo && T->isVariableArrayType()) { 5940 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5941 // FIXME: This won't give the correct result for 5942 // int a[10][n]; 5943 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5944 5945 if (NewVD->isFileVarDecl()) 5946 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5947 << SizeRange; 5948 else if (NewVD->isStaticLocal()) 5949 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5950 << SizeRange; 5951 else 5952 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5953 << SizeRange; 5954 NewVD->setInvalidDecl(); 5955 return; 5956 } 5957 5958 if (!FixedTInfo) { 5959 if (NewVD->isFileVarDecl()) 5960 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5961 else 5962 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5963 NewVD->setInvalidDecl(); 5964 return; 5965 } 5966 5967 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5968 NewVD->setType(FixedTInfo->getType()); 5969 NewVD->setTypeSourceInfo(FixedTInfo); 5970 } 5971 5972 if (T->isVoidType()) { 5973 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5974 // of objects and functions. 5975 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5976 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5977 << T; 5978 NewVD->setInvalidDecl(); 5979 return; 5980 } 5981 } 5982 5983 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5984 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5985 NewVD->setInvalidDecl(); 5986 return; 5987 } 5988 5989 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5990 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5991 NewVD->setInvalidDecl(); 5992 return; 5993 } 5994 5995 if (NewVD->isConstexpr() && !T->isDependentType() && 5996 RequireLiteralType(NewVD->getLocation(), T, 5997 diag::err_constexpr_var_non_literal)) { 5998 NewVD->setInvalidDecl(); 5999 return; 6000 } 6001 } 6002 6003 /// \brief Perform semantic checking on a newly-created variable 6004 /// declaration. 6005 /// 6006 /// This routine performs all of the type-checking required for a 6007 /// variable declaration once it has been built. It is used both to 6008 /// check variables after they have been parsed and their declarators 6009 /// have been translated into a declaration, and to check variables 6010 /// that have been instantiated from a template. 6011 /// 6012 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6013 /// 6014 /// Returns true if the variable declaration is a redeclaration. 6015 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6016 CheckVariableDeclarationType(NewVD); 6017 6018 // If the decl is already known invalid, don't check it. 6019 if (NewVD->isInvalidDecl()) 6020 return false; 6021 6022 // If we did not find anything by this name, look for a non-visible 6023 // extern "C" declaration with the same name. 6024 if (Previous.empty() && 6025 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6026 Previous.setShadowed(); 6027 6028 // Filter out any non-conflicting previous declarations. 6029 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6030 6031 if (!Previous.empty()) { 6032 MergeVarDecl(NewVD, Previous); 6033 return true; 6034 } 6035 return false; 6036 } 6037 6038 /// \brief Data used with FindOverriddenMethod 6039 struct FindOverriddenMethodData { 6040 Sema *S; 6041 CXXMethodDecl *Method; 6042 }; 6043 6044 /// \brief Member lookup function that determines whether a given C++ 6045 /// method overrides a method in a base class, to be used with 6046 /// CXXRecordDecl::lookupInBases(). 6047 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6048 CXXBasePath &Path, 6049 void *UserData) { 6050 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6051 6052 FindOverriddenMethodData *Data 6053 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6054 6055 DeclarationName Name = Data->Method->getDeclName(); 6056 6057 // FIXME: Do we care about other names here too? 6058 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6059 // We really want to find the base class destructor here. 6060 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6061 CanQualType CT = Data->S->Context.getCanonicalType(T); 6062 6063 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6064 } 6065 6066 for (Path.Decls = BaseRecord->lookup(Name); 6067 !Path.Decls.empty(); 6068 Path.Decls = Path.Decls.slice(1)) { 6069 NamedDecl *D = Path.Decls.front(); 6070 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6071 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6072 return true; 6073 } 6074 } 6075 6076 return false; 6077 } 6078 6079 namespace { 6080 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6081 } 6082 /// \brief Report an error regarding overriding, along with any relevant 6083 /// overriden methods. 6084 /// 6085 /// \param DiagID the primary error to report. 6086 /// \param MD the overriding method. 6087 /// \param OEK which overrides to include as notes. 6088 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6089 OverrideErrorKind OEK = OEK_All) { 6090 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6091 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6092 E = MD->end_overridden_methods(); 6093 I != E; ++I) { 6094 // This check (& the OEK parameter) could be replaced by a predicate, but 6095 // without lambdas that would be overkill. This is still nicer than writing 6096 // out the diag loop 3 times. 6097 if ((OEK == OEK_All) || 6098 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6099 (OEK == OEK_Deleted && (*I)->isDeleted())) 6100 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6101 } 6102 } 6103 6104 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6105 /// and if so, check that it's a valid override and remember it. 6106 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6107 // Look for virtual methods in base classes that this method might override. 6108 CXXBasePaths Paths; 6109 FindOverriddenMethodData Data; 6110 Data.Method = MD; 6111 Data.S = this; 6112 bool hasDeletedOverridenMethods = false; 6113 bool hasNonDeletedOverridenMethods = false; 6114 bool AddedAny = false; 6115 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6116 for (auto *I : Paths.found_decls()) { 6117 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6118 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6119 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6120 !CheckOverridingFunctionAttributes(MD, OldMD) && 6121 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6122 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6123 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6124 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6125 AddedAny = true; 6126 } 6127 } 6128 } 6129 } 6130 6131 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6132 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6133 } 6134 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6135 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6136 } 6137 6138 return AddedAny; 6139 } 6140 6141 namespace { 6142 // Struct for holding all of the extra arguments needed by 6143 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6144 struct ActOnFDArgs { 6145 Scope *S; 6146 Declarator &D; 6147 MultiTemplateParamsArg TemplateParamLists; 6148 bool AddToScope; 6149 }; 6150 } 6151 6152 namespace { 6153 6154 // Callback to only accept typo corrections that have a non-zero edit distance. 6155 // Also only accept corrections that have the same parent decl. 6156 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6157 public: 6158 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6159 CXXRecordDecl *Parent) 6160 : Context(Context), OriginalFD(TypoFD), 6161 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6162 6163 bool ValidateCandidate(const TypoCorrection &candidate) override { 6164 if (candidate.getEditDistance() == 0) 6165 return false; 6166 6167 SmallVector<unsigned, 1> MismatchedParams; 6168 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6169 CDeclEnd = candidate.end(); 6170 CDecl != CDeclEnd; ++CDecl) { 6171 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6172 6173 if (FD && !FD->hasBody() && 6174 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6175 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6176 CXXRecordDecl *Parent = MD->getParent(); 6177 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6178 return true; 6179 } else if (!ExpectedParent) { 6180 return true; 6181 } 6182 } 6183 } 6184 6185 return false; 6186 } 6187 6188 private: 6189 ASTContext &Context; 6190 FunctionDecl *OriginalFD; 6191 CXXRecordDecl *ExpectedParent; 6192 }; 6193 6194 } 6195 6196 /// \brief Generate diagnostics for an invalid function redeclaration. 6197 /// 6198 /// This routine handles generating the diagnostic messages for an invalid 6199 /// function redeclaration, including finding possible similar declarations 6200 /// or performing typo correction if there are no previous declarations with 6201 /// the same name. 6202 /// 6203 /// Returns a NamedDecl iff typo correction was performed and substituting in 6204 /// the new declaration name does not cause new errors. 6205 static NamedDecl *DiagnoseInvalidRedeclaration( 6206 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6207 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6208 DeclarationName Name = NewFD->getDeclName(); 6209 DeclContext *NewDC = NewFD->getDeclContext(); 6210 SmallVector<unsigned, 1> MismatchedParams; 6211 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6212 TypoCorrection Correction; 6213 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6214 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6215 : diag::err_member_decl_does_not_match; 6216 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6217 IsLocalFriend ? Sema::LookupLocalFriendName 6218 : Sema::LookupOrdinaryName, 6219 Sema::ForRedeclaration); 6220 6221 NewFD->setInvalidDecl(); 6222 if (IsLocalFriend) 6223 SemaRef.LookupName(Prev, S); 6224 else 6225 SemaRef.LookupQualifiedName(Prev, NewDC); 6226 assert(!Prev.isAmbiguous() && 6227 "Cannot have an ambiguity in previous-declaration lookup"); 6228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6229 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6230 MD ? MD->getParent() : nullptr); 6231 if (!Prev.empty()) { 6232 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6233 Func != FuncEnd; ++Func) { 6234 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6235 if (FD && 6236 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6237 // Add 1 to the index so that 0 can mean the mismatch didn't 6238 // involve a parameter 6239 unsigned ParamNum = 6240 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6241 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6242 } 6243 } 6244 // If the qualified name lookup yielded nothing, try typo correction 6245 } else if ((Correction = SemaRef.CorrectTypo( 6246 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6247 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6248 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6249 // Set up everything for the call to ActOnFunctionDeclarator 6250 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6251 ExtraArgs.D.getIdentifierLoc()); 6252 Previous.clear(); 6253 Previous.setLookupName(Correction.getCorrection()); 6254 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6255 CDeclEnd = Correction.end(); 6256 CDecl != CDeclEnd; ++CDecl) { 6257 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6258 if (FD && !FD->hasBody() && 6259 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6260 Previous.addDecl(FD); 6261 } 6262 } 6263 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6264 6265 NamedDecl *Result; 6266 // Retry building the function declaration with the new previous 6267 // declarations, and with errors suppressed. 6268 { 6269 // Trap errors. 6270 Sema::SFINAETrap Trap(SemaRef); 6271 6272 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6273 // pieces need to verify the typo-corrected C++ declaration and hopefully 6274 // eliminate the need for the parameter pack ExtraArgs. 6275 Result = SemaRef.ActOnFunctionDeclarator( 6276 ExtraArgs.S, ExtraArgs.D, 6277 Correction.getCorrectionDecl()->getDeclContext(), 6278 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6279 ExtraArgs.AddToScope); 6280 6281 if (Trap.hasErrorOccurred()) 6282 Result = nullptr; 6283 } 6284 6285 if (Result) { 6286 // Determine which correction we picked. 6287 Decl *Canonical = Result->getCanonicalDecl(); 6288 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6289 I != E; ++I) 6290 if ((*I)->getCanonicalDecl() == Canonical) 6291 Correction.setCorrectionDecl(*I); 6292 6293 SemaRef.diagnoseTypo( 6294 Correction, 6295 SemaRef.PDiag(IsLocalFriend 6296 ? diag::err_no_matching_local_friend_suggest 6297 : diag::err_member_decl_does_not_match_suggest) 6298 << Name << NewDC << IsDefinition); 6299 return Result; 6300 } 6301 6302 // Pretend the typo correction never occurred 6303 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6304 ExtraArgs.D.getIdentifierLoc()); 6305 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6306 Previous.clear(); 6307 Previous.setLookupName(Name); 6308 } 6309 6310 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6311 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6312 6313 bool NewFDisConst = false; 6314 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6315 NewFDisConst = NewMD->isConst(); 6316 6317 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6318 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6319 NearMatch != NearMatchEnd; ++NearMatch) { 6320 FunctionDecl *FD = NearMatch->first; 6321 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6322 bool FDisConst = MD && MD->isConst(); 6323 bool IsMember = MD || !IsLocalFriend; 6324 6325 // FIXME: These notes are poorly worded for the local friend case. 6326 if (unsigned Idx = NearMatch->second) { 6327 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6328 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6329 if (Loc.isInvalid()) Loc = FD->getLocation(); 6330 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6331 : diag::note_local_decl_close_param_match) 6332 << Idx << FDParam->getType() 6333 << NewFD->getParamDecl(Idx - 1)->getType(); 6334 } else if (FDisConst != NewFDisConst) { 6335 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6336 << NewFDisConst << FD->getSourceRange().getEnd(); 6337 } else 6338 SemaRef.Diag(FD->getLocation(), 6339 IsMember ? diag::note_member_def_close_match 6340 : diag::note_local_decl_close_match); 6341 } 6342 return nullptr; 6343 } 6344 6345 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6346 Declarator &D) { 6347 switch (D.getDeclSpec().getStorageClassSpec()) { 6348 default: llvm_unreachable("Unknown storage class!"); 6349 case DeclSpec::SCS_auto: 6350 case DeclSpec::SCS_register: 6351 case DeclSpec::SCS_mutable: 6352 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6353 diag::err_typecheck_sclass_func); 6354 D.setInvalidType(); 6355 break; 6356 case DeclSpec::SCS_unspecified: break; 6357 case DeclSpec::SCS_extern: 6358 if (D.getDeclSpec().isExternInLinkageSpec()) 6359 return SC_None; 6360 return SC_Extern; 6361 case DeclSpec::SCS_static: { 6362 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6363 // C99 6.7.1p5: 6364 // The declaration of an identifier for a function that has 6365 // block scope shall have no explicit storage-class specifier 6366 // other than extern 6367 // See also (C++ [dcl.stc]p4). 6368 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6369 diag::err_static_block_func); 6370 break; 6371 } else 6372 return SC_Static; 6373 } 6374 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6375 } 6376 6377 // No explicit storage class has already been returned 6378 return SC_None; 6379 } 6380 6381 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6382 DeclContext *DC, QualType &R, 6383 TypeSourceInfo *TInfo, 6384 FunctionDecl::StorageClass SC, 6385 bool &IsVirtualOkay) { 6386 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6387 DeclarationName Name = NameInfo.getName(); 6388 6389 FunctionDecl *NewFD = nullptr; 6390 bool isInline = D.getDeclSpec().isInlineSpecified(); 6391 6392 if (!SemaRef.getLangOpts().CPlusPlus) { 6393 // Determine whether the function was written with a 6394 // prototype. This true when: 6395 // - there is a prototype in the declarator, or 6396 // - the type R of the function is some kind of typedef or other reference 6397 // to a type name (which eventually refers to a function type). 6398 bool HasPrototype = 6399 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6400 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6401 6402 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6403 D.getLocStart(), NameInfo, R, 6404 TInfo, SC, isInline, 6405 HasPrototype, false); 6406 if (D.isInvalidType()) 6407 NewFD->setInvalidDecl(); 6408 6409 // Set the lexical context. 6410 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6411 6412 return NewFD; 6413 } 6414 6415 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6416 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6417 6418 // Check that the return type is not an abstract class type. 6419 // For record types, this is done by the AbstractClassUsageDiagnoser once 6420 // the class has been completely parsed. 6421 if (!DC->isRecord() && 6422 SemaRef.RequireNonAbstractType( 6423 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6424 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6425 D.setInvalidType(); 6426 6427 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6428 // This is a C++ constructor declaration. 6429 assert(DC->isRecord() && 6430 "Constructors can only be declared in a member context"); 6431 6432 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6433 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6434 D.getLocStart(), NameInfo, 6435 R, TInfo, isExplicit, isInline, 6436 /*isImplicitlyDeclared=*/false, 6437 isConstexpr); 6438 6439 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6440 // This is a C++ destructor declaration. 6441 if (DC->isRecord()) { 6442 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6443 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6444 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6445 SemaRef.Context, Record, 6446 D.getLocStart(), 6447 NameInfo, R, TInfo, isInline, 6448 /*isImplicitlyDeclared=*/false); 6449 6450 // If the class is complete, then we now create the implicit exception 6451 // specification. If the class is incomplete or dependent, we can't do 6452 // it yet. 6453 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6454 Record->getDefinition() && !Record->isBeingDefined() && 6455 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6456 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6457 } 6458 6459 IsVirtualOkay = true; 6460 return NewDD; 6461 6462 } else { 6463 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6464 D.setInvalidType(); 6465 6466 // Create a FunctionDecl to satisfy the function definition parsing 6467 // code path. 6468 return FunctionDecl::Create(SemaRef.Context, DC, 6469 D.getLocStart(), 6470 D.getIdentifierLoc(), Name, R, TInfo, 6471 SC, isInline, 6472 /*hasPrototype=*/true, isConstexpr); 6473 } 6474 6475 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6476 if (!DC->isRecord()) { 6477 SemaRef.Diag(D.getIdentifierLoc(), 6478 diag::err_conv_function_not_member); 6479 return nullptr; 6480 } 6481 6482 SemaRef.CheckConversionDeclarator(D, R, SC); 6483 IsVirtualOkay = true; 6484 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6485 D.getLocStart(), NameInfo, 6486 R, TInfo, isInline, isExplicit, 6487 isConstexpr, SourceLocation()); 6488 6489 } else if (DC->isRecord()) { 6490 // If the name of the function is the same as the name of the record, 6491 // then this must be an invalid constructor that has a return type. 6492 // (The parser checks for a return type and makes the declarator a 6493 // constructor if it has no return type). 6494 if (Name.getAsIdentifierInfo() && 6495 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6496 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6497 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6498 << SourceRange(D.getIdentifierLoc()); 6499 return nullptr; 6500 } 6501 6502 // This is a C++ method declaration. 6503 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6504 cast<CXXRecordDecl>(DC), 6505 D.getLocStart(), NameInfo, R, 6506 TInfo, SC, isInline, 6507 isConstexpr, SourceLocation()); 6508 IsVirtualOkay = !Ret->isStatic(); 6509 return Ret; 6510 } else { 6511 // Determine whether the function was written with a 6512 // prototype. This true when: 6513 // - we're in C++ (where every function has a prototype), 6514 return FunctionDecl::Create(SemaRef.Context, DC, 6515 D.getLocStart(), 6516 NameInfo, R, TInfo, SC, isInline, 6517 true/*HasPrototype*/, isConstexpr); 6518 } 6519 } 6520 6521 enum OpenCLParamType { 6522 ValidKernelParam, 6523 PtrPtrKernelParam, 6524 PtrKernelParam, 6525 PrivatePtrKernelParam, 6526 InvalidKernelParam, 6527 RecordKernelParam 6528 }; 6529 6530 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6531 if (PT->isPointerType()) { 6532 QualType PointeeType = PT->getPointeeType(); 6533 if (PointeeType->isPointerType()) 6534 return PtrPtrKernelParam; 6535 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6536 : PtrKernelParam; 6537 } 6538 6539 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6540 // be used as builtin types. 6541 6542 if (PT->isImageType()) 6543 return PtrKernelParam; 6544 6545 if (PT->isBooleanType()) 6546 return InvalidKernelParam; 6547 6548 if (PT->isEventT()) 6549 return InvalidKernelParam; 6550 6551 if (PT->isHalfType()) 6552 return InvalidKernelParam; 6553 6554 if (PT->isRecordType()) 6555 return RecordKernelParam; 6556 6557 return ValidKernelParam; 6558 } 6559 6560 static void checkIsValidOpenCLKernelParameter( 6561 Sema &S, 6562 Declarator &D, 6563 ParmVarDecl *Param, 6564 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6565 QualType PT = Param->getType(); 6566 6567 // Cache the valid types we encounter to avoid rechecking structs that are 6568 // used again 6569 if (ValidTypes.count(PT.getTypePtr())) 6570 return; 6571 6572 switch (getOpenCLKernelParameterType(PT)) { 6573 case PtrPtrKernelParam: 6574 // OpenCL v1.2 s6.9.a: 6575 // A kernel function argument cannot be declared as a 6576 // pointer to a pointer type. 6577 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6578 D.setInvalidType(); 6579 return; 6580 6581 case PrivatePtrKernelParam: 6582 // OpenCL v1.2 s6.9.a: 6583 // A kernel function argument cannot be declared as a 6584 // pointer to the private address space. 6585 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6586 D.setInvalidType(); 6587 return; 6588 6589 // OpenCL v1.2 s6.9.k: 6590 // Arguments to kernel functions in a program cannot be declared with the 6591 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6592 // uintptr_t or a struct and/or union that contain fields declared to be 6593 // one of these built-in scalar types. 6594 6595 case InvalidKernelParam: 6596 // OpenCL v1.2 s6.8 n: 6597 // A kernel function argument cannot be declared 6598 // of event_t type. 6599 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6600 D.setInvalidType(); 6601 return; 6602 6603 case PtrKernelParam: 6604 case ValidKernelParam: 6605 ValidTypes.insert(PT.getTypePtr()); 6606 return; 6607 6608 case RecordKernelParam: 6609 break; 6610 } 6611 6612 // Track nested structs we will inspect 6613 SmallVector<const Decl *, 4> VisitStack; 6614 6615 // Track where we are in the nested structs. Items will migrate from 6616 // VisitStack to HistoryStack as we do the DFS for bad field. 6617 SmallVector<const FieldDecl *, 4> HistoryStack; 6618 HistoryStack.push_back(nullptr); 6619 6620 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6621 VisitStack.push_back(PD); 6622 6623 assert(VisitStack.back() && "First decl null?"); 6624 6625 do { 6626 const Decl *Next = VisitStack.pop_back_val(); 6627 if (!Next) { 6628 assert(!HistoryStack.empty()); 6629 // Found a marker, we have gone up a level 6630 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6631 ValidTypes.insert(Hist->getType().getTypePtr()); 6632 6633 continue; 6634 } 6635 6636 // Adds everything except the original parameter declaration (which is not a 6637 // field itself) to the history stack. 6638 const RecordDecl *RD; 6639 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6640 HistoryStack.push_back(Field); 6641 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6642 } else { 6643 RD = cast<RecordDecl>(Next); 6644 } 6645 6646 // Add a null marker so we know when we've gone back up a level 6647 VisitStack.push_back(nullptr); 6648 6649 for (const auto *FD : RD->fields()) { 6650 QualType QT = FD->getType(); 6651 6652 if (ValidTypes.count(QT.getTypePtr())) 6653 continue; 6654 6655 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6656 if (ParamType == ValidKernelParam) 6657 continue; 6658 6659 if (ParamType == RecordKernelParam) { 6660 VisitStack.push_back(FD); 6661 continue; 6662 } 6663 6664 // OpenCL v1.2 s6.9.p: 6665 // Arguments to kernel functions that are declared to be a struct or union 6666 // do not allow OpenCL objects to be passed as elements of the struct or 6667 // union. 6668 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6669 ParamType == PrivatePtrKernelParam) { 6670 S.Diag(Param->getLocation(), 6671 diag::err_record_with_pointers_kernel_param) 6672 << PT->isUnionType() 6673 << PT; 6674 } else { 6675 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6676 } 6677 6678 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6679 << PD->getDeclName(); 6680 6681 // We have an error, now let's go back up through history and show where 6682 // the offending field came from 6683 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6684 E = HistoryStack.end(); I != E; ++I) { 6685 const FieldDecl *OuterField = *I; 6686 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6687 << OuterField->getType(); 6688 } 6689 6690 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6691 << QT->isPointerType() 6692 << QT; 6693 D.setInvalidType(); 6694 return; 6695 } 6696 } while (!VisitStack.empty()); 6697 } 6698 6699 NamedDecl* 6700 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6701 TypeSourceInfo *TInfo, LookupResult &Previous, 6702 MultiTemplateParamsArg TemplateParamLists, 6703 bool &AddToScope) { 6704 QualType R = TInfo->getType(); 6705 6706 assert(R.getTypePtr()->isFunctionType()); 6707 6708 // TODO: consider using NameInfo for diagnostic. 6709 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6710 DeclarationName Name = NameInfo.getName(); 6711 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6712 6713 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6714 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6715 diag::err_invalid_thread) 6716 << DeclSpec::getSpecifierName(TSCS); 6717 6718 if (D.isFirstDeclarationOfMember()) 6719 adjustMemberFunctionCC(R, D.isStaticMember()); 6720 6721 bool isFriend = false; 6722 FunctionTemplateDecl *FunctionTemplate = nullptr; 6723 bool isExplicitSpecialization = false; 6724 bool isFunctionTemplateSpecialization = false; 6725 6726 bool isDependentClassScopeExplicitSpecialization = false; 6727 bool HasExplicitTemplateArgs = false; 6728 TemplateArgumentListInfo TemplateArgs; 6729 6730 bool isVirtualOkay = false; 6731 6732 DeclContext *OriginalDC = DC; 6733 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6734 6735 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6736 isVirtualOkay); 6737 if (!NewFD) return nullptr; 6738 6739 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6740 NewFD->setTopLevelDeclInObjCContainer(); 6741 6742 // Set the lexical context. If this is a function-scope declaration, or has a 6743 // C++ scope specifier, or is the object of a friend declaration, the lexical 6744 // context will be different from the semantic context. 6745 NewFD->setLexicalDeclContext(CurContext); 6746 6747 if (IsLocalExternDecl) 6748 NewFD->setLocalExternDecl(); 6749 6750 if (getLangOpts().CPlusPlus) { 6751 bool isInline = D.getDeclSpec().isInlineSpecified(); 6752 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6753 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6754 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6755 isFriend = D.getDeclSpec().isFriendSpecified(); 6756 if (isFriend && !isInline && D.isFunctionDefinition()) { 6757 // C++ [class.friend]p5 6758 // A function can be defined in a friend declaration of a 6759 // class . . . . Such a function is implicitly inline. 6760 NewFD->setImplicitlyInline(); 6761 } 6762 6763 // If this is a method defined in an __interface, and is not a constructor 6764 // or an overloaded operator, then set the pure flag (isVirtual will already 6765 // return true). 6766 if (const CXXRecordDecl *Parent = 6767 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6768 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6769 NewFD->setPure(true); 6770 } 6771 6772 SetNestedNameSpecifier(NewFD, D); 6773 isExplicitSpecialization = false; 6774 isFunctionTemplateSpecialization = false; 6775 if (D.isInvalidType()) 6776 NewFD->setInvalidDecl(); 6777 6778 // Match up the template parameter lists with the scope specifier, then 6779 // determine whether we have a template or a template specialization. 6780 bool Invalid = false; 6781 if (TemplateParameterList *TemplateParams = 6782 MatchTemplateParametersToScopeSpecifier( 6783 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6784 D.getCXXScopeSpec(), 6785 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6786 ? D.getName().TemplateId 6787 : nullptr, 6788 TemplateParamLists, isFriend, isExplicitSpecialization, 6789 Invalid)) { 6790 if (TemplateParams->size() > 0) { 6791 // This is a function template 6792 6793 // Check that we can declare a template here. 6794 if (CheckTemplateDeclScope(S, TemplateParams)) 6795 return nullptr; 6796 6797 // A destructor cannot be a template. 6798 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6799 Diag(NewFD->getLocation(), diag::err_destructor_template); 6800 return nullptr; 6801 } 6802 6803 // If we're adding a template to a dependent context, we may need to 6804 // rebuilding some of the types used within the template parameter list, 6805 // now that we know what the current instantiation is. 6806 if (DC->isDependentContext()) { 6807 ContextRAII SavedContext(*this, DC); 6808 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6809 Invalid = true; 6810 } 6811 6812 6813 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6814 NewFD->getLocation(), 6815 Name, TemplateParams, 6816 NewFD); 6817 FunctionTemplate->setLexicalDeclContext(CurContext); 6818 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6819 6820 // For source fidelity, store the other template param lists. 6821 if (TemplateParamLists.size() > 1) { 6822 NewFD->setTemplateParameterListsInfo(Context, 6823 TemplateParamLists.size() - 1, 6824 TemplateParamLists.data()); 6825 } 6826 } else { 6827 // This is a function template specialization. 6828 isFunctionTemplateSpecialization = true; 6829 // For source fidelity, store all the template param lists. 6830 if (TemplateParamLists.size() > 0) 6831 NewFD->setTemplateParameterListsInfo(Context, 6832 TemplateParamLists.size(), 6833 TemplateParamLists.data()); 6834 6835 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6836 if (isFriend) { 6837 // We want to remove the "template<>", found here. 6838 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6839 6840 // If we remove the template<> and the name is not a 6841 // template-id, we're actually silently creating a problem: 6842 // the friend declaration will refer to an untemplated decl, 6843 // and clearly the user wants a template specialization. So 6844 // we need to insert '<>' after the name. 6845 SourceLocation InsertLoc; 6846 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6847 InsertLoc = D.getName().getSourceRange().getEnd(); 6848 InsertLoc = getLocForEndOfToken(InsertLoc); 6849 } 6850 6851 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6852 << Name << RemoveRange 6853 << FixItHint::CreateRemoval(RemoveRange) 6854 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6855 } 6856 } 6857 } 6858 else { 6859 // All template param lists were matched against the scope specifier: 6860 // this is NOT (an explicit specialization of) a template. 6861 if (TemplateParamLists.size() > 0) 6862 // For source fidelity, store all the template param lists. 6863 NewFD->setTemplateParameterListsInfo(Context, 6864 TemplateParamLists.size(), 6865 TemplateParamLists.data()); 6866 } 6867 6868 if (Invalid) { 6869 NewFD->setInvalidDecl(); 6870 if (FunctionTemplate) 6871 FunctionTemplate->setInvalidDecl(); 6872 } 6873 6874 // C++ [dcl.fct.spec]p5: 6875 // The virtual specifier shall only be used in declarations of 6876 // nonstatic class member functions that appear within a 6877 // member-specification of a class declaration; see 10.3. 6878 // 6879 if (isVirtual && !NewFD->isInvalidDecl()) { 6880 if (!isVirtualOkay) { 6881 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6882 diag::err_virtual_non_function); 6883 } else if (!CurContext->isRecord()) { 6884 // 'virtual' was specified outside of the class. 6885 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6886 diag::err_virtual_out_of_class) 6887 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6888 } else if (NewFD->getDescribedFunctionTemplate()) { 6889 // C++ [temp.mem]p3: 6890 // A member function template shall not be virtual. 6891 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6892 diag::err_virtual_member_function_template) 6893 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6894 } else { 6895 // Okay: Add virtual to the method. 6896 NewFD->setVirtualAsWritten(true); 6897 } 6898 6899 if (getLangOpts().CPlusPlus1y && 6900 NewFD->getReturnType()->isUndeducedType()) 6901 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6902 } 6903 6904 if (getLangOpts().CPlusPlus1y && 6905 (NewFD->isDependentContext() || 6906 (isFriend && CurContext->isDependentContext())) && 6907 NewFD->getReturnType()->isUndeducedType()) { 6908 // If the function template is referenced directly (for instance, as a 6909 // member of the current instantiation), pretend it has a dependent type. 6910 // This is not really justified by the standard, but is the only sane 6911 // thing to do. 6912 // FIXME: For a friend function, we have not marked the function as being 6913 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6914 const FunctionProtoType *FPT = 6915 NewFD->getType()->castAs<FunctionProtoType>(); 6916 QualType Result = 6917 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6918 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6919 FPT->getExtProtoInfo())); 6920 } 6921 6922 // C++ [dcl.fct.spec]p3: 6923 // The inline specifier shall not appear on a block scope function 6924 // declaration. 6925 if (isInline && !NewFD->isInvalidDecl()) { 6926 if (CurContext->isFunctionOrMethod()) { 6927 // 'inline' is not allowed on block scope function declaration. 6928 Diag(D.getDeclSpec().getInlineSpecLoc(), 6929 diag::err_inline_declaration_block_scope) << Name 6930 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6931 } 6932 } 6933 6934 // C++ [dcl.fct.spec]p6: 6935 // The explicit specifier shall be used only in the declaration of a 6936 // constructor or conversion function within its class definition; 6937 // see 12.3.1 and 12.3.2. 6938 if (isExplicit && !NewFD->isInvalidDecl()) { 6939 if (!CurContext->isRecord()) { 6940 // 'explicit' was specified outside of the class. 6941 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6942 diag::err_explicit_out_of_class) 6943 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6944 } else if (!isa<CXXConstructorDecl>(NewFD) && 6945 !isa<CXXConversionDecl>(NewFD)) { 6946 // 'explicit' was specified on a function that wasn't a constructor 6947 // or conversion function. 6948 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6949 diag::err_explicit_non_ctor_or_conv_function) 6950 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6951 } 6952 } 6953 6954 if (isConstexpr) { 6955 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6956 // are implicitly inline. 6957 NewFD->setImplicitlyInline(); 6958 6959 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6960 // be either constructors or to return a literal type. Therefore, 6961 // destructors cannot be declared constexpr. 6962 if (isa<CXXDestructorDecl>(NewFD)) 6963 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6964 } 6965 6966 // If __module_private__ was specified, mark the function accordingly. 6967 if (D.getDeclSpec().isModulePrivateSpecified()) { 6968 if (isFunctionTemplateSpecialization) { 6969 SourceLocation ModulePrivateLoc 6970 = D.getDeclSpec().getModulePrivateSpecLoc(); 6971 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6972 << 0 6973 << FixItHint::CreateRemoval(ModulePrivateLoc); 6974 } else { 6975 NewFD->setModulePrivate(); 6976 if (FunctionTemplate) 6977 FunctionTemplate->setModulePrivate(); 6978 } 6979 } 6980 6981 if (isFriend) { 6982 if (FunctionTemplate) { 6983 FunctionTemplate->setObjectOfFriendDecl(); 6984 FunctionTemplate->setAccess(AS_public); 6985 } 6986 NewFD->setObjectOfFriendDecl(); 6987 NewFD->setAccess(AS_public); 6988 } 6989 6990 // If a function is defined as defaulted or deleted, mark it as such now. 6991 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6992 // definition kind to FDK_Definition. 6993 switch (D.getFunctionDefinitionKind()) { 6994 case FDK_Declaration: 6995 case FDK_Definition: 6996 break; 6997 6998 case FDK_Defaulted: 6999 NewFD->setDefaulted(); 7000 break; 7001 7002 case FDK_Deleted: 7003 NewFD->setDeletedAsWritten(); 7004 break; 7005 } 7006 7007 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7008 D.isFunctionDefinition()) { 7009 // C++ [class.mfct]p2: 7010 // A member function may be defined (8.4) in its class definition, in 7011 // which case it is an inline member function (7.1.2) 7012 NewFD->setImplicitlyInline(); 7013 } 7014 7015 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7016 !CurContext->isRecord()) { 7017 // C++ [class.static]p1: 7018 // A data or function member of a class may be declared static 7019 // in a class definition, in which case it is a static member of 7020 // the class. 7021 7022 // Complain about the 'static' specifier if it's on an out-of-line 7023 // member function definition. 7024 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7025 diag::err_static_out_of_line) 7026 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7027 } 7028 7029 // C++11 [except.spec]p15: 7030 // A deallocation function with no exception-specification is treated 7031 // as if it were specified with noexcept(true). 7032 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7033 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7034 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7035 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 7036 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7037 EPI.ExceptionSpecType = EST_BasicNoexcept; 7038 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 7039 FPT->getParamTypes(), EPI)); 7040 } 7041 } 7042 7043 // Filter out previous declarations that don't match the scope. 7044 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7045 D.getCXXScopeSpec().isNotEmpty() || 7046 isExplicitSpecialization || 7047 isFunctionTemplateSpecialization); 7048 7049 // Handle GNU asm-label extension (encoded as an attribute). 7050 if (Expr *E = (Expr*) D.getAsmLabel()) { 7051 // The parser guarantees this is a string. 7052 StringLiteral *SE = cast<StringLiteral>(E); 7053 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7054 SE->getString(), 0)); 7055 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7056 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7057 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7058 if (I != ExtnameUndeclaredIdentifiers.end()) { 7059 NewFD->addAttr(I->second); 7060 ExtnameUndeclaredIdentifiers.erase(I); 7061 } 7062 } 7063 7064 // Copy the parameter declarations from the declarator D to the function 7065 // declaration NewFD, if they are available. First scavenge them into Params. 7066 SmallVector<ParmVarDecl*, 16> Params; 7067 if (D.isFunctionDeclarator()) { 7068 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7069 7070 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7071 // function that takes no arguments, not a function that takes a 7072 // single void argument. 7073 // We let through "const void" here because Sema::GetTypeForDeclarator 7074 // already checks for that case. 7075 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7076 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7077 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7078 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7079 Param->setDeclContext(NewFD); 7080 Params.push_back(Param); 7081 7082 if (Param->isInvalidDecl()) 7083 NewFD->setInvalidDecl(); 7084 } 7085 } 7086 7087 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7088 // When we're declaring a function with a typedef, typeof, etc as in the 7089 // following example, we'll need to synthesize (unnamed) 7090 // parameters for use in the declaration. 7091 // 7092 // @code 7093 // typedef void fn(int); 7094 // fn f; 7095 // @endcode 7096 7097 // Synthesize a parameter for each argument type. 7098 for (const auto &AI : FT->param_types()) { 7099 ParmVarDecl *Param = 7100 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7101 Param->setScopeInfo(0, Params.size()); 7102 Params.push_back(Param); 7103 } 7104 } else { 7105 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7106 "Should not need args for typedef of non-prototype fn"); 7107 } 7108 7109 // Finally, we know we have the right number of parameters, install them. 7110 NewFD->setParams(Params); 7111 7112 // Find all anonymous symbols defined during the declaration of this function 7113 // and add to NewFD. This lets us track decls such 'enum Y' in: 7114 // 7115 // void f(enum Y {AA} x) {} 7116 // 7117 // which would otherwise incorrectly end up in the translation unit scope. 7118 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7119 DeclsInPrototypeScope.clear(); 7120 7121 if (D.getDeclSpec().isNoreturnSpecified()) 7122 NewFD->addAttr( 7123 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7124 Context, 0)); 7125 7126 // Functions returning a variably modified type violate C99 6.7.5.2p2 7127 // because all functions have linkage. 7128 if (!NewFD->isInvalidDecl() && 7129 NewFD->getReturnType()->isVariablyModifiedType()) { 7130 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7131 NewFD->setInvalidDecl(); 7132 } 7133 7134 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7135 !NewFD->hasAttr<SectionAttr>()) { 7136 NewFD->addAttr( 7137 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7138 CodeSegStack.CurrentValue->getString(), 7139 CodeSegStack.CurrentPragmaLocation)); 7140 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7141 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7142 NewFD->dropAttr<SectionAttr>(); 7143 } 7144 7145 // Handle attributes. 7146 ProcessDeclAttributes(S, NewFD, D); 7147 7148 QualType RetType = NewFD->getReturnType(); 7149 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7150 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7151 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7152 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7153 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7154 // Attach WarnUnusedResult to functions returning types with that attribute. 7155 // Don't apply the attribute to that type's own non-static member functions 7156 // (to avoid warning on things like assignment operators) 7157 if (!MD || MD->getParent() != Ret) 7158 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7159 } 7160 7161 if (getLangOpts().OpenCL) { 7162 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7163 // type declaration will generate a compilation error. 7164 unsigned AddressSpace = RetType.getAddressSpace(); 7165 if (AddressSpace == LangAS::opencl_local || 7166 AddressSpace == LangAS::opencl_global || 7167 AddressSpace == LangAS::opencl_constant) { 7168 Diag(NewFD->getLocation(), 7169 diag::err_opencl_return_value_with_address_space); 7170 NewFD->setInvalidDecl(); 7171 } 7172 } 7173 7174 if (!getLangOpts().CPlusPlus) { 7175 // Perform semantic checking on the function declaration. 7176 bool isExplicitSpecialization=false; 7177 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7178 CheckMain(NewFD, D.getDeclSpec()); 7179 7180 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7181 CheckMSVCRTEntryPoint(NewFD); 7182 7183 if (!NewFD->isInvalidDecl()) 7184 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7185 isExplicitSpecialization)); 7186 else if (!Previous.empty()) 7187 // Make graceful recovery from an invalid redeclaration. 7188 D.setRedeclaration(true); 7189 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7190 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7191 "previous declaration set still overloaded"); 7192 } else { 7193 // C++11 [replacement.functions]p3: 7194 // The program's definitions shall not be specified as inline. 7195 // 7196 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7197 // 7198 // Suppress the diagnostic if the function is __attribute__((used)), since 7199 // that forces an external definition to be emitted. 7200 if (D.getDeclSpec().isInlineSpecified() && 7201 NewFD->isReplaceableGlobalAllocationFunction() && 7202 !NewFD->hasAttr<UsedAttr>()) 7203 Diag(D.getDeclSpec().getInlineSpecLoc(), 7204 diag::ext_operator_new_delete_declared_inline) 7205 << NewFD->getDeclName(); 7206 7207 // If the declarator is a template-id, translate the parser's template 7208 // argument list into our AST format. 7209 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7210 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7211 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7212 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7213 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7214 TemplateId->NumArgs); 7215 translateTemplateArguments(TemplateArgsPtr, 7216 TemplateArgs); 7217 7218 HasExplicitTemplateArgs = true; 7219 7220 if (NewFD->isInvalidDecl()) { 7221 HasExplicitTemplateArgs = false; 7222 } else if (FunctionTemplate) { 7223 // Function template with explicit template arguments. 7224 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7225 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7226 7227 HasExplicitTemplateArgs = false; 7228 } else { 7229 assert((isFunctionTemplateSpecialization || 7230 D.getDeclSpec().isFriendSpecified()) && 7231 "should have a 'template<>' for this decl"); 7232 // "friend void foo<>(int);" is an implicit specialization decl. 7233 isFunctionTemplateSpecialization = true; 7234 } 7235 } else if (isFriend && isFunctionTemplateSpecialization) { 7236 // This combination is only possible in a recovery case; the user 7237 // wrote something like: 7238 // template <> friend void foo(int); 7239 // which we're recovering from as if the user had written: 7240 // friend void foo<>(int); 7241 // Go ahead and fake up a template id. 7242 HasExplicitTemplateArgs = true; 7243 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7244 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7245 } 7246 7247 // If it's a friend (and only if it's a friend), it's possible 7248 // that either the specialized function type or the specialized 7249 // template is dependent, and therefore matching will fail. In 7250 // this case, don't check the specialization yet. 7251 bool InstantiationDependent = false; 7252 if (isFunctionTemplateSpecialization && isFriend && 7253 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7254 TemplateSpecializationType::anyDependentTemplateArguments( 7255 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7256 InstantiationDependent))) { 7257 assert(HasExplicitTemplateArgs && 7258 "friend function specialization without template args"); 7259 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7260 Previous)) 7261 NewFD->setInvalidDecl(); 7262 } else if (isFunctionTemplateSpecialization) { 7263 if (CurContext->isDependentContext() && CurContext->isRecord() 7264 && !isFriend) { 7265 isDependentClassScopeExplicitSpecialization = true; 7266 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7267 diag::ext_function_specialization_in_class : 7268 diag::err_function_specialization_in_class) 7269 << NewFD->getDeclName(); 7270 } else if (CheckFunctionTemplateSpecialization(NewFD, 7271 (HasExplicitTemplateArgs ? &TemplateArgs 7272 : nullptr), 7273 Previous)) 7274 NewFD->setInvalidDecl(); 7275 7276 // C++ [dcl.stc]p1: 7277 // A storage-class-specifier shall not be specified in an explicit 7278 // specialization (14.7.3) 7279 FunctionTemplateSpecializationInfo *Info = 7280 NewFD->getTemplateSpecializationInfo(); 7281 if (Info && SC != SC_None) { 7282 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7283 Diag(NewFD->getLocation(), 7284 diag::err_explicit_specialization_inconsistent_storage_class) 7285 << SC 7286 << FixItHint::CreateRemoval( 7287 D.getDeclSpec().getStorageClassSpecLoc()); 7288 7289 else 7290 Diag(NewFD->getLocation(), 7291 diag::ext_explicit_specialization_storage_class) 7292 << FixItHint::CreateRemoval( 7293 D.getDeclSpec().getStorageClassSpecLoc()); 7294 } 7295 7296 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7297 if (CheckMemberSpecialization(NewFD, Previous)) 7298 NewFD->setInvalidDecl(); 7299 } 7300 7301 // Perform semantic checking on the function declaration. 7302 if (!isDependentClassScopeExplicitSpecialization) { 7303 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7304 CheckMain(NewFD, D.getDeclSpec()); 7305 7306 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7307 CheckMSVCRTEntryPoint(NewFD); 7308 7309 if (!NewFD->isInvalidDecl()) 7310 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7311 isExplicitSpecialization)); 7312 } 7313 7314 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7315 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7316 "previous declaration set still overloaded"); 7317 7318 NamedDecl *PrincipalDecl = (FunctionTemplate 7319 ? cast<NamedDecl>(FunctionTemplate) 7320 : NewFD); 7321 7322 if (isFriend && D.isRedeclaration()) { 7323 AccessSpecifier Access = AS_public; 7324 if (!NewFD->isInvalidDecl()) 7325 Access = NewFD->getPreviousDecl()->getAccess(); 7326 7327 NewFD->setAccess(Access); 7328 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7329 } 7330 7331 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7332 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7333 PrincipalDecl->setNonMemberOperator(); 7334 7335 // If we have a function template, check the template parameter 7336 // list. This will check and merge default template arguments. 7337 if (FunctionTemplate) { 7338 FunctionTemplateDecl *PrevTemplate = 7339 FunctionTemplate->getPreviousDecl(); 7340 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7341 PrevTemplate ? PrevTemplate->getTemplateParameters() 7342 : nullptr, 7343 D.getDeclSpec().isFriendSpecified() 7344 ? (D.isFunctionDefinition() 7345 ? TPC_FriendFunctionTemplateDefinition 7346 : TPC_FriendFunctionTemplate) 7347 : (D.getCXXScopeSpec().isSet() && 7348 DC && DC->isRecord() && 7349 DC->isDependentContext()) 7350 ? TPC_ClassTemplateMember 7351 : TPC_FunctionTemplate); 7352 } 7353 7354 if (NewFD->isInvalidDecl()) { 7355 // Ignore all the rest of this. 7356 } else if (!D.isRedeclaration()) { 7357 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7358 AddToScope }; 7359 // Fake up an access specifier if it's supposed to be a class member. 7360 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7361 NewFD->setAccess(AS_public); 7362 7363 // Qualified decls generally require a previous declaration. 7364 if (D.getCXXScopeSpec().isSet()) { 7365 // ...with the major exception of templated-scope or 7366 // dependent-scope friend declarations. 7367 7368 // TODO: we currently also suppress this check in dependent 7369 // contexts because (1) the parameter depth will be off when 7370 // matching friend templates and (2) we might actually be 7371 // selecting a friend based on a dependent factor. But there 7372 // are situations where these conditions don't apply and we 7373 // can actually do this check immediately. 7374 if (isFriend && 7375 (TemplateParamLists.size() || 7376 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7377 CurContext->isDependentContext())) { 7378 // ignore these 7379 } else { 7380 // The user tried to provide an out-of-line definition for a 7381 // function that is a member of a class or namespace, but there 7382 // was no such member function declared (C++ [class.mfct]p2, 7383 // C++ [namespace.memdef]p2). For example: 7384 // 7385 // class X { 7386 // void f() const; 7387 // }; 7388 // 7389 // void X::f() { } // ill-formed 7390 // 7391 // Complain about this problem, and attempt to suggest close 7392 // matches (e.g., those that differ only in cv-qualifiers and 7393 // whether the parameter types are references). 7394 7395 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7396 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7397 AddToScope = ExtraArgs.AddToScope; 7398 return Result; 7399 } 7400 } 7401 7402 // Unqualified local friend declarations are required to resolve 7403 // to something. 7404 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7405 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7406 *this, Previous, NewFD, ExtraArgs, true, S)) { 7407 AddToScope = ExtraArgs.AddToScope; 7408 return Result; 7409 } 7410 } 7411 7412 } else if (!D.isFunctionDefinition() && 7413 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7414 !isFriend && !isFunctionTemplateSpecialization && 7415 !isExplicitSpecialization) { 7416 // An out-of-line member function declaration must also be a 7417 // definition (C++ [class.mfct]p2). 7418 // Note that this is not the case for explicit specializations of 7419 // function templates or member functions of class templates, per 7420 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7421 // extension for compatibility with old SWIG code which likes to 7422 // generate them. 7423 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7424 << D.getCXXScopeSpec().getRange(); 7425 } 7426 } 7427 7428 ProcessPragmaWeak(S, NewFD); 7429 checkAttributesAfterMerging(*this, *NewFD); 7430 7431 AddKnownFunctionAttributes(NewFD); 7432 7433 if (NewFD->hasAttr<OverloadableAttr>() && 7434 !NewFD->getType()->getAs<FunctionProtoType>()) { 7435 Diag(NewFD->getLocation(), 7436 diag::err_attribute_overloadable_no_prototype) 7437 << NewFD; 7438 7439 // Turn this into a variadic function with no parameters. 7440 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7441 FunctionProtoType::ExtProtoInfo EPI( 7442 Context.getDefaultCallingConvention(true, false)); 7443 EPI.Variadic = true; 7444 EPI.ExtInfo = FT->getExtInfo(); 7445 7446 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7447 NewFD->setType(R); 7448 } 7449 7450 // If there's a #pragma GCC visibility in scope, and this isn't a class 7451 // member, set the visibility of this function. 7452 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7453 AddPushedVisibilityAttribute(NewFD); 7454 7455 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7456 // marking the function. 7457 AddCFAuditedAttribute(NewFD); 7458 7459 // If this is a function definition, check if we have to apply optnone due to 7460 // a pragma. 7461 if(D.isFunctionDefinition()) 7462 AddRangeBasedOptnone(NewFD); 7463 7464 // If this is the first declaration of an extern C variable, update 7465 // the map of such variables. 7466 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7467 isIncompleteDeclExternC(*this, NewFD)) 7468 RegisterLocallyScopedExternCDecl(NewFD, S); 7469 7470 // Set this FunctionDecl's range up to the right paren. 7471 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7472 7473 if (D.isRedeclaration() && !Previous.empty()) { 7474 checkDLLAttributeRedeclaration( 7475 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7476 isExplicitSpecialization || isFunctionTemplateSpecialization); 7477 } 7478 7479 if (getLangOpts().CPlusPlus) { 7480 if (FunctionTemplate) { 7481 if (NewFD->isInvalidDecl()) 7482 FunctionTemplate->setInvalidDecl(); 7483 return FunctionTemplate; 7484 } 7485 } 7486 7487 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7488 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7489 if ((getLangOpts().OpenCLVersion >= 120) 7490 && (SC == SC_Static)) { 7491 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7492 D.setInvalidType(); 7493 } 7494 7495 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7496 if (!NewFD->getReturnType()->isVoidType()) { 7497 Diag(D.getIdentifierLoc(), 7498 diag::err_expected_kernel_void_return_type); 7499 D.setInvalidType(); 7500 } 7501 7502 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7503 for (auto Param : NewFD->params()) 7504 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7505 } 7506 7507 MarkUnusedFileScopedDecl(NewFD); 7508 7509 if (getLangOpts().CUDA) 7510 if (IdentifierInfo *II = NewFD->getIdentifier()) 7511 if (!NewFD->isInvalidDecl() && 7512 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7513 if (II->isStr("cudaConfigureCall")) { 7514 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7515 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7516 7517 Context.setcudaConfigureCallDecl(NewFD); 7518 } 7519 } 7520 7521 // Here we have an function template explicit specialization at class scope. 7522 // The actually specialization will be postponed to template instatiation 7523 // time via the ClassScopeFunctionSpecializationDecl node. 7524 if (isDependentClassScopeExplicitSpecialization) { 7525 ClassScopeFunctionSpecializationDecl *NewSpec = 7526 ClassScopeFunctionSpecializationDecl::Create( 7527 Context, CurContext, SourceLocation(), 7528 cast<CXXMethodDecl>(NewFD), 7529 HasExplicitTemplateArgs, TemplateArgs); 7530 CurContext->addDecl(NewSpec); 7531 AddToScope = false; 7532 } 7533 7534 return NewFD; 7535 } 7536 7537 /// \brief Perform semantic checking of a new function declaration. 7538 /// 7539 /// Performs semantic analysis of the new function declaration 7540 /// NewFD. This routine performs all semantic checking that does not 7541 /// require the actual declarator involved in the declaration, and is 7542 /// used both for the declaration of functions as they are parsed 7543 /// (called via ActOnDeclarator) and for the declaration of functions 7544 /// that have been instantiated via C++ template instantiation (called 7545 /// via InstantiateDecl). 7546 /// 7547 /// \param IsExplicitSpecialization whether this new function declaration is 7548 /// an explicit specialization of the previous declaration. 7549 /// 7550 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7551 /// 7552 /// \returns true if the function declaration is a redeclaration. 7553 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7554 LookupResult &Previous, 7555 bool IsExplicitSpecialization) { 7556 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7557 "Variably modified return types are not handled here"); 7558 7559 // Determine whether the type of this function should be merged with 7560 // a previous visible declaration. This never happens for functions in C++, 7561 // and always happens in C if the previous declaration was visible. 7562 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7563 !Previous.isShadowed(); 7564 7565 // Filter out any non-conflicting previous declarations. 7566 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7567 7568 bool Redeclaration = false; 7569 NamedDecl *OldDecl = nullptr; 7570 7571 // Merge or overload the declaration with an existing declaration of 7572 // the same name, if appropriate. 7573 if (!Previous.empty()) { 7574 // Determine whether NewFD is an overload of PrevDecl or 7575 // a declaration that requires merging. If it's an overload, 7576 // there's no more work to do here; we'll just add the new 7577 // function to the scope. 7578 if (!AllowOverloadingOfFunction(Previous, Context)) { 7579 NamedDecl *Candidate = Previous.getFoundDecl(); 7580 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7581 Redeclaration = true; 7582 OldDecl = Candidate; 7583 } 7584 } else { 7585 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7586 /*NewIsUsingDecl*/ false)) { 7587 case Ovl_Match: 7588 Redeclaration = true; 7589 break; 7590 7591 case Ovl_NonFunction: 7592 Redeclaration = true; 7593 break; 7594 7595 case Ovl_Overload: 7596 Redeclaration = false; 7597 break; 7598 } 7599 7600 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7601 // If a function name is overloadable in C, then every function 7602 // with that name must be marked "overloadable". 7603 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7604 << Redeclaration << NewFD; 7605 NamedDecl *OverloadedDecl = nullptr; 7606 if (Redeclaration) 7607 OverloadedDecl = OldDecl; 7608 else if (!Previous.empty()) 7609 OverloadedDecl = Previous.getRepresentativeDecl(); 7610 if (OverloadedDecl) 7611 Diag(OverloadedDecl->getLocation(), 7612 diag::note_attribute_overloadable_prev_overload); 7613 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7614 } 7615 } 7616 } 7617 7618 // Check for a previous extern "C" declaration with this name. 7619 if (!Redeclaration && 7620 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7621 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7622 if (!Previous.empty()) { 7623 // This is an extern "C" declaration with the same name as a previous 7624 // declaration, and thus redeclares that entity... 7625 Redeclaration = true; 7626 OldDecl = Previous.getFoundDecl(); 7627 MergeTypeWithPrevious = false; 7628 7629 // ... except in the presence of __attribute__((overloadable)). 7630 if (OldDecl->hasAttr<OverloadableAttr>()) { 7631 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7632 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7633 << Redeclaration << NewFD; 7634 Diag(Previous.getFoundDecl()->getLocation(), 7635 diag::note_attribute_overloadable_prev_overload); 7636 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7637 } 7638 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7639 Redeclaration = false; 7640 OldDecl = nullptr; 7641 } 7642 } 7643 } 7644 } 7645 7646 // C++11 [dcl.constexpr]p8: 7647 // A constexpr specifier for a non-static member function that is not 7648 // a constructor declares that member function to be const. 7649 // 7650 // This needs to be delayed until we know whether this is an out-of-line 7651 // definition of a static member function. 7652 // 7653 // This rule is not present in C++1y, so we produce a backwards 7654 // compatibility warning whenever it happens in C++11. 7655 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7656 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7657 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7658 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7659 CXXMethodDecl *OldMD = nullptr; 7660 if (OldDecl) 7661 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7662 if (!OldMD || !OldMD->isStatic()) { 7663 const FunctionProtoType *FPT = 7664 MD->getType()->castAs<FunctionProtoType>(); 7665 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7666 EPI.TypeQuals |= Qualifiers::Const; 7667 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7668 FPT->getParamTypes(), EPI)); 7669 7670 // Warn that we did this, if we're not performing template instantiation. 7671 // In that case, we'll have warned already when the template was defined. 7672 if (ActiveTemplateInstantiations.empty()) { 7673 SourceLocation AddConstLoc; 7674 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7675 .IgnoreParens().getAs<FunctionTypeLoc>()) 7676 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7677 7678 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7679 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7680 } 7681 } 7682 } 7683 7684 if (Redeclaration) { 7685 // NewFD and OldDecl represent declarations that need to be 7686 // merged. 7687 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7688 NewFD->setInvalidDecl(); 7689 return Redeclaration; 7690 } 7691 7692 Previous.clear(); 7693 Previous.addDecl(OldDecl); 7694 7695 if (FunctionTemplateDecl *OldTemplateDecl 7696 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7697 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7698 FunctionTemplateDecl *NewTemplateDecl 7699 = NewFD->getDescribedFunctionTemplate(); 7700 assert(NewTemplateDecl && "Template/non-template mismatch"); 7701 if (CXXMethodDecl *Method 7702 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7703 Method->setAccess(OldTemplateDecl->getAccess()); 7704 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7705 } 7706 7707 // If this is an explicit specialization of a member that is a function 7708 // template, mark it as a member specialization. 7709 if (IsExplicitSpecialization && 7710 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7711 NewTemplateDecl->setMemberSpecialization(); 7712 assert(OldTemplateDecl->isMemberSpecialization()); 7713 } 7714 7715 } else { 7716 // This needs to happen first so that 'inline' propagates. 7717 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7718 7719 if (isa<CXXMethodDecl>(NewFD)) { 7720 // A valid redeclaration of a C++ method must be out-of-line, 7721 // but (unfortunately) it's not necessarily a definition 7722 // because of templates, which means that the previous 7723 // declaration is not necessarily from the class definition. 7724 7725 // For just setting the access, that doesn't matter. 7726 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7727 NewFD->setAccess(oldMethod->getAccess()); 7728 7729 // Update the key-function state if necessary for this ABI. 7730 if (NewFD->isInlined() && 7731 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7732 // setNonKeyFunction needs to work with the original 7733 // declaration from the class definition, and isVirtual() is 7734 // just faster in that case, so map back to that now. 7735 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7736 if (oldMethod->isVirtual()) { 7737 Context.setNonKeyFunction(oldMethod); 7738 } 7739 } 7740 } 7741 } 7742 } 7743 7744 // Semantic checking for this function declaration (in isolation). 7745 if (getLangOpts().CPlusPlus) { 7746 // C++-specific checks. 7747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7748 CheckConstructor(Constructor); 7749 } else if (CXXDestructorDecl *Destructor = 7750 dyn_cast<CXXDestructorDecl>(NewFD)) { 7751 CXXRecordDecl *Record = Destructor->getParent(); 7752 QualType ClassType = Context.getTypeDeclType(Record); 7753 7754 // FIXME: Shouldn't we be able to perform this check even when the class 7755 // type is dependent? Both gcc and edg can handle that. 7756 if (!ClassType->isDependentType()) { 7757 DeclarationName Name 7758 = Context.DeclarationNames.getCXXDestructorName( 7759 Context.getCanonicalType(ClassType)); 7760 if (NewFD->getDeclName() != Name) { 7761 Diag(NewFD->getLocation(), diag::err_destructor_name); 7762 NewFD->setInvalidDecl(); 7763 return Redeclaration; 7764 } 7765 } 7766 } else if (CXXConversionDecl *Conversion 7767 = dyn_cast<CXXConversionDecl>(NewFD)) { 7768 ActOnConversionDeclarator(Conversion); 7769 } 7770 7771 // Find any virtual functions that this function overrides. 7772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7773 if (!Method->isFunctionTemplateSpecialization() && 7774 !Method->getDescribedFunctionTemplate() && 7775 Method->isCanonicalDecl()) { 7776 if (AddOverriddenMethods(Method->getParent(), Method)) { 7777 // If the function was marked as "static", we have a problem. 7778 if (NewFD->getStorageClass() == SC_Static) { 7779 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7780 } 7781 } 7782 } 7783 7784 if (Method->isStatic()) 7785 checkThisInStaticMemberFunctionType(Method); 7786 } 7787 7788 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7789 if (NewFD->isOverloadedOperator() && 7790 CheckOverloadedOperatorDeclaration(NewFD)) { 7791 NewFD->setInvalidDecl(); 7792 return Redeclaration; 7793 } 7794 7795 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7796 if (NewFD->getLiteralIdentifier() && 7797 CheckLiteralOperatorDeclaration(NewFD)) { 7798 NewFD->setInvalidDecl(); 7799 return Redeclaration; 7800 } 7801 7802 // In C++, check default arguments now that we have merged decls. Unless 7803 // the lexical context is the class, because in this case this is done 7804 // during delayed parsing anyway. 7805 if (!CurContext->isRecord()) 7806 CheckCXXDefaultArguments(NewFD); 7807 7808 // If this function declares a builtin function, check the type of this 7809 // declaration against the expected type for the builtin. 7810 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7811 ASTContext::GetBuiltinTypeError Error; 7812 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7813 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7814 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7815 // The type of this function differs from the type of the builtin, 7816 // so forget about the builtin entirely. 7817 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7818 } 7819 } 7820 7821 // If this function is declared as being extern "C", then check to see if 7822 // the function returns a UDT (class, struct, or union type) that is not C 7823 // compatible, and if it does, warn the user. 7824 // But, issue any diagnostic on the first declaration only. 7825 if (NewFD->isExternC() && Previous.empty()) { 7826 QualType R = NewFD->getReturnType(); 7827 if (R->isIncompleteType() && !R->isVoidType()) 7828 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7829 << NewFD << R; 7830 else if (!R.isPODType(Context) && !R->isVoidType() && 7831 !R->isObjCObjectPointerType()) 7832 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7833 } 7834 } 7835 return Redeclaration; 7836 } 7837 7838 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7839 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7840 if (!TSI) 7841 return SourceRange(); 7842 7843 TypeLoc TL = TSI->getTypeLoc(); 7844 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7845 if (!FunctionTL) 7846 return SourceRange(); 7847 7848 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7849 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7850 return ResultTL.getSourceRange(); 7851 7852 return SourceRange(); 7853 } 7854 7855 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7856 // C++11 [basic.start.main]p3: 7857 // A program that [...] declares main to be inline, static or 7858 // constexpr is ill-formed. 7859 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7860 // appear in a declaration of main. 7861 // static main is not an error under C99, but we should warn about it. 7862 // We accept _Noreturn main as an extension. 7863 if (FD->getStorageClass() == SC_Static) 7864 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7865 ? diag::err_static_main : diag::warn_static_main) 7866 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7867 if (FD->isInlineSpecified()) 7868 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7869 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7870 if (DS.isNoreturnSpecified()) { 7871 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7872 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 7873 Diag(NoreturnLoc, diag::ext_noreturn_main); 7874 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7875 << FixItHint::CreateRemoval(NoreturnRange); 7876 } 7877 if (FD->isConstexpr()) { 7878 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7879 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7880 FD->setConstexpr(false); 7881 } 7882 7883 if (getLangOpts().OpenCL) { 7884 Diag(FD->getLocation(), diag::err_opencl_no_main) 7885 << FD->hasAttr<OpenCLKernelAttr>(); 7886 FD->setInvalidDecl(); 7887 return; 7888 } 7889 7890 QualType T = FD->getType(); 7891 assert(T->isFunctionType() && "function decl is not of function type"); 7892 const FunctionType* FT = T->castAs<FunctionType>(); 7893 7894 // All the standards say that main() should should return 'int'. 7895 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7896 // In C and C++, main magically returns 0 if you fall off the end; 7897 // set the flag which tells us that. 7898 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7899 FD->setHasImplicitReturnZero(true); 7900 7901 // In C with GNU extensions we allow main() to have non-integer return 7902 // type, but we should warn about the extension, and we disable the 7903 // implicit-return-zero rule. 7904 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7905 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7906 7907 SourceRange ResultRange = getResultSourceRange(FD); 7908 if (ResultRange.isValid()) 7909 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7910 << FixItHint::CreateReplacement(ResultRange, "int"); 7911 7912 // Otherwise, this is just a flat-out error. 7913 } else { 7914 SourceRange ResultRange = getResultSourceRange(FD); 7915 if (ResultRange.isValid()) 7916 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7917 << FixItHint::CreateReplacement(ResultRange, "int"); 7918 else 7919 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7920 7921 FD->setInvalidDecl(true); 7922 } 7923 7924 // Treat protoless main() as nullary. 7925 if (isa<FunctionNoProtoType>(FT)) return; 7926 7927 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7928 unsigned nparams = FTP->getNumParams(); 7929 assert(FD->getNumParams() == nparams); 7930 7931 bool HasExtraParameters = (nparams > 3); 7932 7933 // Darwin passes an undocumented fourth argument of type char**. If 7934 // other platforms start sprouting these, the logic below will start 7935 // getting shifty. 7936 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7937 HasExtraParameters = false; 7938 7939 if (HasExtraParameters) { 7940 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7941 FD->setInvalidDecl(true); 7942 nparams = 3; 7943 } 7944 7945 // FIXME: a lot of the following diagnostics would be improved 7946 // if we had some location information about types. 7947 7948 QualType CharPP = 7949 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7950 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7951 7952 for (unsigned i = 0; i < nparams; ++i) { 7953 QualType AT = FTP->getParamType(i); 7954 7955 bool mismatch = true; 7956 7957 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7958 mismatch = false; 7959 else if (Expected[i] == CharPP) { 7960 // As an extension, the following forms are okay: 7961 // char const ** 7962 // char const * const * 7963 // char * const * 7964 7965 QualifierCollector qs; 7966 const PointerType* PT; 7967 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7968 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7969 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7970 Context.CharTy)) { 7971 qs.removeConst(); 7972 mismatch = !qs.empty(); 7973 } 7974 } 7975 7976 if (mismatch) { 7977 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7978 // TODO: suggest replacing given type with expected type 7979 FD->setInvalidDecl(true); 7980 } 7981 } 7982 7983 if (nparams == 1 && !FD->isInvalidDecl()) { 7984 Diag(FD->getLocation(), diag::warn_main_one_arg); 7985 } 7986 7987 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7988 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7989 FD->setInvalidDecl(); 7990 } 7991 } 7992 7993 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7994 QualType T = FD->getType(); 7995 assert(T->isFunctionType() && "function decl is not of function type"); 7996 const FunctionType *FT = T->castAs<FunctionType>(); 7997 7998 // Set an implicit return of 'zero' if the function can return some integral, 7999 // enumeration, pointer or nullptr type. 8000 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8001 FT->getReturnType()->isAnyPointerType() || 8002 FT->getReturnType()->isNullPtrType()) 8003 // DllMain is exempt because a return value of zero means it failed. 8004 if (FD->getName() != "DllMain") 8005 FD->setHasImplicitReturnZero(true); 8006 8007 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8008 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8009 FD->setInvalidDecl(); 8010 } 8011 } 8012 8013 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8014 // FIXME: Need strict checking. In C89, we need to check for 8015 // any assignment, increment, decrement, function-calls, or 8016 // commas outside of a sizeof. In C99, it's the same list, 8017 // except that the aforementioned are allowed in unevaluated 8018 // expressions. Everything else falls under the 8019 // "may accept other forms of constant expressions" exception. 8020 // (We never end up here for C++, so the constant expression 8021 // rules there don't matter.) 8022 const Expr *Culprit; 8023 if (Init->isConstantInitializer(Context, false, &Culprit)) 8024 return false; 8025 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8026 << Culprit->getSourceRange(); 8027 return true; 8028 } 8029 8030 namespace { 8031 // Visits an initialization expression to see if OrigDecl is evaluated in 8032 // its own initialization and throws a warning if it does. 8033 class SelfReferenceChecker 8034 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8035 Sema &S; 8036 Decl *OrigDecl; 8037 bool isRecordType; 8038 bool isPODType; 8039 bool isReferenceType; 8040 8041 public: 8042 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8043 8044 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8045 S(S), OrigDecl(OrigDecl) { 8046 isPODType = false; 8047 isRecordType = false; 8048 isReferenceType = false; 8049 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8050 isPODType = VD->getType().isPODType(S.Context); 8051 isRecordType = VD->getType()->isRecordType(); 8052 isReferenceType = VD->getType()->isReferenceType(); 8053 } 8054 } 8055 8056 // For most expressions, the cast is directly above the DeclRefExpr. 8057 // For conditional operators, the cast can be outside the conditional 8058 // operator if both expressions are DeclRefExpr's. 8059 void HandleValue(Expr *E) { 8060 if (isReferenceType) 8061 return; 8062 E = E->IgnoreParenImpCasts(); 8063 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8064 HandleDeclRefExpr(DRE); 8065 return; 8066 } 8067 8068 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8069 HandleValue(CO->getTrueExpr()); 8070 HandleValue(CO->getFalseExpr()); 8071 return; 8072 } 8073 8074 if (isa<MemberExpr>(E)) { 8075 Expr *Base = E->IgnoreParenImpCasts(); 8076 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8077 // Check for static member variables and don't warn on them. 8078 if (!isa<FieldDecl>(ME->getMemberDecl())) 8079 return; 8080 Base = ME->getBase()->IgnoreParenImpCasts(); 8081 } 8082 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8083 HandleDeclRefExpr(DRE); 8084 return; 8085 } 8086 } 8087 8088 // Reference types are handled here since all uses of references are 8089 // bad, not just r-value uses. 8090 void VisitDeclRefExpr(DeclRefExpr *E) { 8091 if (isReferenceType) 8092 HandleDeclRefExpr(E); 8093 } 8094 8095 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8096 if (E->getCastKind() == CK_LValueToRValue || 8097 (isRecordType && E->getCastKind() == CK_NoOp)) 8098 HandleValue(E->getSubExpr()); 8099 8100 Inherited::VisitImplicitCastExpr(E); 8101 } 8102 8103 void VisitMemberExpr(MemberExpr *E) { 8104 // Don't warn on arrays since they can be treated as pointers. 8105 if (E->getType()->canDecayToPointerType()) return; 8106 8107 // Warn when a non-static method call is followed by non-static member 8108 // field accesses, which is followed by a DeclRefExpr. 8109 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8110 bool Warn = (MD && !MD->isStatic()); 8111 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8112 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8113 if (!isa<FieldDecl>(ME->getMemberDecl())) 8114 Warn = false; 8115 Base = ME->getBase()->IgnoreParenImpCasts(); 8116 } 8117 8118 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8119 if (Warn) 8120 HandleDeclRefExpr(DRE); 8121 return; 8122 } 8123 8124 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8125 // Visit that expression. 8126 Visit(Base); 8127 } 8128 8129 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8130 if (E->getNumArgs() > 0) 8131 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8132 HandleDeclRefExpr(DRE); 8133 8134 Inherited::VisitCXXOperatorCallExpr(E); 8135 } 8136 8137 void VisitUnaryOperator(UnaryOperator *E) { 8138 // For POD record types, addresses of its own members are well-defined. 8139 if (E->getOpcode() == UO_AddrOf && isRecordType && 8140 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8141 if (!isPODType) 8142 HandleValue(E->getSubExpr()); 8143 return; 8144 } 8145 Inherited::VisitUnaryOperator(E); 8146 } 8147 8148 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8149 8150 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8151 Decl* ReferenceDecl = DRE->getDecl(); 8152 if (OrigDecl != ReferenceDecl) return; 8153 unsigned diag; 8154 if (isReferenceType) { 8155 diag = diag::warn_uninit_self_reference_in_reference_init; 8156 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8157 diag = diag::warn_static_self_reference_in_init; 8158 } else { 8159 diag = diag::warn_uninit_self_reference_in_init; 8160 } 8161 8162 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8163 S.PDiag(diag) 8164 << DRE->getNameInfo().getName() 8165 << OrigDecl->getLocation() 8166 << DRE->getSourceRange()); 8167 } 8168 }; 8169 8170 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8171 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8172 bool DirectInit) { 8173 // Parameters arguments are occassionially constructed with itself, 8174 // for instance, in recursive functions. Skip them. 8175 if (isa<ParmVarDecl>(OrigDecl)) 8176 return; 8177 8178 E = E->IgnoreParens(); 8179 8180 // Skip checking T a = a where T is not a record or reference type. 8181 // Doing so is a way to silence uninitialized warnings. 8182 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8183 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8184 if (ICE->getCastKind() == CK_LValueToRValue) 8185 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8186 if (DRE->getDecl() == OrigDecl) 8187 return; 8188 8189 SelfReferenceChecker(S, OrigDecl).Visit(E); 8190 } 8191 } 8192 8193 /// AddInitializerToDecl - Adds the initializer Init to the 8194 /// declaration dcl. If DirectInit is true, this is C++ direct 8195 /// initialization rather than copy initialization. 8196 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8197 bool DirectInit, bool TypeMayContainAuto) { 8198 // If there is no declaration, there was an error parsing it. Just ignore 8199 // the initializer. 8200 if (!RealDecl || RealDecl->isInvalidDecl()) 8201 return; 8202 8203 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8204 // With declarators parsed the way they are, the parser cannot 8205 // distinguish between a normal initializer and a pure-specifier. 8206 // Thus this grotesque test. 8207 IntegerLiteral *IL; 8208 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8209 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8210 CheckPureMethod(Method, Init->getSourceRange()); 8211 else { 8212 Diag(Method->getLocation(), diag::err_member_function_initialization) 8213 << Method->getDeclName() << Init->getSourceRange(); 8214 Method->setInvalidDecl(); 8215 } 8216 return; 8217 } 8218 8219 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8220 if (!VDecl) { 8221 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8222 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8223 RealDecl->setInvalidDecl(); 8224 return; 8225 } 8226 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8227 8228 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8229 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8230 Expr *DeduceInit = Init; 8231 // Initializer could be a C++ direct-initializer. Deduction only works if it 8232 // contains exactly one expression. 8233 if (CXXDirectInit) { 8234 if (CXXDirectInit->getNumExprs() == 0) { 8235 // It isn't possible to write this directly, but it is possible to 8236 // end up in this situation with "auto x(some_pack...);" 8237 Diag(CXXDirectInit->getLocStart(), 8238 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8239 : diag::err_auto_var_init_no_expression) 8240 << VDecl->getDeclName() << VDecl->getType() 8241 << VDecl->getSourceRange(); 8242 RealDecl->setInvalidDecl(); 8243 return; 8244 } else if (CXXDirectInit->getNumExprs() > 1) { 8245 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8246 VDecl->isInitCapture() 8247 ? diag::err_init_capture_multiple_expressions 8248 : diag::err_auto_var_init_multiple_expressions) 8249 << VDecl->getDeclName() << VDecl->getType() 8250 << VDecl->getSourceRange(); 8251 RealDecl->setInvalidDecl(); 8252 return; 8253 } else { 8254 DeduceInit = CXXDirectInit->getExpr(0); 8255 if (isa<InitListExpr>(DeduceInit)) 8256 Diag(CXXDirectInit->getLocStart(), 8257 diag::err_auto_var_init_paren_braces) 8258 << VDecl->getDeclName() << VDecl->getType() 8259 << VDecl->getSourceRange(); 8260 } 8261 } 8262 8263 // Expressions default to 'id' when we're in a debugger. 8264 bool DefaultedToAuto = false; 8265 if (getLangOpts().DebuggerCastResultToId && 8266 Init->getType() == Context.UnknownAnyTy) { 8267 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8268 if (Result.isInvalid()) { 8269 VDecl->setInvalidDecl(); 8270 return; 8271 } 8272 Init = Result.get(); 8273 DefaultedToAuto = true; 8274 } 8275 8276 QualType DeducedType; 8277 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8278 DAR_Failed) 8279 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8280 if (DeducedType.isNull()) { 8281 RealDecl->setInvalidDecl(); 8282 return; 8283 } 8284 VDecl->setType(DeducedType); 8285 assert(VDecl->isLinkageValid()); 8286 8287 // In ARC, infer lifetime. 8288 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8289 VDecl->setInvalidDecl(); 8290 8291 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8292 // 'id' instead of a specific object type prevents most of our usual checks. 8293 // We only want to warn outside of template instantiations, though: 8294 // inside a template, the 'id' could have come from a parameter. 8295 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8296 DeducedType->isObjCIdType()) { 8297 SourceLocation Loc = 8298 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8299 Diag(Loc, diag::warn_auto_var_is_id) 8300 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8301 } 8302 8303 // If this is a redeclaration, check that the type we just deduced matches 8304 // the previously declared type. 8305 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8306 // We never need to merge the type, because we cannot form an incomplete 8307 // array of auto, nor deduce such a type. 8308 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8309 } 8310 8311 // Check the deduced type is valid for a variable declaration. 8312 CheckVariableDeclarationType(VDecl); 8313 if (VDecl->isInvalidDecl()) 8314 return; 8315 } 8316 8317 // dllimport cannot be used on variable definitions. 8318 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8319 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8320 VDecl->setInvalidDecl(); 8321 return; 8322 } 8323 8324 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8325 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8326 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8327 VDecl->setInvalidDecl(); 8328 return; 8329 } 8330 8331 if (!VDecl->getType()->isDependentType()) { 8332 // A definition must end up with a complete type, which means it must be 8333 // complete with the restriction that an array type might be completed by 8334 // the initializer; note that later code assumes this restriction. 8335 QualType BaseDeclType = VDecl->getType(); 8336 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8337 BaseDeclType = Array->getElementType(); 8338 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8339 diag::err_typecheck_decl_incomplete_type)) { 8340 RealDecl->setInvalidDecl(); 8341 return; 8342 } 8343 8344 // The variable can not have an abstract class type. 8345 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8346 diag::err_abstract_type_in_decl, 8347 AbstractVariableType)) 8348 VDecl->setInvalidDecl(); 8349 } 8350 8351 const VarDecl *Def; 8352 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8353 Diag(VDecl->getLocation(), diag::err_redefinition) 8354 << VDecl->getDeclName(); 8355 Diag(Def->getLocation(), diag::note_previous_definition); 8356 VDecl->setInvalidDecl(); 8357 return; 8358 } 8359 8360 const VarDecl *PrevInit = nullptr; 8361 if (getLangOpts().CPlusPlus) { 8362 // C++ [class.static.data]p4 8363 // If a static data member is of const integral or const 8364 // enumeration type, its declaration in the class definition can 8365 // specify a constant-initializer which shall be an integral 8366 // constant expression (5.19). In that case, the member can appear 8367 // in integral constant expressions. The member shall still be 8368 // defined in a namespace scope if it is used in the program and the 8369 // namespace scope definition shall not contain an initializer. 8370 // 8371 // We already performed a redefinition check above, but for static 8372 // data members we also need to check whether there was an in-class 8373 // declaration with an initializer. 8374 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8375 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8376 << VDecl->getDeclName(); 8377 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8378 return; 8379 } 8380 8381 if (VDecl->hasLocalStorage()) 8382 getCurFunction()->setHasBranchProtectedScope(); 8383 8384 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8385 VDecl->setInvalidDecl(); 8386 return; 8387 } 8388 } 8389 8390 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8391 // a kernel function cannot be initialized." 8392 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8393 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8394 VDecl->setInvalidDecl(); 8395 return; 8396 } 8397 8398 // Get the decls type and save a reference for later, since 8399 // CheckInitializerTypes may change it. 8400 QualType DclT = VDecl->getType(), SavT = DclT; 8401 8402 // Expressions default to 'id' when we're in a debugger 8403 // and we are assigning it to a variable of Objective-C pointer type. 8404 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8405 Init->getType() == Context.UnknownAnyTy) { 8406 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8407 if (Result.isInvalid()) { 8408 VDecl->setInvalidDecl(); 8409 return; 8410 } 8411 Init = Result.get(); 8412 } 8413 8414 // Perform the initialization. 8415 if (!VDecl->isInvalidDecl()) { 8416 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8417 InitializationKind Kind 8418 = DirectInit ? 8419 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8420 Init->getLocStart(), 8421 Init->getLocEnd()) 8422 : InitializationKind::CreateDirectList( 8423 VDecl->getLocation()) 8424 : InitializationKind::CreateCopy(VDecl->getLocation(), 8425 Init->getLocStart()); 8426 8427 MultiExprArg Args = Init; 8428 if (CXXDirectInit) 8429 Args = MultiExprArg(CXXDirectInit->getExprs(), 8430 CXXDirectInit->getNumExprs()); 8431 8432 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8433 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8434 if (Result.isInvalid()) { 8435 VDecl->setInvalidDecl(); 8436 return; 8437 } 8438 8439 Init = Result.getAs<Expr>(); 8440 } 8441 8442 // Check for self-references within variable initializers. 8443 // Variables declared within a function/method body (except for references) 8444 // are handled by a dataflow analysis. 8445 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8446 VDecl->getType()->isReferenceType()) { 8447 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8448 } 8449 8450 // If the type changed, it means we had an incomplete type that was 8451 // completed by the initializer. For example: 8452 // int ary[] = { 1, 3, 5 }; 8453 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8454 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8455 VDecl->setType(DclT); 8456 8457 if (!VDecl->isInvalidDecl()) { 8458 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8459 8460 if (VDecl->hasAttr<BlocksAttr>()) 8461 checkRetainCycles(VDecl, Init); 8462 8463 // It is safe to assign a weak reference into a strong variable. 8464 // Although this code can still have problems: 8465 // id x = self.weakProp; 8466 // id y = self.weakProp; 8467 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8468 // paths through the function. This should be revisited if 8469 // -Wrepeated-use-of-weak is made flow-sensitive. 8470 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8471 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8472 Init->getLocStart())) 8473 getCurFunction()->markSafeWeakUse(Init); 8474 } 8475 8476 // The initialization is usually a full-expression. 8477 // 8478 // FIXME: If this is a braced initialization of an aggregate, it is not 8479 // an expression, and each individual field initializer is a separate 8480 // full-expression. For instance, in: 8481 // 8482 // struct Temp { ~Temp(); }; 8483 // struct S { S(Temp); }; 8484 // struct T { S a, b; } t = { Temp(), Temp() } 8485 // 8486 // we should destroy the first Temp before constructing the second. 8487 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8488 false, 8489 VDecl->isConstexpr()); 8490 if (Result.isInvalid()) { 8491 VDecl->setInvalidDecl(); 8492 return; 8493 } 8494 Init = Result.get(); 8495 8496 // Attach the initializer to the decl. 8497 VDecl->setInit(Init); 8498 8499 if (VDecl->isLocalVarDecl()) { 8500 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8501 // static storage duration shall be constant expressions or string literals. 8502 // C++ does not have this restriction. 8503 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8504 const Expr *Culprit; 8505 if (VDecl->getStorageClass() == SC_Static) 8506 CheckForConstantInitializer(Init, DclT); 8507 // C89 is stricter than C99 for non-static aggregate types. 8508 // C89 6.5.7p3: All the expressions [...] in an initializer list 8509 // for an object that has aggregate or union type shall be 8510 // constant expressions. 8511 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8512 isa<InitListExpr>(Init) && 8513 !Init->isConstantInitializer(Context, false, &Culprit)) 8514 Diag(Culprit->getExprLoc(), 8515 diag::ext_aggregate_init_not_constant) 8516 << Culprit->getSourceRange(); 8517 } 8518 } else if (VDecl->isStaticDataMember() && 8519 VDecl->getLexicalDeclContext()->isRecord()) { 8520 // This is an in-class initialization for a static data member, e.g., 8521 // 8522 // struct S { 8523 // static const int value = 17; 8524 // }; 8525 8526 // C++ [class.mem]p4: 8527 // A member-declarator can contain a constant-initializer only 8528 // if it declares a static member (9.4) of const integral or 8529 // const enumeration type, see 9.4.2. 8530 // 8531 // C++11 [class.static.data]p3: 8532 // If a non-volatile const static data member is of integral or 8533 // enumeration type, its declaration in the class definition can 8534 // specify a brace-or-equal-initializer in which every initalizer-clause 8535 // that is an assignment-expression is a constant expression. A static 8536 // data member of literal type can be declared in the class definition 8537 // with the constexpr specifier; if so, its declaration shall specify a 8538 // brace-or-equal-initializer in which every initializer-clause that is 8539 // an assignment-expression is a constant expression. 8540 8541 // Do nothing on dependent types. 8542 if (DclT->isDependentType()) { 8543 8544 // Allow any 'static constexpr' members, whether or not they are of literal 8545 // type. We separately check that every constexpr variable is of literal 8546 // type. 8547 } else if (VDecl->isConstexpr()) { 8548 8549 // Require constness. 8550 } else if (!DclT.isConstQualified()) { 8551 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8552 << Init->getSourceRange(); 8553 VDecl->setInvalidDecl(); 8554 8555 // We allow integer constant expressions in all cases. 8556 } else if (DclT->isIntegralOrEnumerationType()) { 8557 // Check whether the expression is a constant expression. 8558 SourceLocation Loc; 8559 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8560 // In C++11, a non-constexpr const static data member with an 8561 // in-class initializer cannot be volatile. 8562 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8563 else if (Init->isValueDependent()) 8564 ; // Nothing to check. 8565 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8566 ; // Ok, it's an ICE! 8567 else if (Init->isEvaluatable(Context)) { 8568 // If we can constant fold the initializer through heroics, accept it, 8569 // but report this as a use of an extension for -pedantic. 8570 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8571 << Init->getSourceRange(); 8572 } else { 8573 // Otherwise, this is some crazy unknown case. Report the issue at the 8574 // location provided by the isIntegerConstantExpr failed check. 8575 Diag(Loc, diag::err_in_class_initializer_non_constant) 8576 << Init->getSourceRange(); 8577 VDecl->setInvalidDecl(); 8578 } 8579 8580 // We allow foldable floating-point constants as an extension. 8581 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8582 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8583 // it anyway and provide a fixit to add the 'constexpr'. 8584 if (getLangOpts().CPlusPlus11) { 8585 Diag(VDecl->getLocation(), 8586 diag::ext_in_class_initializer_float_type_cxx11) 8587 << DclT << Init->getSourceRange(); 8588 Diag(VDecl->getLocStart(), 8589 diag::note_in_class_initializer_float_type_cxx11) 8590 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8591 } else { 8592 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8593 << DclT << Init->getSourceRange(); 8594 8595 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8596 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8597 << Init->getSourceRange(); 8598 VDecl->setInvalidDecl(); 8599 } 8600 } 8601 8602 // Suggest adding 'constexpr' in C++11 for literal types. 8603 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8604 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8605 << DclT << Init->getSourceRange() 8606 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8607 VDecl->setConstexpr(true); 8608 8609 } else { 8610 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8611 << DclT << Init->getSourceRange(); 8612 VDecl->setInvalidDecl(); 8613 } 8614 } else if (VDecl->isFileVarDecl()) { 8615 if (VDecl->getStorageClass() == SC_Extern && 8616 (!getLangOpts().CPlusPlus || 8617 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8618 VDecl->isExternC())) && 8619 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8620 Diag(VDecl->getLocation(), diag::warn_extern_init); 8621 8622 // C99 6.7.8p4. All file scoped initializers need to be constant. 8623 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8624 CheckForConstantInitializer(Init, DclT); 8625 } 8626 8627 // We will represent direct-initialization similarly to copy-initialization: 8628 // int x(1); -as-> int x = 1; 8629 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8630 // 8631 // Clients that want to distinguish between the two forms, can check for 8632 // direct initializer using VarDecl::getInitStyle(). 8633 // A major benefit is that clients that don't particularly care about which 8634 // exactly form was it (like the CodeGen) can handle both cases without 8635 // special case code. 8636 8637 // C++ 8.5p11: 8638 // The form of initialization (using parentheses or '=') is generally 8639 // insignificant, but does matter when the entity being initialized has a 8640 // class type. 8641 if (CXXDirectInit) { 8642 assert(DirectInit && "Call-style initializer must be direct init."); 8643 VDecl->setInitStyle(VarDecl::CallInit); 8644 } else if (DirectInit) { 8645 // This must be list-initialization. No other way is direct-initialization. 8646 VDecl->setInitStyle(VarDecl::ListInit); 8647 } 8648 8649 CheckCompleteVariableDeclaration(VDecl); 8650 } 8651 8652 /// ActOnInitializerError - Given that there was an error parsing an 8653 /// initializer for the given declaration, try to return to some form 8654 /// of sanity. 8655 void Sema::ActOnInitializerError(Decl *D) { 8656 // Our main concern here is re-establishing invariants like "a 8657 // variable's type is either dependent or complete". 8658 if (!D || D->isInvalidDecl()) return; 8659 8660 VarDecl *VD = dyn_cast<VarDecl>(D); 8661 if (!VD) return; 8662 8663 // Auto types are meaningless if we can't make sense of the initializer. 8664 if (ParsingInitForAutoVars.count(D)) { 8665 D->setInvalidDecl(); 8666 return; 8667 } 8668 8669 QualType Ty = VD->getType(); 8670 if (Ty->isDependentType()) return; 8671 8672 // Require a complete type. 8673 if (RequireCompleteType(VD->getLocation(), 8674 Context.getBaseElementType(Ty), 8675 diag::err_typecheck_decl_incomplete_type)) { 8676 VD->setInvalidDecl(); 8677 return; 8678 } 8679 8680 // Require a non-abstract type. 8681 if (RequireNonAbstractType(VD->getLocation(), Ty, 8682 diag::err_abstract_type_in_decl, 8683 AbstractVariableType)) { 8684 VD->setInvalidDecl(); 8685 return; 8686 } 8687 8688 // Don't bother complaining about constructors or destructors, 8689 // though. 8690 } 8691 8692 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8693 bool TypeMayContainAuto) { 8694 // If there is no declaration, there was an error parsing it. Just ignore it. 8695 if (!RealDecl) 8696 return; 8697 8698 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8699 QualType Type = Var->getType(); 8700 8701 // C++11 [dcl.spec.auto]p3 8702 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8703 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8704 << Var->getDeclName() << Type; 8705 Var->setInvalidDecl(); 8706 return; 8707 } 8708 8709 // C++11 [class.static.data]p3: A static data member can be declared with 8710 // the constexpr specifier; if so, its declaration shall specify 8711 // a brace-or-equal-initializer. 8712 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8713 // the definition of a variable [...] or the declaration of a static data 8714 // member. 8715 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8716 if (Var->isStaticDataMember()) 8717 Diag(Var->getLocation(), 8718 diag::err_constexpr_static_mem_var_requires_init) 8719 << Var->getDeclName(); 8720 else 8721 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8722 Var->setInvalidDecl(); 8723 return; 8724 } 8725 8726 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8727 // be initialized. 8728 if (!Var->isInvalidDecl() && 8729 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8730 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8731 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8732 Var->setInvalidDecl(); 8733 return; 8734 } 8735 8736 switch (Var->isThisDeclarationADefinition()) { 8737 case VarDecl::Definition: 8738 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8739 break; 8740 8741 // We have an out-of-line definition of a static data member 8742 // that has an in-class initializer, so we type-check this like 8743 // a declaration. 8744 // 8745 // Fall through 8746 8747 case VarDecl::DeclarationOnly: 8748 // It's only a declaration. 8749 8750 // Block scope. C99 6.7p7: If an identifier for an object is 8751 // declared with no linkage (C99 6.2.2p6), the type for the 8752 // object shall be complete. 8753 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8754 !Var->hasLinkage() && !Var->isInvalidDecl() && 8755 RequireCompleteType(Var->getLocation(), Type, 8756 diag::err_typecheck_decl_incomplete_type)) 8757 Var->setInvalidDecl(); 8758 8759 // Make sure that the type is not abstract. 8760 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8761 RequireNonAbstractType(Var->getLocation(), Type, 8762 diag::err_abstract_type_in_decl, 8763 AbstractVariableType)) 8764 Var->setInvalidDecl(); 8765 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8766 Var->getStorageClass() == SC_PrivateExtern) { 8767 Diag(Var->getLocation(), diag::warn_private_extern); 8768 Diag(Var->getLocation(), diag::note_private_extern); 8769 } 8770 8771 return; 8772 8773 case VarDecl::TentativeDefinition: 8774 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8775 // object that has file scope without an initializer, and without a 8776 // storage-class specifier or with the storage-class specifier "static", 8777 // constitutes a tentative definition. Note: A tentative definition with 8778 // external linkage is valid (C99 6.2.2p5). 8779 if (!Var->isInvalidDecl()) { 8780 if (const IncompleteArrayType *ArrayT 8781 = Context.getAsIncompleteArrayType(Type)) { 8782 if (RequireCompleteType(Var->getLocation(), 8783 ArrayT->getElementType(), 8784 diag::err_illegal_decl_array_incomplete_type)) 8785 Var->setInvalidDecl(); 8786 } else if (Var->getStorageClass() == SC_Static) { 8787 // C99 6.9.2p3: If the declaration of an identifier for an object is 8788 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8789 // declared type shall not be an incomplete type. 8790 // NOTE: code such as the following 8791 // static struct s; 8792 // struct s { int a; }; 8793 // is accepted by gcc. Hence here we issue a warning instead of 8794 // an error and we do not invalidate the static declaration. 8795 // NOTE: to avoid multiple warnings, only check the first declaration. 8796 if (Var->isFirstDecl()) 8797 RequireCompleteType(Var->getLocation(), Type, 8798 diag::ext_typecheck_decl_incomplete_type); 8799 } 8800 } 8801 8802 // Record the tentative definition; we're done. 8803 if (!Var->isInvalidDecl()) 8804 TentativeDefinitions.push_back(Var); 8805 return; 8806 } 8807 8808 // Provide a specific diagnostic for uninitialized variable 8809 // definitions with incomplete array type. 8810 if (Type->isIncompleteArrayType()) { 8811 Diag(Var->getLocation(), 8812 diag::err_typecheck_incomplete_array_needs_initializer); 8813 Var->setInvalidDecl(); 8814 return; 8815 } 8816 8817 // Provide a specific diagnostic for uninitialized variable 8818 // definitions with reference type. 8819 if (Type->isReferenceType()) { 8820 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8821 << Var->getDeclName() 8822 << SourceRange(Var->getLocation(), Var->getLocation()); 8823 Var->setInvalidDecl(); 8824 return; 8825 } 8826 8827 // Do not attempt to type-check the default initializer for a 8828 // variable with dependent type. 8829 if (Type->isDependentType()) 8830 return; 8831 8832 if (Var->isInvalidDecl()) 8833 return; 8834 8835 if (RequireCompleteType(Var->getLocation(), 8836 Context.getBaseElementType(Type), 8837 diag::err_typecheck_decl_incomplete_type)) { 8838 Var->setInvalidDecl(); 8839 return; 8840 } 8841 8842 // The variable can not have an abstract class type. 8843 if (RequireNonAbstractType(Var->getLocation(), Type, 8844 diag::err_abstract_type_in_decl, 8845 AbstractVariableType)) { 8846 Var->setInvalidDecl(); 8847 return; 8848 } 8849 8850 // Check for jumps past the implicit initializer. C++0x 8851 // clarifies that this applies to a "variable with automatic 8852 // storage duration", not a "local variable". 8853 // C++11 [stmt.dcl]p3 8854 // A program that jumps from a point where a variable with automatic 8855 // storage duration is not in scope to a point where it is in scope is 8856 // ill-formed unless the variable has scalar type, class type with a 8857 // trivial default constructor and a trivial destructor, a cv-qualified 8858 // version of one of these types, or an array of one of the preceding 8859 // types and is declared without an initializer. 8860 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8861 if (const RecordType *Record 8862 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8863 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8864 // Mark the function for further checking even if the looser rules of 8865 // C++11 do not require such checks, so that we can diagnose 8866 // incompatibilities with C++98. 8867 if (!CXXRecord->isPOD()) 8868 getCurFunction()->setHasBranchProtectedScope(); 8869 } 8870 } 8871 8872 // C++03 [dcl.init]p9: 8873 // If no initializer is specified for an object, and the 8874 // object is of (possibly cv-qualified) non-POD class type (or 8875 // array thereof), the object shall be default-initialized; if 8876 // the object is of const-qualified type, the underlying class 8877 // type shall have a user-declared default 8878 // constructor. Otherwise, if no initializer is specified for 8879 // a non- static object, the object and its subobjects, if 8880 // any, have an indeterminate initial value); if the object 8881 // or any of its subobjects are of const-qualified type, the 8882 // program is ill-formed. 8883 // C++0x [dcl.init]p11: 8884 // If no initializer is specified for an object, the object is 8885 // default-initialized; [...]. 8886 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8887 InitializationKind Kind 8888 = InitializationKind::CreateDefault(Var->getLocation()); 8889 8890 InitializationSequence InitSeq(*this, Entity, Kind, None); 8891 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8892 if (Init.isInvalid()) 8893 Var->setInvalidDecl(); 8894 else if (Init.get()) { 8895 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8896 // This is important for template substitution. 8897 Var->setInitStyle(VarDecl::CallInit); 8898 } 8899 8900 CheckCompleteVariableDeclaration(Var); 8901 } 8902 } 8903 8904 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8905 VarDecl *VD = dyn_cast<VarDecl>(D); 8906 if (!VD) { 8907 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8908 D->setInvalidDecl(); 8909 return; 8910 } 8911 8912 VD->setCXXForRangeDecl(true); 8913 8914 // for-range-declaration cannot be given a storage class specifier. 8915 int Error = -1; 8916 switch (VD->getStorageClass()) { 8917 case SC_None: 8918 break; 8919 case SC_Extern: 8920 Error = 0; 8921 break; 8922 case SC_Static: 8923 Error = 1; 8924 break; 8925 case SC_PrivateExtern: 8926 Error = 2; 8927 break; 8928 case SC_Auto: 8929 Error = 3; 8930 break; 8931 case SC_Register: 8932 Error = 4; 8933 break; 8934 case SC_OpenCLWorkGroupLocal: 8935 llvm_unreachable("Unexpected storage class"); 8936 } 8937 if (VD->isConstexpr()) 8938 Error = 5; 8939 if (Error != -1) { 8940 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8941 << VD->getDeclName() << Error; 8942 D->setInvalidDecl(); 8943 } 8944 } 8945 8946 StmtResult 8947 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 8948 IdentifierInfo *Ident, 8949 ParsedAttributes &Attrs, 8950 SourceLocation AttrEnd) { 8951 // C++1y [stmt.iter]p1: 8952 // A range-based for statement of the form 8953 // for ( for-range-identifier : for-range-initializer ) statement 8954 // is equivalent to 8955 // for ( auto&& for-range-identifier : for-range-initializer ) statement 8956 DeclSpec DS(Attrs.getPool().getFactory()); 8957 8958 const char *PrevSpec; 8959 unsigned DiagID; 8960 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 8961 getPrintingPolicy()); 8962 8963 Declarator D(DS, Declarator::ForContext); 8964 D.SetIdentifier(Ident, IdentLoc); 8965 D.takeAttributes(Attrs, AttrEnd); 8966 8967 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 8968 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 8969 EmptyAttrs, IdentLoc); 8970 Decl *Var = ActOnDeclarator(S, D); 8971 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 8972 FinalizeDeclaration(Var); 8973 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 8974 AttrEnd.isValid() ? AttrEnd : IdentLoc); 8975 } 8976 8977 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8978 if (var->isInvalidDecl()) return; 8979 8980 // In ARC, don't allow jumps past the implicit initialization of a 8981 // local retaining variable. 8982 if (getLangOpts().ObjCAutoRefCount && 8983 var->hasLocalStorage()) { 8984 switch (var->getType().getObjCLifetime()) { 8985 case Qualifiers::OCL_None: 8986 case Qualifiers::OCL_ExplicitNone: 8987 case Qualifiers::OCL_Autoreleasing: 8988 break; 8989 8990 case Qualifiers::OCL_Weak: 8991 case Qualifiers::OCL_Strong: 8992 getCurFunction()->setHasBranchProtectedScope(); 8993 break; 8994 } 8995 } 8996 8997 // Warn about externally-visible variables being defined without a 8998 // prior declaration. We only want to do this for global 8999 // declarations, but we also specifically need to avoid doing it for 9000 // class members because the linkage of an anonymous class can 9001 // change if it's later given a typedef name. 9002 if (var->isThisDeclarationADefinition() && 9003 var->getDeclContext()->getRedeclContext()->isFileContext() && 9004 var->isExternallyVisible() && var->hasLinkage() && 9005 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9006 var->getLocation())) { 9007 // Find a previous declaration that's not a definition. 9008 VarDecl *prev = var->getPreviousDecl(); 9009 while (prev && prev->isThisDeclarationADefinition()) 9010 prev = prev->getPreviousDecl(); 9011 9012 if (!prev) 9013 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9014 } 9015 9016 if (var->getTLSKind() == VarDecl::TLS_Static) { 9017 const Expr *Culprit; 9018 if (var->getType().isDestructedType()) { 9019 // GNU C++98 edits for __thread, [basic.start.term]p3: 9020 // The type of an object with thread storage duration shall not 9021 // have a non-trivial destructor. 9022 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9023 if (getLangOpts().CPlusPlus11) 9024 Diag(var->getLocation(), diag::note_use_thread_local); 9025 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9026 !var->getInit()->isConstantInitializer( 9027 Context, var->getType()->isReferenceType(), &Culprit)) { 9028 // GNU C++98 edits for __thread, [basic.start.init]p4: 9029 // An object of thread storage duration shall not require dynamic 9030 // initialization. 9031 // FIXME: Need strict checking here. 9032 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9033 << Culprit->getSourceRange(); 9034 if (getLangOpts().CPlusPlus11) 9035 Diag(var->getLocation(), diag::note_use_thread_local); 9036 } 9037 9038 } 9039 9040 if (var->isThisDeclarationADefinition() && 9041 ActiveTemplateInstantiations.empty()) { 9042 PragmaStack<StringLiteral *> *Stack = nullptr; 9043 int SectionFlags = PSF_Implicit | PSF_Read; 9044 if (var->getType().isConstQualified()) 9045 Stack = &ConstSegStack; 9046 else if (!var->getInit()) { 9047 Stack = &BSSSegStack; 9048 SectionFlags |= PSF_Write; 9049 } else { 9050 Stack = &DataSegStack; 9051 SectionFlags |= PSF_Write; 9052 } 9053 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9054 var->addAttr( 9055 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9056 Stack->CurrentValue->getString(), 9057 Stack->CurrentPragmaLocation)); 9058 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9059 if (UnifySection(SA->getName(), SectionFlags, var)) 9060 var->dropAttr<SectionAttr>(); 9061 } 9062 9063 // All the following checks are C++ only. 9064 if (!getLangOpts().CPlusPlus) return; 9065 9066 QualType type = var->getType(); 9067 if (type->isDependentType()) return; 9068 9069 // __block variables might require us to capture a copy-initializer. 9070 if (var->hasAttr<BlocksAttr>()) { 9071 // It's currently invalid to ever have a __block variable with an 9072 // array type; should we diagnose that here? 9073 9074 // Regardless, we don't want to ignore array nesting when 9075 // constructing this copy. 9076 if (type->isStructureOrClassType()) { 9077 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9078 SourceLocation poi = var->getLocation(); 9079 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9080 ExprResult result 9081 = PerformMoveOrCopyInitialization( 9082 InitializedEntity::InitializeBlock(poi, type, false), 9083 var, var->getType(), varRef, /*AllowNRVO=*/true); 9084 if (!result.isInvalid()) { 9085 result = MaybeCreateExprWithCleanups(result); 9086 Expr *init = result.getAs<Expr>(); 9087 Context.setBlockVarCopyInits(var, init); 9088 } 9089 } 9090 } 9091 9092 Expr *Init = var->getInit(); 9093 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9094 QualType baseType = Context.getBaseElementType(type); 9095 9096 if (!var->getDeclContext()->isDependentContext() && 9097 Init && !Init->isValueDependent()) { 9098 if (IsGlobal && !var->isConstexpr() && 9099 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9100 var->getLocation())) { 9101 // Warn about globals which don't have a constant initializer. Don't 9102 // warn about globals with a non-trivial destructor because we already 9103 // warned about them. 9104 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9105 if (!(RD && !RD->hasTrivialDestructor()) && 9106 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9107 Diag(var->getLocation(), diag::warn_global_constructor) 9108 << Init->getSourceRange(); 9109 } 9110 9111 if (var->isConstexpr()) { 9112 SmallVector<PartialDiagnosticAt, 8> Notes; 9113 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9114 SourceLocation DiagLoc = var->getLocation(); 9115 // If the note doesn't add any useful information other than a source 9116 // location, fold it into the primary diagnostic. 9117 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9118 diag::note_invalid_subexpr_in_const_expr) { 9119 DiagLoc = Notes[0].first; 9120 Notes.clear(); 9121 } 9122 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9123 << var << Init->getSourceRange(); 9124 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9125 Diag(Notes[I].first, Notes[I].second); 9126 } 9127 } else if (var->isUsableInConstantExpressions(Context)) { 9128 // Check whether the initializer of a const variable of integral or 9129 // enumeration type is an ICE now, since we can't tell whether it was 9130 // initialized by a constant expression if we check later. 9131 var->checkInitIsICE(); 9132 } 9133 } 9134 9135 // Require the destructor. 9136 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9137 FinalizeVarWithDestructor(var, recordType); 9138 } 9139 9140 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9141 /// any semantic actions necessary after any initializer has been attached. 9142 void 9143 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9144 // Note that we are no longer parsing the initializer for this declaration. 9145 ParsingInitForAutoVars.erase(ThisDecl); 9146 9147 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9148 if (!VD) 9149 return; 9150 9151 checkAttributesAfterMerging(*this, *VD); 9152 9153 // Static locals inherit dll attributes from their function. 9154 if (VD->isStaticLocal()) { 9155 if (FunctionDecl *FD = 9156 dyn_cast<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9157 if (Attr *A = getDLLAttr(FD)) { 9158 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9159 NewAttr->setInherited(true); 9160 VD->addAttr(NewAttr); 9161 } 9162 } 9163 } 9164 9165 // Imported static data members cannot be defined out-of-line. 9166 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) { 9167 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9168 VD->isThisDeclarationADefinition()) { 9169 // We allow definitions of dllimport class template static data members 9170 // with a warning. 9171 CXXRecordDecl *Context = 9172 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9173 bool IsClassTemplateMember = 9174 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9175 Context->getDescribedClassTemplate(); 9176 9177 Diag(VD->getLocation(), 9178 IsClassTemplateMember 9179 ? diag::warn_attribute_dllimport_static_field_definition 9180 : diag::err_attribute_dllimport_static_field_definition); 9181 Diag(IA->getLocation(), diag::note_attribute); 9182 if (!IsClassTemplateMember) 9183 VD->setInvalidDecl(); 9184 } 9185 } 9186 9187 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9188 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9189 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9190 VD->dropAttr<UsedAttr>(); 9191 } 9192 } 9193 9194 if (!VD->isInvalidDecl() && 9195 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9196 if (const VarDecl *Def = VD->getDefinition()) { 9197 if (Def->hasAttr<AliasAttr>()) { 9198 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9199 << VD->getDeclName(); 9200 Diag(Def->getLocation(), diag::note_previous_definition); 9201 VD->setInvalidDecl(); 9202 } 9203 } 9204 } 9205 9206 const DeclContext *DC = VD->getDeclContext(); 9207 // If there's a #pragma GCC visibility in scope, and this isn't a class 9208 // member, set the visibility of this variable. 9209 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9210 AddPushedVisibilityAttribute(VD); 9211 9212 // FIXME: Warn on unused templates. 9213 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9214 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9215 MarkUnusedFileScopedDecl(VD); 9216 9217 // Now we have parsed the initializer and can update the table of magic 9218 // tag values. 9219 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9220 !VD->getType()->isIntegralOrEnumerationType()) 9221 return; 9222 9223 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9224 const Expr *MagicValueExpr = VD->getInit(); 9225 if (!MagicValueExpr) { 9226 continue; 9227 } 9228 llvm::APSInt MagicValueInt; 9229 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9230 Diag(I->getRange().getBegin(), 9231 diag::err_type_tag_for_datatype_not_ice) 9232 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9233 continue; 9234 } 9235 if (MagicValueInt.getActiveBits() > 64) { 9236 Diag(I->getRange().getBegin(), 9237 diag::err_type_tag_for_datatype_too_large) 9238 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9239 continue; 9240 } 9241 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9242 RegisterTypeTagForDatatype(I->getArgumentKind(), 9243 MagicValue, 9244 I->getMatchingCType(), 9245 I->getLayoutCompatible(), 9246 I->getMustBeNull()); 9247 } 9248 } 9249 9250 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9251 ArrayRef<Decl *> Group) { 9252 SmallVector<Decl*, 8> Decls; 9253 9254 if (DS.isTypeSpecOwned()) 9255 Decls.push_back(DS.getRepAsDecl()); 9256 9257 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9258 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9259 if (Decl *D = Group[i]) { 9260 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9261 if (!FirstDeclaratorInGroup) 9262 FirstDeclaratorInGroup = DD; 9263 Decls.push_back(D); 9264 } 9265 9266 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9267 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9268 HandleTagNumbering(*this, Tag, S); 9269 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9270 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9271 } 9272 } 9273 9274 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9275 } 9276 9277 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9278 /// group, performing any necessary semantic checking. 9279 Sema::DeclGroupPtrTy 9280 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9281 bool TypeMayContainAuto) { 9282 // C++0x [dcl.spec.auto]p7: 9283 // If the type deduced for the template parameter U is not the same in each 9284 // deduction, the program is ill-formed. 9285 // FIXME: When initializer-list support is added, a distinction is needed 9286 // between the deduced type U and the deduced type which 'auto' stands for. 9287 // auto a = 0, b = { 1, 2, 3 }; 9288 // is legal because the deduced type U is 'int' in both cases. 9289 if (TypeMayContainAuto && Group.size() > 1) { 9290 QualType Deduced; 9291 CanQualType DeducedCanon; 9292 VarDecl *DeducedDecl = nullptr; 9293 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9294 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9295 AutoType *AT = D->getType()->getContainedAutoType(); 9296 // Don't reissue diagnostics when instantiating a template. 9297 if (AT && D->isInvalidDecl()) 9298 break; 9299 QualType U = AT ? AT->getDeducedType() : QualType(); 9300 if (!U.isNull()) { 9301 CanQualType UCanon = Context.getCanonicalType(U); 9302 if (Deduced.isNull()) { 9303 Deduced = U; 9304 DeducedCanon = UCanon; 9305 DeducedDecl = D; 9306 } else if (DeducedCanon != UCanon) { 9307 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9308 diag::err_auto_different_deductions) 9309 << (AT->isDecltypeAuto() ? 1 : 0) 9310 << Deduced << DeducedDecl->getDeclName() 9311 << U << D->getDeclName() 9312 << DeducedDecl->getInit()->getSourceRange() 9313 << D->getInit()->getSourceRange(); 9314 D->setInvalidDecl(); 9315 break; 9316 } 9317 } 9318 } 9319 } 9320 } 9321 9322 ActOnDocumentableDecls(Group); 9323 9324 return DeclGroupPtrTy::make( 9325 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9326 } 9327 9328 void Sema::ActOnDocumentableDecl(Decl *D) { 9329 ActOnDocumentableDecls(D); 9330 } 9331 9332 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9333 // Don't parse the comment if Doxygen diagnostics are ignored. 9334 if (Group.empty() || !Group[0]) 9335 return; 9336 9337 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9338 return; 9339 9340 if (Group.size() >= 2) { 9341 // This is a decl group. Normally it will contain only declarations 9342 // produced from declarator list. But in case we have any definitions or 9343 // additional declaration references: 9344 // 'typedef struct S {} S;' 9345 // 'typedef struct S *S;' 9346 // 'struct S *pS;' 9347 // FinalizeDeclaratorGroup adds these as separate declarations. 9348 Decl *MaybeTagDecl = Group[0]; 9349 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9350 Group = Group.slice(1); 9351 } 9352 } 9353 9354 // See if there are any new comments that are not attached to a decl. 9355 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9356 if (!Comments.empty() && 9357 !Comments.back()->isAttached()) { 9358 // There is at least one comment that not attached to a decl. 9359 // Maybe it should be attached to one of these decls? 9360 // 9361 // Note that this way we pick up not only comments that precede the 9362 // declaration, but also comments that *follow* the declaration -- thanks to 9363 // the lookahead in the lexer: we've consumed the semicolon and looked 9364 // ahead through comments. 9365 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9366 Context.getCommentForDecl(Group[i], &PP); 9367 } 9368 } 9369 9370 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9371 /// to introduce parameters into function prototype scope. 9372 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9373 const DeclSpec &DS = D.getDeclSpec(); 9374 9375 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9376 9377 // C++03 [dcl.stc]p2 also permits 'auto'. 9378 VarDecl::StorageClass StorageClass = SC_None; 9379 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9380 StorageClass = SC_Register; 9381 } else if (getLangOpts().CPlusPlus && 9382 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9383 StorageClass = SC_Auto; 9384 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9385 Diag(DS.getStorageClassSpecLoc(), 9386 diag::err_invalid_storage_class_in_func_decl); 9387 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9388 } 9389 9390 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9391 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9392 << DeclSpec::getSpecifierName(TSCS); 9393 if (DS.isConstexprSpecified()) 9394 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9395 << 0; 9396 9397 DiagnoseFunctionSpecifiers(DS); 9398 9399 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9400 QualType parmDeclType = TInfo->getType(); 9401 9402 if (getLangOpts().CPlusPlus) { 9403 // Check that there are no default arguments inside the type of this 9404 // parameter. 9405 CheckExtraCXXDefaultArguments(D); 9406 9407 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9408 if (D.getCXXScopeSpec().isSet()) { 9409 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9410 << D.getCXXScopeSpec().getRange(); 9411 D.getCXXScopeSpec().clear(); 9412 } 9413 } 9414 9415 // Ensure we have a valid name 9416 IdentifierInfo *II = nullptr; 9417 if (D.hasName()) { 9418 II = D.getIdentifier(); 9419 if (!II) { 9420 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9421 << GetNameForDeclarator(D).getName(); 9422 D.setInvalidType(true); 9423 } 9424 } 9425 9426 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9427 if (II) { 9428 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9429 ForRedeclaration); 9430 LookupName(R, S); 9431 if (R.isSingleResult()) { 9432 NamedDecl *PrevDecl = R.getFoundDecl(); 9433 if (PrevDecl->isTemplateParameter()) { 9434 // Maybe we will complain about the shadowed template parameter. 9435 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9436 // Just pretend that we didn't see the previous declaration. 9437 PrevDecl = nullptr; 9438 } else if (S->isDeclScope(PrevDecl)) { 9439 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9440 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9441 9442 // Recover by removing the name 9443 II = nullptr; 9444 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9445 D.setInvalidType(true); 9446 } 9447 } 9448 } 9449 9450 // Temporarily put parameter variables in the translation unit, not 9451 // the enclosing context. This prevents them from accidentally 9452 // looking like class members in C++. 9453 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9454 D.getLocStart(), 9455 D.getIdentifierLoc(), II, 9456 parmDeclType, TInfo, 9457 StorageClass); 9458 9459 if (D.isInvalidType()) 9460 New->setInvalidDecl(); 9461 9462 assert(S->isFunctionPrototypeScope()); 9463 assert(S->getFunctionPrototypeDepth() >= 1); 9464 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9465 S->getNextFunctionPrototypeIndex()); 9466 9467 // Add the parameter declaration into this scope. 9468 S->AddDecl(New); 9469 if (II) 9470 IdResolver.AddDecl(New); 9471 9472 ProcessDeclAttributes(S, New, D); 9473 9474 if (D.getDeclSpec().isModulePrivateSpecified()) 9475 Diag(New->getLocation(), diag::err_module_private_local) 9476 << 1 << New->getDeclName() 9477 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9478 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9479 9480 if (New->hasAttr<BlocksAttr>()) { 9481 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9482 } 9483 return New; 9484 } 9485 9486 /// \brief Synthesizes a variable for a parameter arising from a 9487 /// typedef. 9488 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9489 SourceLocation Loc, 9490 QualType T) { 9491 /* FIXME: setting StartLoc == Loc. 9492 Would it be worth to modify callers so as to provide proper source 9493 location for the unnamed parameters, embedding the parameter's type? */ 9494 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9495 T, Context.getTrivialTypeSourceInfo(T, Loc), 9496 SC_None, nullptr); 9497 Param->setImplicit(); 9498 return Param; 9499 } 9500 9501 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9502 ParmVarDecl * const *ParamEnd) { 9503 // Don't diagnose unused-parameter errors in template instantiations; we 9504 // will already have done so in the template itself. 9505 if (!ActiveTemplateInstantiations.empty()) 9506 return; 9507 9508 for (; Param != ParamEnd; ++Param) { 9509 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9510 !(*Param)->hasAttr<UnusedAttr>()) { 9511 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9512 << (*Param)->getDeclName(); 9513 } 9514 } 9515 } 9516 9517 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9518 ParmVarDecl * const *ParamEnd, 9519 QualType ReturnTy, 9520 NamedDecl *D) { 9521 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9522 return; 9523 9524 // Warn if the return value is pass-by-value and larger than the specified 9525 // threshold. 9526 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9527 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9528 if (Size > LangOpts.NumLargeByValueCopy) 9529 Diag(D->getLocation(), diag::warn_return_value_size) 9530 << D->getDeclName() << Size; 9531 } 9532 9533 // Warn if any parameter is pass-by-value and larger than the specified 9534 // threshold. 9535 for (; Param != ParamEnd; ++Param) { 9536 QualType T = (*Param)->getType(); 9537 if (T->isDependentType() || !T.isPODType(Context)) 9538 continue; 9539 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9540 if (Size > LangOpts.NumLargeByValueCopy) 9541 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9542 << (*Param)->getDeclName() << Size; 9543 } 9544 } 9545 9546 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9547 SourceLocation NameLoc, IdentifierInfo *Name, 9548 QualType T, TypeSourceInfo *TSInfo, 9549 VarDecl::StorageClass StorageClass) { 9550 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9551 if (getLangOpts().ObjCAutoRefCount && 9552 T.getObjCLifetime() == Qualifiers::OCL_None && 9553 T->isObjCLifetimeType()) { 9554 9555 Qualifiers::ObjCLifetime lifetime; 9556 9557 // Special cases for arrays: 9558 // - if it's const, use __unsafe_unretained 9559 // - otherwise, it's an error 9560 if (T->isArrayType()) { 9561 if (!T.isConstQualified()) { 9562 DelayedDiagnostics.add( 9563 sema::DelayedDiagnostic::makeForbiddenType( 9564 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9565 } 9566 lifetime = Qualifiers::OCL_ExplicitNone; 9567 } else { 9568 lifetime = T->getObjCARCImplicitLifetime(); 9569 } 9570 T = Context.getLifetimeQualifiedType(T, lifetime); 9571 } 9572 9573 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9574 Context.getAdjustedParameterType(T), 9575 TSInfo, 9576 StorageClass, nullptr); 9577 9578 // Parameters can not be abstract class types. 9579 // For record types, this is done by the AbstractClassUsageDiagnoser once 9580 // the class has been completely parsed. 9581 if (!CurContext->isRecord() && 9582 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9583 AbstractParamType)) 9584 New->setInvalidDecl(); 9585 9586 // Parameter declarators cannot be interface types. All ObjC objects are 9587 // passed by reference. 9588 if (T->isObjCObjectType()) { 9589 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9590 Diag(NameLoc, 9591 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9592 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9593 T = Context.getObjCObjectPointerType(T); 9594 New->setType(T); 9595 } 9596 9597 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9598 // duration shall not be qualified by an address-space qualifier." 9599 // Since all parameters have automatic store duration, they can not have 9600 // an address space. 9601 if (T.getAddressSpace() != 0) { 9602 // OpenCL allows function arguments declared to be an array of a type 9603 // to be qualified with an address space. 9604 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9605 Diag(NameLoc, diag::err_arg_with_address_space); 9606 New->setInvalidDecl(); 9607 } 9608 } 9609 9610 return New; 9611 } 9612 9613 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9614 SourceLocation LocAfterDecls) { 9615 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9616 9617 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9618 // for a K&R function. 9619 if (!FTI.hasPrototype) { 9620 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9621 --i; 9622 if (FTI.Params[i].Param == nullptr) { 9623 SmallString<256> Code; 9624 llvm::raw_svector_ostream(Code) 9625 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9626 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9627 << FTI.Params[i].Ident 9628 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9629 9630 // Implicitly declare the argument as type 'int' for lack of a better 9631 // type. 9632 AttributeFactory attrs; 9633 DeclSpec DS(attrs); 9634 const char* PrevSpec; // unused 9635 unsigned DiagID; // unused 9636 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9637 DiagID, Context.getPrintingPolicy()); 9638 // Use the identifier location for the type source range. 9639 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9640 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9641 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9642 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9643 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9644 } 9645 } 9646 } 9647 } 9648 9649 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9650 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 9651 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9652 Scope *ParentScope = FnBodyScope->getParent(); 9653 9654 D.setFunctionDefinitionKind(FDK_Definition); 9655 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9656 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9657 } 9658 9659 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 9660 Consumer.HandleInlineMethodDefinition(D); 9661 } 9662 9663 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9664 const FunctionDecl*& PossibleZeroParamPrototype) { 9665 // Don't warn about invalid declarations. 9666 if (FD->isInvalidDecl()) 9667 return false; 9668 9669 // Or declarations that aren't global. 9670 if (!FD->isGlobal()) 9671 return false; 9672 9673 // Don't warn about C++ member functions. 9674 if (isa<CXXMethodDecl>(FD)) 9675 return false; 9676 9677 // Don't warn about 'main'. 9678 if (FD->isMain()) 9679 return false; 9680 9681 // Don't warn about inline functions. 9682 if (FD->isInlined()) 9683 return false; 9684 9685 // Don't warn about function templates. 9686 if (FD->getDescribedFunctionTemplate()) 9687 return false; 9688 9689 // Don't warn about function template specializations. 9690 if (FD->isFunctionTemplateSpecialization()) 9691 return false; 9692 9693 // Don't warn for OpenCL kernels. 9694 if (FD->hasAttr<OpenCLKernelAttr>()) 9695 return false; 9696 9697 bool MissingPrototype = true; 9698 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9699 Prev; Prev = Prev->getPreviousDecl()) { 9700 // Ignore any declarations that occur in function or method 9701 // scope, because they aren't visible from the header. 9702 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9703 continue; 9704 9705 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9706 if (FD->getNumParams() == 0) 9707 PossibleZeroParamPrototype = Prev; 9708 break; 9709 } 9710 9711 return MissingPrototype; 9712 } 9713 9714 void 9715 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9716 const FunctionDecl *EffectiveDefinition) { 9717 // Don't complain if we're in GNU89 mode and the previous definition 9718 // was an extern inline function. 9719 const FunctionDecl *Definition = EffectiveDefinition; 9720 if (!Definition) 9721 if (!FD->isDefined(Definition)) 9722 return; 9723 9724 if (canRedefineFunction(Definition, getLangOpts())) 9725 return; 9726 9727 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9728 Definition->getStorageClass() == SC_Extern) 9729 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9730 << FD->getDeclName() << getLangOpts().CPlusPlus; 9731 else 9732 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9733 9734 Diag(Definition->getLocation(), diag::note_previous_definition); 9735 FD->setInvalidDecl(); 9736 } 9737 9738 9739 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9740 Sema &S) { 9741 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9742 9743 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9744 LSI->CallOperator = CallOperator; 9745 LSI->Lambda = LambdaClass; 9746 LSI->ReturnType = CallOperator->getReturnType(); 9747 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9748 9749 if (LCD == LCD_None) 9750 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9751 else if (LCD == LCD_ByCopy) 9752 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9753 else if (LCD == LCD_ByRef) 9754 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9755 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9756 9757 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9758 LSI->Mutable = !CallOperator->isConst(); 9759 9760 // Add the captures to the LSI so they can be noted as already 9761 // captured within tryCaptureVar. 9762 for (const auto &C : LambdaClass->captures()) { 9763 if (C.capturesVariable()) { 9764 VarDecl *VD = C.getCapturedVar(); 9765 if (VD->isInitCapture()) 9766 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9767 QualType CaptureType = VD->getType(); 9768 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 9769 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9770 /*RefersToEnclosingLocal*/true, C.getLocation(), 9771 /*EllipsisLoc*/C.isPackExpansion() 9772 ? C.getEllipsisLoc() : SourceLocation(), 9773 CaptureType, /*Expr*/ nullptr); 9774 9775 } else if (C.capturesThis()) { 9776 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 9777 S.getCurrentThisType(), /*Expr*/ nullptr); 9778 } 9779 } 9780 } 9781 9782 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9783 // Clear the last template instantiation error context. 9784 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9785 9786 if (!D) 9787 return D; 9788 FunctionDecl *FD = nullptr; 9789 9790 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9791 FD = FunTmpl->getTemplatedDecl(); 9792 else 9793 FD = cast<FunctionDecl>(D); 9794 // If we are instantiating a generic lambda call operator, push 9795 // a LambdaScopeInfo onto the function stack. But use the information 9796 // that's already been calculated (ActOnLambdaExpr) to prime the current 9797 // LambdaScopeInfo. 9798 // When the template operator is being specialized, the LambdaScopeInfo, 9799 // has to be properly restored so that tryCaptureVariable doesn't try 9800 // and capture any new variables. In addition when calculating potential 9801 // captures during transformation of nested lambdas, it is necessary to 9802 // have the LSI properly restored. 9803 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9804 assert(ActiveTemplateInstantiations.size() && 9805 "There should be an active template instantiation on the stack " 9806 "when instantiating a generic lambda!"); 9807 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9808 } 9809 else 9810 // Enter a new function scope 9811 PushFunctionScope(); 9812 9813 // See if this is a redefinition. 9814 if (!FD->isLateTemplateParsed()) 9815 CheckForFunctionRedefinition(FD); 9816 9817 // Builtin functions cannot be defined. 9818 if (unsigned BuiltinID = FD->getBuiltinID()) { 9819 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9820 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9821 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9822 FD->setInvalidDecl(); 9823 } 9824 } 9825 9826 // The return type of a function definition must be complete 9827 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9828 QualType ResultType = FD->getReturnType(); 9829 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9830 !FD->isInvalidDecl() && 9831 RequireCompleteType(FD->getLocation(), ResultType, 9832 diag::err_func_def_incomplete_result)) 9833 FD->setInvalidDecl(); 9834 9835 // GNU warning -Wmissing-prototypes: 9836 // Warn if a global function is defined without a previous 9837 // prototype declaration. This warning is issued even if the 9838 // definition itself provides a prototype. The aim is to detect 9839 // global functions that fail to be declared in header files. 9840 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 9841 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9842 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9843 9844 if (PossibleZeroParamPrototype) { 9845 // We found a declaration that is not a prototype, 9846 // but that could be a zero-parameter prototype 9847 if (TypeSourceInfo *TI = 9848 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9849 TypeLoc TL = TI->getTypeLoc(); 9850 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9851 Diag(PossibleZeroParamPrototype->getLocation(), 9852 diag::note_declaration_not_a_prototype) 9853 << PossibleZeroParamPrototype 9854 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9855 } 9856 } 9857 } 9858 9859 if (FnBodyScope) 9860 PushDeclContext(FnBodyScope, FD); 9861 9862 // Check the validity of our function parameters 9863 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9864 /*CheckParameterNames=*/true); 9865 9866 // Introduce our parameters into the function scope 9867 for (auto Param : FD->params()) { 9868 Param->setOwningFunction(FD); 9869 9870 // If this has an identifier, add it to the scope stack. 9871 if (Param->getIdentifier() && FnBodyScope) { 9872 CheckShadow(FnBodyScope, Param); 9873 9874 PushOnScopeChains(Param, FnBodyScope); 9875 } 9876 } 9877 9878 // If we had any tags defined in the function prototype, 9879 // introduce them into the function scope. 9880 if (FnBodyScope) { 9881 for (ArrayRef<NamedDecl *>::iterator 9882 I = FD->getDeclsInPrototypeScope().begin(), 9883 E = FD->getDeclsInPrototypeScope().end(); 9884 I != E; ++I) { 9885 NamedDecl *D = *I; 9886 9887 // Some of these decls (like enums) may have been pinned to the translation unit 9888 // for lack of a real context earlier. If so, remove from the translation unit 9889 // and reattach to the current context. 9890 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9891 // Is the decl actually in the context? 9892 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9893 if (DI == D) { 9894 Context.getTranslationUnitDecl()->removeDecl(D); 9895 break; 9896 } 9897 } 9898 // Either way, reassign the lexical decl context to our FunctionDecl. 9899 D->setLexicalDeclContext(CurContext); 9900 } 9901 9902 // If the decl has a non-null name, make accessible in the current scope. 9903 if (!D->getName().empty()) 9904 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9905 9906 // Similarly, dive into enums and fish their constants out, making them 9907 // accessible in this scope. 9908 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9909 for (auto *EI : ED->enumerators()) 9910 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9911 } 9912 } 9913 } 9914 9915 // Ensure that the function's exception specification is instantiated. 9916 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9917 ResolveExceptionSpec(D->getLocation(), FPT); 9918 9919 // dllimport cannot be applied to non-inline function definitions. 9920 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 9921 !FD->isTemplateInstantiation()) { 9922 assert(!FD->hasAttr<DLLExportAttr>()); 9923 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 9924 FD->setInvalidDecl(); 9925 return D; 9926 } 9927 // We want to attach documentation to original Decl (which might be 9928 // a function template). 9929 ActOnDocumentableDecl(D); 9930 if (getCurLexicalContext()->isObjCContainer() && 9931 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 9932 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 9933 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 9934 9935 return D; 9936 } 9937 9938 /// \brief Given the set of return statements within a function body, 9939 /// compute the variables that are subject to the named return value 9940 /// optimization. 9941 /// 9942 /// Each of the variables that is subject to the named return value 9943 /// optimization will be marked as NRVO variables in the AST, and any 9944 /// return statement that has a marked NRVO variable as its NRVO candidate can 9945 /// use the named return value optimization. 9946 /// 9947 /// This function applies a very simplistic algorithm for NRVO: if every return 9948 /// statement in the scope of a variable has the same NRVO candidate, that 9949 /// candidate is an NRVO variable. 9950 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9951 ReturnStmt **Returns = Scope->Returns.data(); 9952 9953 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9954 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 9955 if (!NRVOCandidate->isNRVOVariable()) 9956 Returns[I]->setNRVOCandidate(nullptr); 9957 } 9958 } 9959 } 9960 9961 bool Sema::canDelayFunctionBody(const Declarator &D) { 9962 // We can't delay parsing the body of a constexpr function template (yet). 9963 if (D.getDeclSpec().isConstexprSpecified()) 9964 return false; 9965 9966 // We can't delay parsing the body of a function template with a deduced 9967 // return type (yet). 9968 if (D.getDeclSpec().containsPlaceholderType()) { 9969 // If the placeholder introduces a non-deduced trailing return type, 9970 // we can still delay parsing it. 9971 if (D.getNumTypeObjects()) { 9972 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 9973 if (Outer.Kind == DeclaratorChunk::Function && 9974 Outer.Fun.hasTrailingReturnType()) { 9975 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 9976 return Ty.isNull() || !Ty->isUndeducedType(); 9977 } 9978 } 9979 return false; 9980 } 9981 9982 return true; 9983 } 9984 9985 bool Sema::canSkipFunctionBody(Decl *D) { 9986 // We cannot skip the body of a function (or function template) which is 9987 // constexpr, since we may need to evaluate its body in order to parse the 9988 // rest of the file. 9989 // We cannot skip the body of a function with an undeduced return type, 9990 // because any callers of that function need to know the type. 9991 if (const FunctionDecl *FD = D->getAsFunction()) 9992 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9993 return false; 9994 return Consumer.shouldSkipFunctionBody(D); 9995 } 9996 9997 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9998 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9999 FD->setHasSkippedBody(); 10000 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10001 MD->setHasSkippedBody(); 10002 return ActOnFinishFunctionBody(Decl, nullptr); 10003 } 10004 10005 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10006 return ActOnFinishFunctionBody(D, BodyArg, false); 10007 } 10008 10009 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10010 bool IsInstantiation) { 10011 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10012 10013 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10014 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10015 10016 if (FD) { 10017 FD->setBody(Body); 10018 10019 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 10020 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10021 // If the function has a deduced result type but contains no 'return' 10022 // statements, the result type as written must be exactly 'auto', and 10023 // the deduced result type is 'void'. 10024 if (!FD->getReturnType()->getAs<AutoType>()) { 10025 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10026 << FD->getReturnType(); 10027 FD->setInvalidDecl(); 10028 } else { 10029 // Substitute 'void' for the 'auto' in the type. 10030 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 10031 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 10032 Context.adjustDeducedFunctionResultType( 10033 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10034 } 10035 } 10036 10037 // The only way to be included in UndefinedButUsed is if there is an 10038 // ODR use before the definition. Avoid the expensive map lookup if this 10039 // is the first declaration. 10040 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10041 if (!FD->isExternallyVisible()) 10042 UndefinedButUsed.erase(FD); 10043 else if (FD->isInlined() && 10044 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10045 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10046 UndefinedButUsed.erase(FD); 10047 } 10048 10049 // If the function implicitly returns zero (like 'main') or is naked, 10050 // don't complain about missing return statements. 10051 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10052 WP.disableCheckFallThrough(); 10053 10054 // MSVC permits the use of pure specifier (=0) on function definition, 10055 // defined at class scope, warn about this non-standard construct. 10056 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10057 Diag(FD->getLocation(), diag::warn_pure_function_definition); 10058 10059 if (!FD->isInvalidDecl()) { 10060 // Don't diagnose unused parameters of defaulted or deleted functions. 10061 if (Body) 10062 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10063 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10064 FD->getReturnType(), FD); 10065 10066 // If this is a constructor, we need a vtable. 10067 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10068 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10069 10070 // Try to apply the named return value optimization. We have to check 10071 // if we can do this here because lambdas keep return statements around 10072 // to deduce an implicit return type. 10073 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10074 !FD->isDependentContext()) 10075 computeNRVO(Body, getCurFunction()); 10076 } 10077 10078 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10079 "Function parsing confused"); 10080 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10081 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10082 MD->setBody(Body); 10083 if (!MD->isInvalidDecl()) { 10084 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10085 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10086 MD->getReturnType(), MD); 10087 10088 if (Body) 10089 computeNRVO(Body, getCurFunction()); 10090 } 10091 if (getCurFunction()->ObjCShouldCallSuper) { 10092 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10093 << MD->getSelector().getAsString(); 10094 getCurFunction()->ObjCShouldCallSuper = false; 10095 } 10096 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10097 const ObjCMethodDecl *InitMethod = nullptr; 10098 bool isDesignated = 10099 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10100 assert(isDesignated && InitMethod); 10101 (void)isDesignated; 10102 10103 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10104 auto IFace = MD->getClassInterface(); 10105 if (!IFace) 10106 return false; 10107 auto SuperD = IFace->getSuperClass(); 10108 if (!SuperD) 10109 return false; 10110 return SuperD->getIdentifier() == 10111 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10112 }; 10113 // Don't issue this warning for unavailable inits or direct subclasses 10114 // of NSObject. 10115 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10116 Diag(MD->getLocation(), 10117 diag::warn_objc_designated_init_missing_super_call); 10118 Diag(InitMethod->getLocation(), 10119 diag::note_objc_designated_init_marked_here); 10120 } 10121 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10122 } 10123 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10124 // Don't issue this warning for unavaialable inits. 10125 if (!MD->isUnavailable()) 10126 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10127 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10128 } 10129 } else { 10130 return nullptr; 10131 } 10132 10133 assert(!getCurFunction()->ObjCShouldCallSuper && 10134 "This should only be set for ObjC methods, which should have been " 10135 "handled in the block above."); 10136 10137 // Verify and clean out per-function state. 10138 if (Body) { 10139 // C++ constructors that have function-try-blocks can't have return 10140 // statements in the handlers of that block. (C++ [except.handle]p14) 10141 // Verify this. 10142 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10143 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10144 10145 // Verify that gotos and switch cases don't jump into scopes illegally. 10146 if (getCurFunction()->NeedsScopeChecking() && 10147 !PP.isCodeCompletionEnabled()) 10148 DiagnoseInvalidJumps(Body); 10149 10150 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10151 if (!Destructor->getParent()->isDependentType()) 10152 CheckDestructor(Destructor); 10153 10154 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10155 Destructor->getParent()); 10156 } 10157 10158 // If any errors have occurred, clear out any temporaries that may have 10159 // been leftover. This ensures that these temporaries won't be picked up for 10160 // deletion in some later function. 10161 if (getDiagnostics().hasErrorOccurred() || 10162 getDiagnostics().getSuppressAllDiagnostics()) { 10163 DiscardCleanupsInEvaluationContext(); 10164 } 10165 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10166 !isa<FunctionTemplateDecl>(dcl)) { 10167 // Since the body is valid, issue any analysis-based warnings that are 10168 // enabled. 10169 ActivePolicy = &WP; 10170 } 10171 10172 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10173 (!CheckConstexprFunctionDecl(FD) || 10174 !CheckConstexprFunctionBody(FD, Body))) 10175 FD->setInvalidDecl(); 10176 10177 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10178 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10179 assert(MaybeODRUseExprs.empty() && 10180 "Leftover expressions for odr-use checking"); 10181 } 10182 10183 if (!IsInstantiation) 10184 PopDeclContext(); 10185 10186 PopFunctionScopeInfo(ActivePolicy, dcl); 10187 // If any errors have occurred, clear out any temporaries that may have 10188 // been leftover. This ensures that these temporaries won't be picked up for 10189 // deletion in some later function. 10190 if (getDiagnostics().hasErrorOccurred()) { 10191 DiscardCleanupsInEvaluationContext(); 10192 } 10193 10194 return dcl; 10195 } 10196 10197 10198 /// When we finish delayed parsing of an attribute, we must attach it to the 10199 /// relevant Decl. 10200 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10201 ParsedAttributes &Attrs) { 10202 // Always attach attributes to the underlying decl. 10203 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10204 D = TD->getTemplatedDecl(); 10205 ProcessDeclAttributeList(S, D, Attrs.getList()); 10206 10207 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10208 if (Method->isStatic()) 10209 checkThisInStaticMemberFunctionAttributes(Method); 10210 } 10211 10212 10213 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10214 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10215 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10216 IdentifierInfo &II, Scope *S) { 10217 // Before we produce a declaration for an implicitly defined 10218 // function, see whether there was a locally-scoped declaration of 10219 // this name as a function or variable. If so, use that 10220 // (non-visible) declaration, and complain about it. 10221 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10222 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10223 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10224 return ExternCPrev; 10225 } 10226 10227 // Extension in C99. Legal in C90, but warn about it. 10228 unsigned diag_id; 10229 if (II.getName().startswith("__builtin_")) 10230 diag_id = diag::warn_builtin_unknown; 10231 else if (getLangOpts().C99) 10232 diag_id = diag::ext_implicit_function_decl; 10233 else 10234 diag_id = diag::warn_implicit_function_decl; 10235 Diag(Loc, diag_id) << &II; 10236 10237 // Because typo correction is expensive, only do it if the implicit 10238 // function declaration is going to be treated as an error. 10239 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10240 TypoCorrection Corrected; 10241 DeclFilterCCC<FunctionDecl> Validator; 10242 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10243 LookupOrdinaryName, S, nullptr, Validator, 10244 CTK_NonError))) 10245 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10246 /*ErrorRecovery*/false); 10247 } 10248 10249 // Set a Declarator for the implicit definition: int foo(); 10250 const char *Dummy; 10251 AttributeFactory attrFactory; 10252 DeclSpec DS(attrFactory); 10253 unsigned DiagID; 10254 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10255 Context.getPrintingPolicy()); 10256 (void)Error; // Silence warning. 10257 assert(!Error && "Error setting up implicit decl!"); 10258 SourceLocation NoLoc; 10259 Declarator D(DS, Declarator::BlockContext); 10260 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10261 /*IsAmbiguous=*/false, 10262 /*LParenLoc=*/NoLoc, 10263 /*Params=*/nullptr, 10264 /*NumParams=*/0, 10265 /*EllipsisLoc=*/NoLoc, 10266 /*RParenLoc=*/NoLoc, 10267 /*TypeQuals=*/0, 10268 /*RefQualifierIsLvalueRef=*/true, 10269 /*RefQualifierLoc=*/NoLoc, 10270 /*ConstQualifierLoc=*/NoLoc, 10271 /*VolatileQualifierLoc=*/NoLoc, 10272 /*MutableLoc=*/NoLoc, 10273 EST_None, 10274 /*ESpecLoc=*/NoLoc, 10275 /*Exceptions=*/nullptr, 10276 /*ExceptionRanges=*/nullptr, 10277 /*NumExceptions=*/0, 10278 /*NoexceptExpr=*/nullptr, 10279 Loc, Loc, D), 10280 DS.getAttributes(), 10281 SourceLocation()); 10282 D.SetIdentifier(&II, Loc); 10283 10284 // Insert this function into translation-unit scope. 10285 10286 DeclContext *PrevDC = CurContext; 10287 CurContext = Context.getTranslationUnitDecl(); 10288 10289 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10290 FD->setImplicit(); 10291 10292 CurContext = PrevDC; 10293 10294 AddKnownFunctionAttributes(FD); 10295 10296 return FD; 10297 } 10298 10299 /// \brief Adds any function attributes that we know a priori based on 10300 /// the declaration of this function. 10301 /// 10302 /// These attributes can apply both to implicitly-declared builtins 10303 /// (like __builtin___printf_chk) or to library-declared functions 10304 /// like NSLog or printf. 10305 /// 10306 /// We need to check for duplicate attributes both here and where user-written 10307 /// attributes are applied to declarations. 10308 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10309 if (FD->isInvalidDecl()) 10310 return; 10311 10312 // If this is a built-in function, map its builtin attributes to 10313 // actual attributes. 10314 if (unsigned BuiltinID = FD->getBuiltinID()) { 10315 // Handle printf-formatting attributes. 10316 unsigned FormatIdx; 10317 bool HasVAListArg; 10318 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10319 if (!FD->hasAttr<FormatAttr>()) { 10320 const char *fmt = "printf"; 10321 unsigned int NumParams = FD->getNumParams(); 10322 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10323 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10324 fmt = "NSString"; 10325 FD->addAttr(FormatAttr::CreateImplicit(Context, 10326 &Context.Idents.get(fmt), 10327 FormatIdx+1, 10328 HasVAListArg ? 0 : FormatIdx+2, 10329 FD->getLocation())); 10330 } 10331 } 10332 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10333 HasVAListArg)) { 10334 if (!FD->hasAttr<FormatAttr>()) 10335 FD->addAttr(FormatAttr::CreateImplicit(Context, 10336 &Context.Idents.get("scanf"), 10337 FormatIdx+1, 10338 HasVAListArg ? 0 : FormatIdx+2, 10339 FD->getLocation())); 10340 } 10341 10342 // Mark const if we don't care about errno and that is the only 10343 // thing preventing the function from being const. This allows 10344 // IRgen to use LLVM intrinsics for such functions. 10345 if (!getLangOpts().MathErrno && 10346 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10347 if (!FD->hasAttr<ConstAttr>()) 10348 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10349 } 10350 10351 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10352 !FD->hasAttr<ReturnsTwiceAttr>()) 10353 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10354 FD->getLocation())); 10355 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10356 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10357 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10358 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10359 } 10360 10361 IdentifierInfo *Name = FD->getIdentifier(); 10362 if (!Name) 10363 return; 10364 if ((!getLangOpts().CPlusPlus && 10365 FD->getDeclContext()->isTranslationUnit()) || 10366 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10367 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10368 LinkageSpecDecl::lang_c)) { 10369 // Okay: this could be a libc/libm/Objective-C function we know 10370 // about. 10371 } else 10372 return; 10373 10374 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10375 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10376 // target-specific builtins, perhaps? 10377 if (!FD->hasAttr<FormatAttr>()) 10378 FD->addAttr(FormatAttr::CreateImplicit(Context, 10379 &Context.Idents.get("printf"), 2, 10380 Name->isStr("vasprintf") ? 0 : 3, 10381 FD->getLocation())); 10382 } 10383 10384 if (Name->isStr("__CFStringMakeConstantString")) { 10385 // We already have a __builtin___CFStringMakeConstantString, 10386 // but builds that use -fno-constant-cfstrings don't go through that. 10387 if (!FD->hasAttr<FormatArgAttr>()) 10388 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10389 FD->getLocation())); 10390 } 10391 } 10392 10393 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10394 TypeSourceInfo *TInfo) { 10395 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10396 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10397 10398 if (!TInfo) { 10399 assert(D.isInvalidType() && "no declarator info for valid type"); 10400 TInfo = Context.getTrivialTypeSourceInfo(T); 10401 } 10402 10403 // Scope manipulation handled by caller. 10404 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10405 D.getLocStart(), 10406 D.getIdentifierLoc(), 10407 D.getIdentifier(), 10408 TInfo); 10409 10410 // Bail out immediately if we have an invalid declaration. 10411 if (D.isInvalidType()) { 10412 NewTD->setInvalidDecl(); 10413 return NewTD; 10414 } 10415 10416 if (D.getDeclSpec().isModulePrivateSpecified()) { 10417 if (CurContext->isFunctionOrMethod()) 10418 Diag(NewTD->getLocation(), diag::err_module_private_local) 10419 << 2 << NewTD->getDeclName() 10420 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10421 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10422 else 10423 NewTD->setModulePrivate(); 10424 } 10425 10426 // C++ [dcl.typedef]p8: 10427 // If the typedef declaration defines an unnamed class (or 10428 // enum), the first typedef-name declared by the declaration 10429 // to be that class type (or enum type) is used to denote the 10430 // class type (or enum type) for linkage purposes only. 10431 // We need to check whether the type was declared in the declaration. 10432 switch (D.getDeclSpec().getTypeSpecType()) { 10433 case TST_enum: 10434 case TST_struct: 10435 case TST_interface: 10436 case TST_union: 10437 case TST_class: { 10438 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10439 10440 // Do nothing if the tag is not anonymous or already has an 10441 // associated typedef (from an earlier typedef in this decl group). 10442 if (tagFromDeclSpec->getIdentifier()) break; 10443 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10444 10445 // A well-formed anonymous tag must always be a TUK_Definition. 10446 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10447 10448 // The type must match the tag exactly; no qualifiers allowed. 10449 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10450 break; 10451 10452 // If we've already computed linkage for the anonymous tag, then 10453 // adding a typedef name for the anonymous decl can change that 10454 // linkage, which might be a serious problem. Diagnose this as 10455 // unsupported and ignore the typedef name. TODO: we should 10456 // pursue this as a language defect and establish a formal rule 10457 // for how to handle it. 10458 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10459 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10460 10461 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10462 tagLoc = getLocForEndOfToken(tagLoc); 10463 10464 llvm::SmallString<40> textToInsert; 10465 textToInsert += ' '; 10466 textToInsert += D.getIdentifier()->getName(); 10467 Diag(tagLoc, diag::note_typedef_changes_linkage) 10468 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10469 break; 10470 } 10471 10472 // Otherwise, set this is the anon-decl typedef for the tag. 10473 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10474 break; 10475 } 10476 10477 default: 10478 break; 10479 } 10480 10481 return NewTD; 10482 } 10483 10484 10485 /// \brief Check that this is a valid underlying type for an enum declaration. 10486 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10487 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10488 QualType T = TI->getType(); 10489 10490 if (T->isDependentType()) 10491 return false; 10492 10493 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10494 if (BT->isInteger()) 10495 return false; 10496 10497 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10498 return true; 10499 } 10500 10501 /// Check whether this is a valid redeclaration of a previous enumeration. 10502 /// \return true if the redeclaration was invalid. 10503 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10504 QualType EnumUnderlyingTy, 10505 const EnumDecl *Prev) { 10506 bool IsFixed = !EnumUnderlyingTy.isNull(); 10507 10508 if (IsScoped != Prev->isScoped()) { 10509 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10510 << Prev->isScoped(); 10511 Diag(Prev->getLocation(), diag::note_previous_declaration); 10512 return true; 10513 } 10514 10515 if (IsFixed && Prev->isFixed()) { 10516 if (!EnumUnderlyingTy->isDependentType() && 10517 !Prev->getIntegerType()->isDependentType() && 10518 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10519 Prev->getIntegerType())) { 10520 // TODO: Highlight the underlying type of the redeclaration. 10521 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10522 << EnumUnderlyingTy << Prev->getIntegerType(); 10523 Diag(Prev->getLocation(), diag::note_previous_declaration) 10524 << Prev->getIntegerTypeRange(); 10525 return true; 10526 } 10527 } else if (IsFixed != Prev->isFixed()) { 10528 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10529 << Prev->isFixed(); 10530 Diag(Prev->getLocation(), diag::note_previous_declaration); 10531 return true; 10532 } 10533 10534 return false; 10535 } 10536 10537 /// \brief Get diagnostic %select index for tag kind for 10538 /// redeclaration diagnostic message. 10539 /// WARNING: Indexes apply to particular diagnostics only! 10540 /// 10541 /// \returns diagnostic %select index. 10542 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10543 switch (Tag) { 10544 case TTK_Struct: return 0; 10545 case TTK_Interface: return 1; 10546 case TTK_Class: return 2; 10547 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10548 } 10549 } 10550 10551 /// \brief Determine if tag kind is a class-key compatible with 10552 /// class for redeclaration (class, struct, or __interface). 10553 /// 10554 /// \returns true iff the tag kind is compatible. 10555 static bool isClassCompatTagKind(TagTypeKind Tag) 10556 { 10557 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10558 } 10559 10560 /// \brief Determine whether a tag with a given kind is acceptable 10561 /// as a redeclaration of the given tag declaration. 10562 /// 10563 /// \returns true if the new tag kind is acceptable, false otherwise. 10564 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10565 TagTypeKind NewTag, bool isDefinition, 10566 SourceLocation NewTagLoc, 10567 const IdentifierInfo &Name) { 10568 // C++ [dcl.type.elab]p3: 10569 // The class-key or enum keyword present in the 10570 // elaborated-type-specifier shall agree in kind with the 10571 // declaration to which the name in the elaborated-type-specifier 10572 // refers. This rule also applies to the form of 10573 // elaborated-type-specifier that declares a class-name or 10574 // friend class since it can be construed as referring to the 10575 // definition of the class. Thus, in any 10576 // elaborated-type-specifier, the enum keyword shall be used to 10577 // refer to an enumeration (7.2), the union class-key shall be 10578 // used to refer to a union (clause 9), and either the class or 10579 // struct class-key shall be used to refer to a class (clause 9) 10580 // declared using the class or struct class-key. 10581 TagTypeKind OldTag = Previous->getTagKind(); 10582 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10583 if (OldTag == NewTag) 10584 return true; 10585 10586 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10587 // Warn about the struct/class tag mismatch. 10588 bool isTemplate = false; 10589 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10590 isTemplate = Record->getDescribedClassTemplate(); 10591 10592 if (!ActiveTemplateInstantiations.empty()) { 10593 // In a template instantiation, do not offer fix-its for tag mismatches 10594 // since they usually mess up the template instead of fixing the problem. 10595 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10596 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10597 << getRedeclDiagFromTagKind(OldTag); 10598 return true; 10599 } 10600 10601 if (isDefinition) { 10602 // On definitions, check previous tags and issue a fix-it for each 10603 // one that doesn't match the current tag. 10604 if (Previous->getDefinition()) { 10605 // Don't suggest fix-its for redefinitions. 10606 return true; 10607 } 10608 10609 bool previousMismatch = false; 10610 for (auto I : Previous->redecls()) { 10611 if (I->getTagKind() != NewTag) { 10612 if (!previousMismatch) { 10613 previousMismatch = true; 10614 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10615 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10616 << getRedeclDiagFromTagKind(I->getTagKind()); 10617 } 10618 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10619 << getRedeclDiagFromTagKind(NewTag) 10620 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10621 TypeWithKeyword::getTagTypeKindName(NewTag)); 10622 } 10623 } 10624 return true; 10625 } 10626 10627 // Check for a previous definition. If current tag and definition 10628 // are same type, do nothing. If no definition, but disagree with 10629 // with previous tag type, give a warning, but no fix-it. 10630 const TagDecl *Redecl = Previous->getDefinition() ? 10631 Previous->getDefinition() : Previous; 10632 if (Redecl->getTagKind() == NewTag) { 10633 return true; 10634 } 10635 10636 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10637 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10638 << getRedeclDiagFromTagKind(OldTag); 10639 Diag(Redecl->getLocation(), diag::note_previous_use); 10640 10641 // If there is a previous definition, suggest a fix-it. 10642 if (Previous->getDefinition()) { 10643 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10644 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10645 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10646 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10647 } 10648 10649 return true; 10650 } 10651 return false; 10652 } 10653 10654 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10655 /// former case, Name will be non-null. In the later case, Name will be null. 10656 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10657 /// reference/declaration/definition of a tag. 10658 /// 10659 /// IsTypeSpecifier is true if this is a type-specifier (or 10660 /// trailing-type-specifier) other than one in an alias-declaration. 10661 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10662 SourceLocation KWLoc, CXXScopeSpec &SS, 10663 IdentifierInfo *Name, SourceLocation NameLoc, 10664 AttributeList *Attr, AccessSpecifier AS, 10665 SourceLocation ModulePrivateLoc, 10666 MultiTemplateParamsArg TemplateParameterLists, 10667 bool &OwnedDecl, bool &IsDependent, 10668 SourceLocation ScopedEnumKWLoc, 10669 bool ScopedEnumUsesClassTag, 10670 TypeResult UnderlyingType, 10671 bool IsTypeSpecifier) { 10672 // If this is not a definition, it must have a name. 10673 IdentifierInfo *OrigName = Name; 10674 assert((Name != nullptr || TUK == TUK_Definition) && 10675 "Nameless record must be a definition!"); 10676 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10677 10678 OwnedDecl = false; 10679 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10680 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10681 10682 // FIXME: Check explicit specializations more carefully. 10683 bool isExplicitSpecialization = false; 10684 bool Invalid = false; 10685 10686 // We only need to do this matching if we have template parameters 10687 // or a scope specifier, which also conveniently avoids this work 10688 // for non-C++ cases. 10689 if (TemplateParameterLists.size() > 0 || 10690 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10691 if (TemplateParameterList *TemplateParams = 10692 MatchTemplateParametersToScopeSpecifier( 10693 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 10694 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 10695 if (Kind == TTK_Enum) { 10696 Diag(KWLoc, diag::err_enum_template); 10697 return nullptr; 10698 } 10699 10700 if (TemplateParams->size() > 0) { 10701 // This is a declaration or definition of a class template (which may 10702 // be a member of another template). 10703 10704 if (Invalid) 10705 return nullptr; 10706 10707 OwnedDecl = false; 10708 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10709 SS, Name, NameLoc, Attr, 10710 TemplateParams, AS, 10711 ModulePrivateLoc, 10712 TemplateParameterLists.size()-1, 10713 TemplateParameterLists.data()); 10714 return Result.get(); 10715 } else { 10716 // The "template<>" header is extraneous. 10717 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10718 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10719 isExplicitSpecialization = true; 10720 } 10721 } 10722 } 10723 10724 // Figure out the underlying type if this a enum declaration. We need to do 10725 // this early, because it's needed to detect if this is an incompatible 10726 // redeclaration. 10727 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10728 10729 if (Kind == TTK_Enum) { 10730 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10731 // No underlying type explicitly specified, or we failed to parse the 10732 // type, default to int. 10733 EnumUnderlying = Context.IntTy.getTypePtr(); 10734 else if (UnderlyingType.get()) { 10735 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10736 // integral type; any cv-qualification is ignored. 10737 TypeSourceInfo *TI = nullptr; 10738 GetTypeFromParser(UnderlyingType.get(), &TI); 10739 EnumUnderlying = TI; 10740 10741 if (CheckEnumUnderlyingType(TI)) 10742 // Recover by falling back to int. 10743 EnumUnderlying = Context.IntTy.getTypePtr(); 10744 10745 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10746 UPPC_FixedUnderlyingType)) 10747 EnumUnderlying = Context.IntTy.getTypePtr(); 10748 10749 } else if (getLangOpts().MSVCCompat) 10750 // Microsoft enums are always of int type. 10751 EnumUnderlying = Context.IntTy.getTypePtr(); 10752 } 10753 10754 DeclContext *SearchDC = CurContext; 10755 DeclContext *DC = CurContext; 10756 bool isStdBadAlloc = false; 10757 10758 RedeclarationKind Redecl = ForRedeclaration; 10759 if (TUK == TUK_Friend || TUK == TUK_Reference) 10760 Redecl = NotForRedeclaration; 10761 10762 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10763 bool FriendSawTagOutsideEnclosingNamespace = false; 10764 if (Name && SS.isNotEmpty()) { 10765 // We have a nested-name tag ('struct foo::bar'). 10766 10767 // Check for invalid 'foo::'. 10768 if (SS.isInvalid()) { 10769 Name = nullptr; 10770 goto CreateNewDecl; 10771 } 10772 10773 // If this is a friend or a reference to a class in a dependent 10774 // context, don't try to make a decl for it. 10775 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10776 DC = computeDeclContext(SS, false); 10777 if (!DC) { 10778 IsDependent = true; 10779 return nullptr; 10780 } 10781 } else { 10782 DC = computeDeclContext(SS, true); 10783 if (!DC) { 10784 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10785 << SS.getRange(); 10786 return nullptr; 10787 } 10788 } 10789 10790 if (RequireCompleteDeclContext(SS, DC)) 10791 return nullptr; 10792 10793 SearchDC = DC; 10794 // Look-up name inside 'foo::'. 10795 LookupQualifiedName(Previous, DC); 10796 10797 if (Previous.isAmbiguous()) 10798 return nullptr; 10799 10800 if (Previous.empty()) { 10801 // Name lookup did not find anything. However, if the 10802 // nested-name-specifier refers to the current instantiation, 10803 // and that current instantiation has any dependent base 10804 // classes, we might find something at instantiation time: treat 10805 // this as a dependent elaborated-type-specifier. 10806 // But this only makes any sense for reference-like lookups. 10807 if (Previous.wasNotFoundInCurrentInstantiation() && 10808 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10809 IsDependent = true; 10810 return nullptr; 10811 } 10812 10813 // A tag 'foo::bar' must already exist. 10814 Diag(NameLoc, diag::err_not_tag_in_scope) 10815 << Kind << Name << DC << SS.getRange(); 10816 Name = nullptr; 10817 Invalid = true; 10818 goto CreateNewDecl; 10819 } 10820 } else if (Name) { 10821 // If this is a named struct, check to see if there was a previous forward 10822 // declaration or definition. 10823 // FIXME: We're looking into outer scopes here, even when we 10824 // shouldn't be. Doing so can result in ambiguities that we 10825 // shouldn't be diagnosing. 10826 LookupName(Previous, S); 10827 10828 // When declaring or defining a tag, ignore ambiguities introduced 10829 // by types using'ed into this scope. 10830 if (Previous.isAmbiguous() && 10831 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10832 LookupResult::Filter F = Previous.makeFilter(); 10833 while (F.hasNext()) { 10834 NamedDecl *ND = F.next(); 10835 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10836 F.erase(); 10837 } 10838 F.done(); 10839 } 10840 10841 // C++11 [namespace.memdef]p3: 10842 // If the name in a friend declaration is neither qualified nor 10843 // a template-id and the declaration is a function or an 10844 // elaborated-type-specifier, the lookup to determine whether 10845 // the entity has been previously declared shall not consider 10846 // any scopes outside the innermost enclosing namespace. 10847 // 10848 // Does it matter that this should be by scope instead of by 10849 // semantic context? 10850 if (!Previous.empty() && TUK == TUK_Friend) { 10851 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10852 LookupResult::Filter F = Previous.makeFilter(); 10853 while (F.hasNext()) { 10854 NamedDecl *ND = F.next(); 10855 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10856 if (DC->isFileContext() && 10857 !EnclosingNS->Encloses(ND->getDeclContext())) { 10858 F.erase(); 10859 FriendSawTagOutsideEnclosingNamespace = true; 10860 } 10861 } 10862 F.done(); 10863 } 10864 10865 // Note: there used to be some attempt at recovery here. 10866 if (Previous.isAmbiguous()) 10867 return nullptr; 10868 10869 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10870 // FIXME: This makes sure that we ignore the contexts associated 10871 // with C structs, unions, and enums when looking for a matching 10872 // tag declaration or definition. See the similar lookup tweak 10873 // in Sema::LookupName; is there a better way to deal with this? 10874 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10875 SearchDC = SearchDC->getParent(); 10876 } 10877 } 10878 10879 if (Previous.isSingleResult() && 10880 Previous.getFoundDecl()->isTemplateParameter()) { 10881 // Maybe we will complain about the shadowed template parameter. 10882 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10883 // Just pretend that we didn't see the previous declaration. 10884 Previous.clear(); 10885 } 10886 10887 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10888 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10889 // This is a declaration of or a reference to "std::bad_alloc". 10890 isStdBadAlloc = true; 10891 10892 if (Previous.empty() && StdBadAlloc) { 10893 // std::bad_alloc has been implicitly declared (but made invisible to 10894 // name lookup). Fill in this implicit declaration as the previous 10895 // declaration, so that the declarations get chained appropriately. 10896 Previous.addDecl(getStdBadAlloc()); 10897 } 10898 } 10899 10900 // If we didn't find a previous declaration, and this is a reference 10901 // (or friend reference), move to the correct scope. In C++, we 10902 // also need to do a redeclaration lookup there, just in case 10903 // there's a shadow friend decl. 10904 if (Name && Previous.empty() && 10905 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10906 if (Invalid) goto CreateNewDecl; 10907 assert(SS.isEmpty()); 10908 10909 if (TUK == TUK_Reference) { 10910 // C++ [basic.scope.pdecl]p5: 10911 // -- for an elaborated-type-specifier of the form 10912 // 10913 // class-key identifier 10914 // 10915 // if the elaborated-type-specifier is used in the 10916 // decl-specifier-seq or parameter-declaration-clause of a 10917 // function defined in namespace scope, the identifier is 10918 // declared as a class-name in the namespace that contains 10919 // the declaration; otherwise, except as a friend 10920 // declaration, the identifier is declared in the smallest 10921 // non-class, non-function-prototype scope that contains the 10922 // declaration. 10923 // 10924 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10925 // C structs and unions. 10926 // 10927 // It is an error in C++ to declare (rather than define) an enum 10928 // type, including via an elaborated type specifier. We'll 10929 // diagnose that later; for now, declare the enum in the same 10930 // scope as we would have picked for any other tag type. 10931 // 10932 // GNU C also supports this behavior as part of its incomplete 10933 // enum types extension, while GNU C++ does not. 10934 // 10935 // Find the context where we'll be declaring the tag. 10936 // FIXME: We would like to maintain the current DeclContext as the 10937 // lexical context, 10938 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10939 SearchDC = SearchDC->getParent(); 10940 10941 // Find the scope where we'll be declaring the tag. 10942 while (S->isClassScope() || 10943 (getLangOpts().CPlusPlus && 10944 S->isFunctionPrototypeScope()) || 10945 ((S->getFlags() & Scope::DeclScope) == 0) || 10946 (S->getEntity() && S->getEntity()->isTransparentContext())) 10947 S = S->getParent(); 10948 } else { 10949 assert(TUK == TUK_Friend); 10950 // C++ [namespace.memdef]p3: 10951 // If a friend declaration in a non-local class first declares a 10952 // class or function, the friend class or function is a member of 10953 // the innermost enclosing namespace. 10954 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10955 } 10956 10957 // In C++, we need to do a redeclaration lookup to properly 10958 // diagnose some problems. 10959 if (getLangOpts().CPlusPlus) { 10960 Previous.setRedeclarationKind(ForRedeclaration); 10961 LookupQualifiedName(Previous, SearchDC); 10962 } 10963 } 10964 10965 if (!Previous.empty()) { 10966 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10967 NamedDecl *DirectPrevDecl = 10968 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10969 10970 // It's okay to have a tag decl in the same scope as a typedef 10971 // which hides a tag decl in the same scope. Finding this 10972 // insanity with a redeclaration lookup can only actually happen 10973 // in C++. 10974 // 10975 // This is also okay for elaborated-type-specifiers, which is 10976 // technically forbidden by the current standard but which is 10977 // okay according to the likely resolution of an open issue; 10978 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10979 if (getLangOpts().CPlusPlus) { 10980 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10981 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10982 TagDecl *Tag = TT->getDecl(); 10983 if (Tag->getDeclName() == Name && 10984 Tag->getDeclContext()->getRedeclContext() 10985 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10986 PrevDecl = Tag; 10987 Previous.clear(); 10988 Previous.addDecl(Tag); 10989 Previous.resolveKind(); 10990 } 10991 } 10992 } 10993 } 10994 10995 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10996 // If this is a use of a previous tag, or if the tag is already declared 10997 // in the same scope (so that the definition/declaration completes or 10998 // rementions the tag), reuse the decl. 10999 if (TUK == TUK_Reference || TUK == TUK_Friend || 11000 isDeclInScope(DirectPrevDecl, SearchDC, S, 11001 SS.isNotEmpty() || isExplicitSpecialization)) { 11002 // Make sure that this wasn't declared as an enum and now used as a 11003 // struct or something similar. 11004 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11005 TUK == TUK_Definition, KWLoc, 11006 *Name)) { 11007 bool SafeToContinue 11008 = (PrevTagDecl->getTagKind() != TTK_Enum && 11009 Kind != TTK_Enum); 11010 if (SafeToContinue) 11011 Diag(KWLoc, diag::err_use_with_wrong_tag) 11012 << Name 11013 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11014 PrevTagDecl->getKindName()); 11015 else 11016 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11017 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11018 11019 if (SafeToContinue) 11020 Kind = PrevTagDecl->getTagKind(); 11021 else { 11022 // Recover by making this an anonymous redefinition. 11023 Name = nullptr; 11024 Previous.clear(); 11025 Invalid = true; 11026 } 11027 } 11028 11029 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11030 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11031 11032 // If this is an elaborated-type-specifier for a scoped enumeration, 11033 // the 'class' keyword is not necessary and not permitted. 11034 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11035 if (ScopedEnum) 11036 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11037 << PrevEnum->isScoped() 11038 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11039 return PrevTagDecl; 11040 } 11041 11042 QualType EnumUnderlyingTy; 11043 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11044 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11045 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11046 EnumUnderlyingTy = QualType(T, 0); 11047 11048 // All conflicts with previous declarations are recovered by 11049 // returning the previous declaration, unless this is a definition, 11050 // in which case we want the caller to bail out. 11051 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11052 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11053 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11054 } 11055 11056 // C++11 [class.mem]p1: 11057 // A member shall not be declared twice in the member-specification, 11058 // except that a nested class or member class template can be declared 11059 // and then later defined. 11060 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11061 S->isDeclScope(PrevDecl)) { 11062 Diag(NameLoc, diag::ext_member_redeclared); 11063 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11064 } 11065 11066 if (!Invalid) { 11067 // If this is a use, just return the declaration we found, unless 11068 // we have attributes. 11069 11070 // FIXME: In the future, return a variant or some other clue 11071 // for the consumer of this Decl to know it doesn't own it. 11072 // For our current ASTs this shouldn't be a problem, but will 11073 // need to be changed with DeclGroups. 11074 if (!Attr && 11075 ((TUK == TUK_Reference && 11076 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11077 || TUK == TUK_Friend)) 11078 return PrevTagDecl; 11079 11080 // Diagnose attempts to redefine a tag. 11081 if (TUK == TUK_Definition) { 11082 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11083 // If we're defining a specialization and the previous definition 11084 // is from an implicit instantiation, don't emit an error 11085 // here; we'll catch this in the general case below. 11086 bool IsExplicitSpecializationAfterInstantiation = false; 11087 if (isExplicitSpecialization) { 11088 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11089 IsExplicitSpecializationAfterInstantiation = 11090 RD->getTemplateSpecializationKind() != 11091 TSK_ExplicitSpecialization; 11092 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11093 IsExplicitSpecializationAfterInstantiation = 11094 ED->getTemplateSpecializationKind() != 11095 TSK_ExplicitSpecialization; 11096 } 11097 11098 if (!IsExplicitSpecializationAfterInstantiation) { 11099 // A redeclaration in function prototype scope in C isn't 11100 // visible elsewhere, so merely issue a warning. 11101 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11102 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11103 else 11104 Diag(NameLoc, diag::err_redefinition) << Name; 11105 Diag(Def->getLocation(), diag::note_previous_definition); 11106 // If this is a redefinition, recover by making this 11107 // struct be anonymous, which will make any later 11108 // references get the previous definition. 11109 Name = nullptr; 11110 Previous.clear(); 11111 Invalid = true; 11112 } 11113 } else { 11114 // If the type is currently being defined, complain 11115 // about a nested redefinition. 11116 const TagType *Tag 11117 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 11118 if (Tag->isBeingDefined()) { 11119 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11120 Diag(PrevTagDecl->getLocation(), 11121 diag::note_previous_definition); 11122 Name = nullptr; 11123 Previous.clear(); 11124 Invalid = true; 11125 } 11126 } 11127 11128 // Okay, this is definition of a previously declared or referenced 11129 // tag. We're going to create a new Decl for it. 11130 } 11131 11132 // Okay, we're going to make a redeclaration. If this is some kind 11133 // of reference, make sure we build the redeclaration in the same DC 11134 // as the original, and ignore the current access specifier. 11135 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11136 SearchDC = PrevTagDecl->getDeclContext(); 11137 AS = AS_none; 11138 } 11139 } 11140 // If we get here we have (another) forward declaration or we 11141 // have a definition. Just create a new decl. 11142 11143 } else { 11144 // If we get here, this is a definition of a new tag type in a nested 11145 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11146 // new decl/type. We set PrevDecl to NULL so that the entities 11147 // have distinct types. 11148 Previous.clear(); 11149 } 11150 // If we get here, we're going to create a new Decl. If PrevDecl 11151 // is non-NULL, it's a definition of the tag declared by 11152 // PrevDecl. If it's NULL, we have a new definition. 11153 11154 11155 // Otherwise, PrevDecl is not a tag, but was found with tag 11156 // lookup. This is only actually possible in C++, where a few 11157 // things like templates still live in the tag namespace. 11158 } else { 11159 // Use a better diagnostic if an elaborated-type-specifier 11160 // found the wrong kind of type on the first 11161 // (non-redeclaration) lookup. 11162 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11163 !Previous.isForRedeclaration()) { 11164 unsigned Kind = 0; 11165 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11166 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11167 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11168 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11169 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11170 Invalid = true; 11171 11172 // Otherwise, only diagnose if the declaration is in scope. 11173 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11174 SS.isNotEmpty() || isExplicitSpecialization)) { 11175 // do nothing 11176 11177 // Diagnose implicit declarations introduced by elaborated types. 11178 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11179 unsigned Kind = 0; 11180 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11181 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11182 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11183 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11184 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11185 Invalid = true; 11186 11187 // Otherwise it's a declaration. Call out a particularly common 11188 // case here. 11189 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11190 unsigned Kind = 0; 11191 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11192 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11193 << Name << Kind << TND->getUnderlyingType(); 11194 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11195 Invalid = true; 11196 11197 // Otherwise, diagnose. 11198 } else { 11199 // The tag name clashes with something else in the target scope, 11200 // issue an error and recover by making this tag be anonymous. 11201 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11202 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11203 Name = nullptr; 11204 Invalid = true; 11205 } 11206 11207 // The existing declaration isn't relevant to us; we're in a 11208 // new scope, so clear out the previous declaration. 11209 Previous.clear(); 11210 } 11211 } 11212 11213 CreateNewDecl: 11214 11215 TagDecl *PrevDecl = nullptr; 11216 if (Previous.isSingleResult()) 11217 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11218 11219 // If there is an identifier, use the location of the identifier as the 11220 // location of the decl, otherwise use the location of the struct/union 11221 // keyword. 11222 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11223 11224 // Otherwise, create a new declaration. If there is a previous 11225 // declaration of the same entity, the two will be linked via 11226 // PrevDecl. 11227 TagDecl *New; 11228 11229 bool IsForwardReference = false; 11230 if (Kind == TTK_Enum) { 11231 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11232 // enum X { A, B, C } D; D should chain to X. 11233 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11234 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11235 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11236 // If this is an undefined enum, warn. 11237 if (TUK != TUK_Definition && !Invalid) { 11238 TagDecl *Def; 11239 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11240 cast<EnumDecl>(New)->isFixed()) { 11241 // C++0x: 7.2p2: opaque-enum-declaration. 11242 // Conflicts are diagnosed above. Do nothing. 11243 } 11244 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11245 Diag(Loc, diag::ext_forward_ref_enum_def) 11246 << New; 11247 Diag(Def->getLocation(), diag::note_previous_definition); 11248 } else { 11249 unsigned DiagID = diag::ext_forward_ref_enum; 11250 if (getLangOpts().MSVCCompat) 11251 DiagID = diag::ext_ms_forward_ref_enum; 11252 else if (getLangOpts().CPlusPlus) 11253 DiagID = diag::err_forward_ref_enum; 11254 Diag(Loc, DiagID); 11255 11256 // If this is a forward-declared reference to an enumeration, make a 11257 // note of it; we won't actually be introducing the declaration into 11258 // the declaration context. 11259 if (TUK == TUK_Reference) 11260 IsForwardReference = true; 11261 } 11262 } 11263 11264 if (EnumUnderlying) { 11265 EnumDecl *ED = cast<EnumDecl>(New); 11266 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11267 ED->setIntegerTypeSourceInfo(TI); 11268 else 11269 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11270 ED->setPromotionType(ED->getIntegerType()); 11271 } 11272 11273 } else { 11274 // struct/union/class 11275 11276 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11277 // struct X { int A; } D; D should chain to X. 11278 if (getLangOpts().CPlusPlus) { 11279 // FIXME: Look for a way to use RecordDecl for simple structs. 11280 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11281 cast_or_null<CXXRecordDecl>(PrevDecl)); 11282 11283 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11284 StdBadAlloc = cast<CXXRecordDecl>(New); 11285 } else 11286 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11287 cast_or_null<RecordDecl>(PrevDecl)); 11288 } 11289 11290 // C++11 [dcl.type]p3: 11291 // A type-specifier-seq shall not define a class or enumeration [...]. 11292 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11293 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11294 << Context.getTagDeclType(New); 11295 Invalid = true; 11296 } 11297 11298 // Maybe add qualifier info. 11299 if (SS.isNotEmpty()) { 11300 if (SS.isSet()) { 11301 // If this is either a declaration or a definition, check the 11302 // nested-name-specifier against the current context. We don't do this 11303 // for explicit specializations, because they have similar checking 11304 // (with more specific diagnostics) in the call to 11305 // CheckMemberSpecialization, below. 11306 if (!isExplicitSpecialization && 11307 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11308 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11309 Invalid = true; 11310 11311 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11312 if (TemplateParameterLists.size() > 0) { 11313 New->setTemplateParameterListsInfo(Context, 11314 TemplateParameterLists.size(), 11315 TemplateParameterLists.data()); 11316 } 11317 } 11318 else 11319 Invalid = true; 11320 } 11321 11322 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11323 // Add alignment attributes if necessary; these attributes are checked when 11324 // the ASTContext lays out the structure. 11325 // 11326 // It is important for implementing the correct semantics that this 11327 // happen here (in act on tag decl). The #pragma pack stack is 11328 // maintained as a result of parser callbacks which can occur at 11329 // many points during the parsing of a struct declaration (because 11330 // the #pragma tokens are effectively skipped over during the 11331 // parsing of the struct). 11332 if (TUK == TUK_Definition) { 11333 AddAlignmentAttributesForRecord(RD); 11334 AddMsStructLayoutForRecord(RD); 11335 } 11336 } 11337 11338 if (ModulePrivateLoc.isValid()) { 11339 if (isExplicitSpecialization) 11340 Diag(New->getLocation(), diag::err_module_private_specialization) 11341 << 2 11342 << FixItHint::CreateRemoval(ModulePrivateLoc); 11343 // __module_private__ does not apply to local classes. However, we only 11344 // diagnose this as an error when the declaration specifiers are 11345 // freestanding. Here, we just ignore the __module_private__. 11346 else if (!SearchDC->isFunctionOrMethod()) 11347 New->setModulePrivate(); 11348 } 11349 11350 // If this is a specialization of a member class (of a class template), 11351 // check the specialization. 11352 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11353 Invalid = true; 11354 11355 // If we're declaring or defining a tag in function prototype scope in C, 11356 // note that this type can only be used within the function and add it to 11357 // the list of decls to inject into the function definition scope. 11358 if ((Name || Kind == TTK_Enum) && 11359 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11360 if (getLangOpts().CPlusPlus) { 11361 // C++ [dcl.fct]p6: 11362 // Types shall not be defined in return or parameter types. 11363 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11364 Diag(Loc, diag::err_type_defined_in_param_type) 11365 << Name; 11366 Invalid = true; 11367 } 11368 } else { 11369 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11370 } 11371 DeclsInPrototypeScope.push_back(New); 11372 } 11373 11374 if (Invalid) 11375 New->setInvalidDecl(); 11376 11377 if (Attr) 11378 ProcessDeclAttributeList(S, New, Attr); 11379 11380 // Set the lexical context. If the tag has a C++ scope specifier, the 11381 // lexical context will be different from the semantic context. 11382 New->setLexicalDeclContext(CurContext); 11383 11384 // Mark this as a friend decl if applicable. 11385 // In Microsoft mode, a friend declaration also acts as a forward 11386 // declaration so we always pass true to setObjectOfFriendDecl to make 11387 // the tag name visible. 11388 if (TUK == TUK_Friend) 11389 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11390 getLangOpts().MicrosoftExt); 11391 11392 // Set the access specifier. 11393 if (!Invalid && SearchDC->isRecord()) 11394 SetMemberAccessSpecifier(New, PrevDecl, AS); 11395 11396 if (TUK == TUK_Definition) 11397 New->startDefinition(); 11398 11399 // If this has an identifier, add it to the scope stack. 11400 if (TUK == TUK_Friend) { 11401 // We might be replacing an existing declaration in the lookup tables; 11402 // if so, borrow its access specifier. 11403 if (PrevDecl) 11404 New->setAccess(PrevDecl->getAccess()); 11405 11406 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11407 DC->makeDeclVisibleInContext(New); 11408 if (Name) // can be null along some error paths 11409 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11410 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11411 } else if (Name) { 11412 S = getNonFieldDeclScope(S); 11413 PushOnScopeChains(New, S, !IsForwardReference); 11414 if (IsForwardReference) 11415 SearchDC->makeDeclVisibleInContext(New); 11416 11417 } else { 11418 CurContext->addDecl(New); 11419 } 11420 11421 // If this is the C FILE type, notify the AST context. 11422 if (IdentifierInfo *II = New->getIdentifier()) 11423 if (!New->isInvalidDecl() && 11424 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11425 II->isStr("FILE")) 11426 Context.setFILEDecl(New); 11427 11428 if (PrevDecl) 11429 mergeDeclAttributes(New, PrevDecl); 11430 11431 // If there's a #pragma GCC visibility in scope, set the visibility of this 11432 // record. 11433 AddPushedVisibilityAttribute(New); 11434 11435 OwnedDecl = true; 11436 // In C++, don't return an invalid declaration. We can't recover well from 11437 // the cases where we make the type anonymous. 11438 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11439 } 11440 11441 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11442 AdjustDeclIfTemplate(TagD); 11443 TagDecl *Tag = cast<TagDecl>(TagD); 11444 11445 // Enter the tag context. 11446 PushDeclContext(S, Tag); 11447 11448 ActOnDocumentableDecl(TagD); 11449 11450 // If there's a #pragma GCC visibility in scope, set the visibility of this 11451 // record. 11452 AddPushedVisibilityAttribute(Tag); 11453 } 11454 11455 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11456 assert(isa<ObjCContainerDecl>(IDecl) && 11457 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11458 DeclContext *OCD = cast<DeclContext>(IDecl); 11459 assert(getContainingDC(OCD) == CurContext && 11460 "The next DeclContext should be lexically contained in the current one."); 11461 CurContext = OCD; 11462 return IDecl; 11463 } 11464 11465 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11466 SourceLocation FinalLoc, 11467 bool IsFinalSpelledSealed, 11468 SourceLocation LBraceLoc) { 11469 AdjustDeclIfTemplate(TagD); 11470 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11471 11472 FieldCollector->StartClass(); 11473 11474 if (!Record->getIdentifier()) 11475 return; 11476 11477 if (FinalLoc.isValid()) 11478 Record->addAttr(new (Context) 11479 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11480 11481 // C++ [class]p2: 11482 // [...] The class-name is also inserted into the scope of the 11483 // class itself; this is known as the injected-class-name. For 11484 // purposes of access checking, the injected-class-name is treated 11485 // as if it were a public member name. 11486 CXXRecordDecl *InjectedClassName 11487 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11488 Record->getLocStart(), Record->getLocation(), 11489 Record->getIdentifier(), 11490 /*PrevDecl=*/nullptr, 11491 /*DelayTypeCreation=*/true); 11492 Context.getTypeDeclType(InjectedClassName, Record); 11493 InjectedClassName->setImplicit(); 11494 InjectedClassName->setAccess(AS_public); 11495 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11496 InjectedClassName->setDescribedClassTemplate(Template); 11497 PushOnScopeChains(InjectedClassName, S); 11498 assert(InjectedClassName->isInjectedClassName() && 11499 "Broken injected-class-name"); 11500 } 11501 11502 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11503 SourceLocation RBraceLoc) { 11504 AdjustDeclIfTemplate(TagD); 11505 TagDecl *Tag = cast<TagDecl>(TagD); 11506 Tag->setRBraceLoc(RBraceLoc); 11507 11508 // Make sure we "complete" the definition even it is invalid. 11509 if (Tag->isBeingDefined()) { 11510 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11511 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11512 RD->completeDefinition(); 11513 } 11514 11515 if (isa<CXXRecordDecl>(Tag)) 11516 FieldCollector->FinishClass(); 11517 11518 // Exit this scope of this tag's definition. 11519 PopDeclContext(); 11520 11521 if (getCurLexicalContext()->isObjCContainer() && 11522 Tag->getDeclContext()->isFileContext()) 11523 Tag->setTopLevelDeclInObjCContainer(); 11524 11525 // Notify the consumer that we've defined a tag. 11526 if (!Tag->isInvalidDecl()) 11527 Consumer.HandleTagDeclDefinition(Tag); 11528 } 11529 11530 void Sema::ActOnObjCContainerFinishDefinition() { 11531 // Exit this scope of this interface definition. 11532 PopDeclContext(); 11533 } 11534 11535 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11536 assert(DC == CurContext && "Mismatch of container contexts"); 11537 OriginalLexicalContext = DC; 11538 ActOnObjCContainerFinishDefinition(); 11539 } 11540 11541 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11542 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11543 OriginalLexicalContext = nullptr; 11544 } 11545 11546 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11547 AdjustDeclIfTemplate(TagD); 11548 TagDecl *Tag = cast<TagDecl>(TagD); 11549 Tag->setInvalidDecl(); 11550 11551 // Make sure we "complete" the definition even it is invalid. 11552 if (Tag->isBeingDefined()) { 11553 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11554 RD->completeDefinition(); 11555 } 11556 11557 // We're undoing ActOnTagStartDefinition here, not 11558 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11559 // the FieldCollector. 11560 11561 PopDeclContext(); 11562 } 11563 11564 // Note that FieldName may be null for anonymous bitfields. 11565 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11566 IdentifierInfo *FieldName, 11567 QualType FieldTy, bool IsMsStruct, 11568 Expr *BitWidth, bool *ZeroWidth) { 11569 // Default to true; that shouldn't confuse checks for emptiness 11570 if (ZeroWidth) 11571 *ZeroWidth = true; 11572 11573 // C99 6.7.2.1p4 - verify the field type. 11574 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11575 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11576 // Handle incomplete types with specific error. 11577 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11578 return ExprError(); 11579 if (FieldName) 11580 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11581 << FieldName << FieldTy << BitWidth->getSourceRange(); 11582 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11583 << FieldTy << BitWidth->getSourceRange(); 11584 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11585 UPPC_BitFieldWidth)) 11586 return ExprError(); 11587 11588 // If the bit-width is type- or value-dependent, don't try to check 11589 // it now. 11590 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11591 return BitWidth; 11592 11593 llvm::APSInt Value; 11594 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11595 if (ICE.isInvalid()) 11596 return ICE; 11597 BitWidth = ICE.get(); 11598 11599 if (Value != 0 && ZeroWidth) 11600 *ZeroWidth = false; 11601 11602 // Zero-width bitfield is ok for anonymous field. 11603 if (Value == 0 && FieldName) 11604 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11605 11606 if (Value.isSigned() && Value.isNegative()) { 11607 if (FieldName) 11608 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11609 << FieldName << Value.toString(10); 11610 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11611 << Value.toString(10); 11612 } 11613 11614 if (!FieldTy->isDependentType()) { 11615 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11616 if (Value.getZExtValue() > TypeSize) { 11617 if (!getLangOpts().CPlusPlus || IsMsStruct || 11618 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11619 if (FieldName) 11620 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11621 << FieldName << (unsigned)Value.getZExtValue() 11622 << (unsigned)TypeSize; 11623 11624 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11625 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11626 } 11627 11628 if (FieldName) 11629 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11630 << FieldName << (unsigned)Value.getZExtValue() 11631 << (unsigned)TypeSize; 11632 else 11633 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11634 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11635 } 11636 } 11637 11638 return BitWidth; 11639 } 11640 11641 /// ActOnField - Each field of a C struct/union is passed into this in order 11642 /// to create a FieldDecl object for it. 11643 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11644 Declarator &D, Expr *BitfieldWidth) { 11645 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11646 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11647 /*InitStyle=*/ICIS_NoInit, AS_public); 11648 return Res; 11649 } 11650 11651 /// HandleField - Analyze a field of a C struct or a C++ data member. 11652 /// 11653 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11654 SourceLocation DeclStart, 11655 Declarator &D, Expr *BitWidth, 11656 InClassInitStyle InitStyle, 11657 AccessSpecifier AS) { 11658 IdentifierInfo *II = D.getIdentifier(); 11659 SourceLocation Loc = DeclStart; 11660 if (II) Loc = D.getIdentifierLoc(); 11661 11662 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11663 QualType T = TInfo->getType(); 11664 if (getLangOpts().CPlusPlus) { 11665 CheckExtraCXXDefaultArguments(D); 11666 11667 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11668 UPPC_DataMemberType)) { 11669 D.setInvalidType(); 11670 T = Context.IntTy; 11671 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11672 } 11673 } 11674 11675 // TR 18037 does not allow fields to be declared with address spaces. 11676 if (T.getQualifiers().hasAddressSpace()) { 11677 Diag(Loc, diag::err_field_with_address_space); 11678 D.setInvalidType(); 11679 } 11680 11681 // OpenCL 1.2 spec, s6.9 r: 11682 // The event type cannot be used to declare a structure or union field. 11683 if (LangOpts.OpenCL && T->isEventT()) { 11684 Diag(Loc, diag::err_event_t_struct_field); 11685 D.setInvalidType(); 11686 } 11687 11688 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11689 11690 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11691 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11692 diag::err_invalid_thread) 11693 << DeclSpec::getSpecifierName(TSCS); 11694 11695 // Check to see if this name was declared as a member previously 11696 NamedDecl *PrevDecl = nullptr; 11697 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11698 LookupName(Previous, S); 11699 switch (Previous.getResultKind()) { 11700 case LookupResult::Found: 11701 case LookupResult::FoundUnresolvedValue: 11702 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11703 break; 11704 11705 case LookupResult::FoundOverloaded: 11706 PrevDecl = Previous.getRepresentativeDecl(); 11707 break; 11708 11709 case LookupResult::NotFound: 11710 case LookupResult::NotFoundInCurrentInstantiation: 11711 case LookupResult::Ambiguous: 11712 break; 11713 } 11714 Previous.suppressDiagnostics(); 11715 11716 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11717 // Maybe we will complain about the shadowed template parameter. 11718 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11719 // Just pretend that we didn't see the previous declaration. 11720 PrevDecl = nullptr; 11721 } 11722 11723 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11724 PrevDecl = nullptr; 11725 11726 bool Mutable 11727 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11728 SourceLocation TSSL = D.getLocStart(); 11729 FieldDecl *NewFD 11730 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11731 TSSL, AS, PrevDecl, &D); 11732 11733 if (NewFD->isInvalidDecl()) 11734 Record->setInvalidDecl(); 11735 11736 if (D.getDeclSpec().isModulePrivateSpecified()) 11737 NewFD->setModulePrivate(); 11738 11739 if (NewFD->isInvalidDecl() && PrevDecl) { 11740 // Don't introduce NewFD into scope; there's already something 11741 // with the same name in the same scope. 11742 } else if (II) { 11743 PushOnScopeChains(NewFD, S); 11744 } else 11745 Record->addDecl(NewFD); 11746 11747 return NewFD; 11748 } 11749 11750 /// \brief Build a new FieldDecl and check its well-formedness. 11751 /// 11752 /// This routine builds a new FieldDecl given the fields name, type, 11753 /// record, etc. \p PrevDecl should refer to any previous declaration 11754 /// with the same name and in the same scope as the field to be 11755 /// created. 11756 /// 11757 /// \returns a new FieldDecl. 11758 /// 11759 /// \todo The Declarator argument is a hack. It will be removed once 11760 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11761 TypeSourceInfo *TInfo, 11762 RecordDecl *Record, SourceLocation Loc, 11763 bool Mutable, Expr *BitWidth, 11764 InClassInitStyle InitStyle, 11765 SourceLocation TSSL, 11766 AccessSpecifier AS, NamedDecl *PrevDecl, 11767 Declarator *D) { 11768 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11769 bool InvalidDecl = false; 11770 if (D) InvalidDecl = D->isInvalidType(); 11771 11772 // If we receive a broken type, recover by assuming 'int' and 11773 // marking this declaration as invalid. 11774 if (T.isNull()) { 11775 InvalidDecl = true; 11776 T = Context.IntTy; 11777 } 11778 11779 QualType EltTy = Context.getBaseElementType(T); 11780 if (!EltTy->isDependentType()) { 11781 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11782 // Fields of incomplete type force their record to be invalid. 11783 Record->setInvalidDecl(); 11784 InvalidDecl = true; 11785 } else { 11786 NamedDecl *Def; 11787 EltTy->isIncompleteType(&Def); 11788 if (Def && Def->isInvalidDecl()) { 11789 Record->setInvalidDecl(); 11790 InvalidDecl = true; 11791 } 11792 } 11793 } 11794 11795 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11796 if (BitWidth && getLangOpts().OpenCL) { 11797 Diag(Loc, diag::err_opencl_bitfields); 11798 InvalidDecl = true; 11799 } 11800 11801 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11802 // than a variably modified type. 11803 if (!InvalidDecl && T->isVariablyModifiedType()) { 11804 bool SizeIsNegative; 11805 llvm::APSInt Oversized; 11806 11807 TypeSourceInfo *FixedTInfo = 11808 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11809 SizeIsNegative, 11810 Oversized); 11811 if (FixedTInfo) { 11812 Diag(Loc, diag::warn_illegal_constant_array_size); 11813 TInfo = FixedTInfo; 11814 T = FixedTInfo->getType(); 11815 } else { 11816 if (SizeIsNegative) 11817 Diag(Loc, diag::err_typecheck_negative_array_size); 11818 else if (Oversized.getBoolValue()) 11819 Diag(Loc, diag::err_array_too_large) 11820 << Oversized.toString(10); 11821 else 11822 Diag(Loc, diag::err_typecheck_field_variable_size); 11823 InvalidDecl = true; 11824 } 11825 } 11826 11827 // Fields can not have abstract class types 11828 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11829 diag::err_abstract_type_in_decl, 11830 AbstractFieldType)) 11831 InvalidDecl = true; 11832 11833 bool ZeroWidth = false; 11834 // If this is declared as a bit-field, check the bit-field. 11835 if (!InvalidDecl && BitWidth) { 11836 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11837 &ZeroWidth).get(); 11838 if (!BitWidth) { 11839 InvalidDecl = true; 11840 BitWidth = nullptr; 11841 ZeroWidth = false; 11842 } 11843 } 11844 11845 // Check that 'mutable' is consistent with the type of the declaration. 11846 if (!InvalidDecl && Mutable) { 11847 unsigned DiagID = 0; 11848 if (T->isReferenceType()) 11849 DiagID = diag::err_mutable_reference; 11850 else if (T.isConstQualified()) 11851 DiagID = diag::err_mutable_const; 11852 11853 if (DiagID) { 11854 SourceLocation ErrLoc = Loc; 11855 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11856 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11857 Diag(ErrLoc, DiagID); 11858 Mutable = false; 11859 InvalidDecl = true; 11860 } 11861 } 11862 11863 // C++11 [class.union]p8 (DR1460): 11864 // At most one variant member of a union may have a 11865 // brace-or-equal-initializer. 11866 if (InitStyle != ICIS_NoInit) 11867 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11868 11869 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11870 BitWidth, Mutable, InitStyle); 11871 if (InvalidDecl) 11872 NewFD->setInvalidDecl(); 11873 11874 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11875 Diag(Loc, diag::err_duplicate_member) << II; 11876 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11877 NewFD->setInvalidDecl(); 11878 } 11879 11880 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11881 if (Record->isUnion()) { 11882 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11883 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11884 if (RDecl->getDefinition()) { 11885 // C++ [class.union]p1: An object of a class with a non-trivial 11886 // constructor, a non-trivial copy constructor, a non-trivial 11887 // destructor, or a non-trivial copy assignment operator 11888 // cannot be a member of a union, nor can an array of such 11889 // objects. 11890 if (CheckNontrivialField(NewFD)) 11891 NewFD->setInvalidDecl(); 11892 } 11893 } 11894 11895 // C++ [class.union]p1: If a union contains a member of reference type, 11896 // the program is ill-formed, except when compiling with MSVC extensions 11897 // enabled. 11898 if (EltTy->isReferenceType()) { 11899 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11900 diag::ext_union_member_of_reference_type : 11901 diag::err_union_member_of_reference_type) 11902 << NewFD->getDeclName() << EltTy; 11903 if (!getLangOpts().MicrosoftExt) 11904 NewFD->setInvalidDecl(); 11905 } 11906 } 11907 } 11908 11909 // FIXME: We need to pass in the attributes given an AST 11910 // representation, not a parser representation. 11911 if (D) { 11912 // FIXME: The current scope is almost... but not entirely... correct here. 11913 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11914 11915 if (NewFD->hasAttrs()) 11916 CheckAlignasUnderalignment(NewFD); 11917 } 11918 11919 // In auto-retain/release, infer strong retension for fields of 11920 // retainable type. 11921 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11922 NewFD->setInvalidDecl(); 11923 11924 if (T.isObjCGCWeak()) 11925 Diag(Loc, diag::warn_attribute_weak_on_field); 11926 11927 NewFD->setAccess(AS); 11928 return NewFD; 11929 } 11930 11931 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11932 assert(FD); 11933 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11934 11935 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11936 return false; 11937 11938 QualType EltTy = Context.getBaseElementType(FD->getType()); 11939 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11940 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11941 if (RDecl->getDefinition()) { 11942 // We check for copy constructors before constructors 11943 // because otherwise we'll never get complaints about 11944 // copy constructors. 11945 11946 CXXSpecialMember member = CXXInvalid; 11947 // We're required to check for any non-trivial constructors. Since the 11948 // implicit default constructor is suppressed if there are any 11949 // user-declared constructors, we just need to check that there is a 11950 // trivial default constructor and a trivial copy constructor. (We don't 11951 // worry about move constructors here, since this is a C++98 check.) 11952 if (RDecl->hasNonTrivialCopyConstructor()) 11953 member = CXXCopyConstructor; 11954 else if (!RDecl->hasTrivialDefaultConstructor()) 11955 member = CXXDefaultConstructor; 11956 else if (RDecl->hasNonTrivialCopyAssignment()) 11957 member = CXXCopyAssignment; 11958 else if (RDecl->hasNonTrivialDestructor()) 11959 member = CXXDestructor; 11960 11961 if (member != CXXInvalid) { 11962 if (!getLangOpts().CPlusPlus11 && 11963 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11964 // Objective-C++ ARC: it is an error to have a non-trivial field of 11965 // a union. However, system headers in Objective-C programs 11966 // occasionally have Objective-C lifetime objects within unions, 11967 // and rather than cause the program to fail, we make those 11968 // members unavailable. 11969 SourceLocation Loc = FD->getLocation(); 11970 if (getSourceManager().isInSystemHeader(Loc)) { 11971 if (!FD->hasAttr<UnavailableAttr>()) 11972 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11973 "this system field has retaining ownership", 11974 Loc)); 11975 return false; 11976 } 11977 } 11978 11979 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11980 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11981 diag::err_illegal_union_or_anon_struct_member) 11982 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11983 DiagnoseNontrivial(RDecl, member); 11984 return !getLangOpts().CPlusPlus11; 11985 } 11986 } 11987 } 11988 11989 return false; 11990 } 11991 11992 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11993 /// AST enum value. 11994 static ObjCIvarDecl::AccessControl 11995 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11996 switch (ivarVisibility) { 11997 default: llvm_unreachable("Unknown visitibility kind"); 11998 case tok::objc_private: return ObjCIvarDecl::Private; 11999 case tok::objc_public: return ObjCIvarDecl::Public; 12000 case tok::objc_protected: return ObjCIvarDecl::Protected; 12001 case tok::objc_package: return ObjCIvarDecl::Package; 12002 } 12003 } 12004 12005 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12006 /// in order to create an IvarDecl object for it. 12007 Decl *Sema::ActOnIvar(Scope *S, 12008 SourceLocation DeclStart, 12009 Declarator &D, Expr *BitfieldWidth, 12010 tok::ObjCKeywordKind Visibility) { 12011 12012 IdentifierInfo *II = D.getIdentifier(); 12013 Expr *BitWidth = (Expr*)BitfieldWidth; 12014 SourceLocation Loc = DeclStart; 12015 if (II) Loc = D.getIdentifierLoc(); 12016 12017 // FIXME: Unnamed fields can be handled in various different ways, for 12018 // example, unnamed unions inject all members into the struct namespace! 12019 12020 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12021 QualType T = TInfo->getType(); 12022 12023 if (BitWidth) { 12024 // 6.7.2.1p3, 6.7.2.1p4 12025 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12026 if (!BitWidth) 12027 D.setInvalidType(); 12028 } else { 12029 // Not a bitfield. 12030 12031 // validate II. 12032 12033 } 12034 if (T->isReferenceType()) { 12035 Diag(Loc, diag::err_ivar_reference_type); 12036 D.setInvalidType(); 12037 } 12038 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12039 // than a variably modified type. 12040 else if (T->isVariablyModifiedType()) { 12041 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12042 D.setInvalidType(); 12043 } 12044 12045 // Get the visibility (access control) for this ivar. 12046 ObjCIvarDecl::AccessControl ac = 12047 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12048 : ObjCIvarDecl::None; 12049 // Must set ivar's DeclContext to its enclosing interface. 12050 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12051 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12052 return nullptr; 12053 ObjCContainerDecl *EnclosingContext; 12054 if (ObjCImplementationDecl *IMPDecl = 12055 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12056 if (LangOpts.ObjCRuntime.isFragile()) { 12057 // Case of ivar declared in an implementation. Context is that of its class. 12058 EnclosingContext = IMPDecl->getClassInterface(); 12059 assert(EnclosingContext && "Implementation has no class interface!"); 12060 } 12061 else 12062 EnclosingContext = EnclosingDecl; 12063 } else { 12064 if (ObjCCategoryDecl *CDecl = 12065 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12066 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12067 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12068 return nullptr; 12069 } 12070 } 12071 EnclosingContext = EnclosingDecl; 12072 } 12073 12074 // Construct the decl. 12075 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12076 DeclStart, Loc, II, T, 12077 TInfo, ac, (Expr *)BitfieldWidth); 12078 12079 if (II) { 12080 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12081 ForRedeclaration); 12082 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12083 && !isa<TagDecl>(PrevDecl)) { 12084 Diag(Loc, diag::err_duplicate_member) << II; 12085 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12086 NewID->setInvalidDecl(); 12087 } 12088 } 12089 12090 // Process attributes attached to the ivar. 12091 ProcessDeclAttributes(S, NewID, D); 12092 12093 if (D.isInvalidType()) 12094 NewID->setInvalidDecl(); 12095 12096 // In ARC, infer 'retaining' for ivars of retainable type. 12097 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12098 NewID->setInvalidDecl(); 12099 12100 if (D.getDeclSpec().isModulePrivateSpecified()) 12101 NewID->setModulePrivate(); 12102 12103 if (II) { 12104 // FIXME: When interfaces are DeclContexts, we'll need to add 12105 // these to the interface. 12106 S->AddDecl(NewID); 12107 IdResolver.AddDecl(NewID); 12108 } 12109 12110 if (LangOpts.ObjCRuntime.isNonFragile() && 12111 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12112 Diag(Loc, diag::warn_ivars_in_interface); 12113 12114 return NewID; 12115 } 12116 12117 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12118 /// class and class extensions. For every class \@interface and class 12119 /// extension \@interface, if the last ivar is a bitfield of any type, 12120 /// then add an implicit `char :0` ivar to the end of that interface. 12121 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12122 SmallVectorImpl<Decl *> &AllIvarDecls) { 12123 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12124 return; 12125 12126 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12127 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12128 12129 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12130 return; 12131 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12132 if (!ID) { 12133 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12134 if (!CD->IsClassExtension()) 12135 return; 12136 } 12137 // No need to add this to end of @implementation. 12138 else 12139 return; 12140 } 12141 // All conditions are met. Add a new bitfield to the tail end of ivars. 12142 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12143 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12144 12145 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12146 DeclLoc, DeclLoc, nullptr, 12147 Context.CharTy, 12148 Context.getTrivialTypeSourceInfo(Context.CharTy, 12149 DeclLoc), 12150 ObjCIvarDecl::Private, BW, 12151 true); 12152 AllIvarDecls.push_back(Ivar); 12153 } 12154 12155 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12156 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12157 SourceLocation RBrac, AttributeList *Attr) { 12158 assert(EnclosingDecl && "missing record or interface decl"); 12159 12160 // If this is an Objective-C @implementation or category and we have 12161 // new fields here we should reset the layout of the interface since 12162 // it will now change. 12163 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12164 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12165 switch (DC->getKind()) { 12166 default: break; 12167 case Decl::ObjCCategory: 12168 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12169 break; 12170 case Decl::ObjCImplementation: 12171 Context. 12172 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12173 break; 12174 } 12175 } 12176 12177 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12178 12179 // Start counting up the number of named members; make sure to include 12180 // members of anonymous structs and unions in the total. 12181 unsigned NumNamedMembers = 0; 12182 if (Record) { 12183 for (const auto *I : Record->decls()) { 12184 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12185 if (IFD->getDeclName()) 12186 ++NumNamedMembers; 12187 } 12188 } 12189 12190 // Verify that all the fields are okay. 12191 SmallVector<FieldDecl*, 32> RecFields; 12192 12193 bool ARCErrReported = false; 12194 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12195 i != end; ++i) { 12196 FieldDecl *FD = cast<FieldDecl>(*i); 12197 12198 // Get the type for the field. 12199 const Type *FDTy = FD->getType().getTypePtr(); 12200 12201 if (!FD->isAnonymousStructOrUnion()) { 12202 // Remember all fields written by the user. 12203 RecFields.push_back(FD); 12204 } 12205 12206 // If the field is already invalid for some reason, don't emit more 12207 // diagnostics about it. 12208 if (FD->isInvalidDecl()) { 12209 EnclosingDecl->setInvalidDecl(); 12210 continue; 12211 } 12212 12213 // C99 6.7.2.1p2: 12214 // A structure or union shall not contain a member with 12215 // incomplete or function type (hence, a structure shall not 12216 // contain an instance of itself, but may contain a pointer to 12217 // an instance of itself), except that the last member of a 12218 // structure with more than one named member may have incomplete 12219 // array type; such a structure (and any union containing, 12220 // possibly recursively, a member that is such a structure) 12221 // shall not be a member of a structure or an element of an 12222 // array. 12223 if (FDTy->isFunctionType()) { 12224 // Field declared as a function. 12225 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12226 << FD->getDeclName(); 12227 FD->setInvalidDecl(); 12228 EnclosingDecl->setInvalidDecl(); 12229 continue; 12230 } else if (FDTy->isIncompleteArrayType() && Record && 12231 ((i + 1 == Fields.end() && !Record->isUnion()) || 12232 ((getLangOpts().MicrosoftExt || 12233 getLangOpts().CPlusPlus) && 12234 (i + 1 == Fields.end() || Record->isUnion())))) { 12235 // Flexible array member. 12236 // Microsoft and g++ is more permissive regarding flexible array. 12237 // It will accept flexible array in union and also 12238 // as the sole element of a struct/class. 12239 unsigned DiagID = 0; 12240 if (Record->isUnion()) 12241 DiagID = getLangOpts().MicrosoftExt 12242 ? diag::ext_flexible_array_union_ms 12243 : getLangOpts().CPlusPlus 12244 ? diag::ext_flexible_array_union_gnu 12245 : diag::err_flexible_array_union; 12246 else if (Fields.size() == 1) 12247 DiagID = getLangOpts().MicrosoftExt 12248 ? diag::ext_flexible_array_empty_aggregate_ms 12249 : getLangOpts().CPlusPlus 12250 ? diag::ext_flexible_array_empty_aggregate_gnu 12251 : NumNamedMembers < 1 12252 ? diag::err_flexible_array_empty_aggregate 12253 : 0; 12254 12255 if (DiagID) 12256 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12257 << Record->getTagKind(); 12258 // While the layout of types that contain virtual bases is not specified 12259 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12260 // virtual bases after the derived members. This would make a flexible 12261 // array member declared at the end of an object not adjacent to the end 12262 // of the type. 12263 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12264 if (RD->getNumVBases() != 0) 12265 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12266 << FD->getDeclName() << Record->getTagKind(); 12267 if (!getLangOpts().C99) 12268 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12269 << FD->getDeclName() << Record->getTagKind(); 12270 12271 // If the element type has a non-trivial destructor, we would not 12272 // implicitly destroy the elements, so disallow it for now. 12273 // 12274 // FIXME: GCC allows this. We should probably either implicitly delete 12275 // the destructor of the containing class, or just allow this. 12276 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12277 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12278 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12279 << FD->getDeclName() << FD->getType(); 12280 FD->setInvalidDecl(); 12281 EnclosingDecl->setInvalidDecl(); 12282 continue; 12283 } 12284 // Okay, we have a legal flexible array member at the end of the struct. 12285 if (Record) 12286 Record->setHasFlexibleArrayMember(true); 12287 } else if (!FDTy->isDependentType() && 12288 RequireCompleteType(FD->getLocation(), FD->getType(), 12289 diag::err_field_incomplete)) { 12290 // Incomplete type 12291 FD->setInvalidDecl(); 12292 EnclosingDecl->setInvalidDecl(); 12293 continue; 12294 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12295 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12296 // If this is a member of a union, then entire union becomes "flexible". 12297 if (Record && Record->isUnion()) { 12298 Record->setHasFlexibleArrayMember(true); 12299 } else { 12300 // If this is a struct/class and this is not the last element, reject 12301 // it. Note that GCC supports variable sized arrays in the middle of 12302 // structures. 12303 if (i + 1 != Fields.end()) 12304 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12305 << FD->getDeclName() << FD->getType(); 12306 else { 12307 // We support flexible arrays at the end of structs in 12308 // other structs as an extension. 12309 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12310 << FD->getDeclName(); 12311 if (Record) 12312 Record->setHasFlexibleArrayMember(true); 12313 } 12314 } 12315 } 12316 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12317 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12318 diag::err_abstract_type_in_decl, 12319 AbstractIvarType)) { 12320 // Ivars can not have abstract class types 12321 FD->setInvalidDecl(); 12322 } 12323 if (Record && FDTTy->getDecl()->hasObjectMember()) 12324 Record->setHasObjectMember(true); 12325 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12326 Record->setHasVolatileMember(true); 12327 } else if (FDTy->isObjCObjectType()) { 12328 /// A field cannot be an Objective-c object 12329 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12330 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12331 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12332 FD->setType(T); 12333 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12334 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12335 // It's an error in ARC if a field has lifetime. 12336 // We don't want to report this in a system header, though, 12337 // so we just make the field unavailable. 12338 // FIXME: that's really not sufficient; we need to make the type 12339 // itself invalid to, say, initialize or copy. 12340 QualType T = FD->getType(); 12341 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12342 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12343 SourceLocation loc = FD->getLocation(); 12344 if (getSourceManager().isInSystemHeader(loc)) { 12345 if (!FD->hasAttr<UnavailableAttr>()) { 12346 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12347 "this system field has retaining ownership", 12348 loc)); 12349 } 12350 } else { 12351 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12352 << T->isBlockPointerType() << Record->getTagKind(); 12353 } 12354 ARCErrReported = true; 12355 } 12356 } else if (getLangOpts().ObjC1 && 12357 getLangOpts().getGC() != LangOptions::NonGC && 12358 Record && !Record->hasObjectMember()) { 12359 if (FD->getType()->isObjCObjectPointerType() || 12360 FD->getType().isObjCGCStrong()) 12361 Record->setHasObjectMember(true); 12362 else if (Context.getAsArrayType(FD->getType())) { 12363 QualType BaseType = Context.getBaseElementType(FD->getType()); 12364 if (BaseType->isRecordType() && 12365 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12366 Record->setHasObjectMember(true); 12367 else if (BaseType->isObjCObjectPointerType() || 12368 BaseType.isObjCGCStrong()) 12369 Record->setHasObjectMember(true); 12370 } 12371 } 12372 if (Record && FD->getType().isVolatileQualified()) 12373 Record->setHasVolatileMember(true); 12374 // Keep track of the number of named members. 12375 if (FD->getIdentifier()) 12376 ++NumNamedMembers; 12377 } 12378 12379 // Okay, we successfully defined 'Record'. 12380 if (Record) { 12381 bool Completed = false; 12382 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12383 if (!CXXRecord->isInvalidDecl()) { 12384 // Set access bits correctly on the directly-declared conversions. 12385 for (CXXRecordDecl::conversion_iterator 12386 I = CXXRecord->conversion_begin(), 12387 E = CXXRecord->conversion_end(); I != E; ++I) 12388 I.setAccess((*I)->getAccess()); 12389 12390 if (!CXXRecord->isDependentType()) { 12391 if (CXXRecord->hasUserDeclaredDestructor()) { 12392 // Adjust user-defined destructor exception spec. 12393 if (getLangOpts().CPlusPlus11) 12394 AdjustDestructorExceptionSpec(CXXRecord, 12395 CXXRecord->getDestructor()); 12396 } 12397 12398 // Add any implicitly-declared members to this class. 12399 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12400 12401 // If we have virtual base classes, we may end up finding multiple 12402 // final overriders for a given virtual function. Check for this 12403 // problem now. 12404 if (CXXRecord->getNumVBases()) { 12405 CXXFinalOverriderMap FinalOverriders; 12406 CXXRecord->getFinalOverriders(FinalOverriders); 12407 12408 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12409 MEnd = FinalOverriders.end(); 12410 M != MEnd; ++M) { 12411 for (OverridingMethods::iterator SO = M->second.begin(), 12412 SOEnd = M->second.end(); 12413 SO != SOEnd; ++SO) { 12414 assert(SO->second.size() > 0 && 12415 "Virtual function without overridding functions?"); 12416 if (SO->second.size() == 1) 12417 continue; 12418 12419 // C++ [class.virtual]p2: 12420 // In a derived class, if a virtual member function of a base 12421 // class subobject has more than one final overrider the 12422 // program is ill-formed. 12423 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12424 << (const NamedDecl *)M->first << Record; 12425 Diag(M->first->getLocation(), 12426 diag::note_overridden_virtual_function); 12427 for (OverridingMethods::overriding_iterator 12428 OM = SO->second.begin(), 12429 OMEnd = SO->second.end(); 12430 OM != OMEnd; ++OM) 12431 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12432 << (const NamedDecl *)M->first << OM->Method->getParent(); 12433 12434 Record->setInvalidDecl(); 12435 } 12436 } 12437 CXXRecord->completeDefinition(&FinalOverriders); 12438 Completed = true; 12439 } 12440 } 12441 } 12442 } 12443 12444 if (!Completed) 12445 Record->completeDefinition(); 12446 12447 if (Record->hasAttrs()) { 12448 CheckAlignasUnderalignment(Record); 12449 12450 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12451 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12452 IA->getRange(), IA->getBestCase(), 12453 IA->getSemanticSpelling()); 12454 } 12455 12456 // Check if the structure/union declaration is a type that can have zero 12457 // size in C. For C this is a language extension, for C++ it may cause 12458 // compatibility problems. 12459 bool CheckForZeroSize; 12460 if (!getLangOpts().CPlusPlus) { 12461 CheckForZeroSize = true; 12462 } else { 12463 // For C++ filter out types that cannot be referenced in C code. 12464 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12465 CheckForZeroSize = 12466 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12467 !CXXRecord->isDependentType() && 12468 CXXRecord->isCLike(); 12469 } 12470 if (CheckForZeroSize) { 12471 bool ZeroSize = true; 12472 bool IsEmpty = true; 12473 unsigned NonBitFields = 0; 12474 for (RecordDecl::field_iterator I = Record->field_begin(), 12475 E = Record->field_end(); 12476 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12477 IsEmpty = false; 12478 if (I->isUnnamedBitfield()) { 12479 if (I->getBitWidthValue(Context) > 0) 12480 ZeroSize = false; 12481 } else { 12482 ++NonBitFields; 12483 QualType FieldType = I->getType(); 12484 if (FieldType->isIncompleteType() || 12485 !Context.getTypeSizeInChars(FieldType).isZero()) 12486 ZeroSize = false; 12487 } 12488 } 12489 12490 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12491 // allowed in C++, but warn if its declaration is inside 12492 // extern "C" block. 12493 if (ZeroSize) { 12494 Diag(RecLoc, getLangOpts().CPlusPlus ? 12495 diag::warn_zero_size_struct_union_in_extern_c : 12496 diag::warn_zero_size_struct_union_compat) 12497 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12498 } 12499 12500 // Structs without named members are extension in C (C99 6.7.2.1p7), 12501 // but are accepted by GCC. 12502 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12503 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12504 diag::ext_no_named_members_in_struct_union) 12505 << Record->isUnion(); 12506 } 12507 } 12508 } else { 12509 ObjCIvarDecl **ClsFields = 12510 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12511 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12512 ID->setEndOfDefinitionLoc(RBrac); 12513 // Add ivar's to class's DeclContext. 12514 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12515 ClsFields[i]->setLexicalDeclContext(ID); 12516 ID->addDecl(ClsFields[i]); 12517 } 12518 // Must enforce the rule that ivars in the base classes may not be 12519 // duplicates. 12520 if (ID->getSuperClass()) 12521 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12522 } else if (ObjCImplementationDecl *IMPDecl = 12523 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12524 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12525 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12526 // Ivar declared in @implementation never belongs to the implementation. 12527 // Only it is in implementation's lexical context. 12528 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12529 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12530 IMPDecl->setIvarLBraceLoc(LBrac); 12531 IMPDecl->setIvarRBraceLoc(RBrac); 12532 } else if (ObjCCategoryDecl *CDecl = 12533 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12534 // case of ivars in class extension; all other cases have been 12535 // reported as errors elsewhere. 12536 // FIXME. Class extension does not have a LocEnd field. 12537 // CDecl->setLocEnd(RBrac); 12538 // Add ivar's to class extension's DeclContext. 12539 // Diagnose redeclaration of private ivars. 12540 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12541 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12542 if (IDecl) { 12543 if (const ObjCIvarDecl *ClsIvar = 12544 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12545 Diag(ClsFields[i]->getLocation(), 12546 diag::err_duplicate_ivar_declaration); 12547 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12548 continue; 12549 } 12550 for (const auto *Ext : IDecl->known_extensions()) { 12551 if (const ObjCIvarDecl *ClsExtIvar 12552 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12553 Diag(ClsFields[i]->getLocation(), 12554 diag::err_duplicate_ivar_declaration); 12555 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12556 continue; 12557 } 12558 } 12559 } 12560 ClsFields[i]->setLexicalDeclContext(CDecl); 12561 CDecl->addDecl(ClsFields[i]); 12562 } 12563 CDecl->setIvarLBraceLoc(LBrac); 12564 CDecl->setIvarRBraceLoc(RBrac); 12565 } 12566 } 12567 12568 if (Attr) 12569 ProcessDeclAttributeList(S, Record, Attr); 12570 } 12571 12572 /// \brief Determine whether the given integral value is representable within 12573 /// the given type T. 12574 static bool isRepresentableIntegerValue(ASTContext &Context, 12575 llvm::APSInt &Value, 12576 QualType T) { 12577 assert(T->isIntegralType(Context) && "Integral type required!"); 12578 unsigned BitWidth = Context.getIntWidth(T); 12579 12580 if (Value.isUnsigned() || Value.isNonNegative()) { 12581 if (T->isSignedIntegerOrEnumerationType()) 12582 --BitWidth; 12583 return Value.getActiveBits() <= BitWidth; 12584 } 12585 return Value.getMinSignedBits() <= BitWidth; 12586 } 12587 12588 // \brief Given an integral type, return the next larger integral type 12589 // (or a NULL type of no such type exists). 12590 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12591 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12592 // enum checking below. 12593 assert(T->isIntegralType(Context) && "Integral type required!"); 12594 const unsigned NumTypes = 4; 12595 QualType SignedIntegralTypes[NumTypes] = { 12596 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12597 }; 12598 QualType UnsignedIntegralTypes[NumTypes] = { 12599 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12600 Context.UnsignedLongLongTy 12601 }; 12602 12603 unsigned BitWidth = Context.getTypeSize(T); 12604 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12605 : UnsignedIntegralTypes; 12606 for (unsigned I = 0; I != NumTypes; ++I) 12607 if (Context.getTypeSize(Types[I]) > BitWidth) 12608 return Types[I]; 12609 12610 return QualType(); 12611 } 12612 12613 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12614 EnumConstantDecl *LastEnumConst, 12615 SourceLocation IdLoc, 12616 IdentifierInfo *Id, 12617 Expr *Val) { 12618 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12619 llvm::APSInt EnumVal(IntWidth); 12620 QualType EltTy; 12621 12622 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12623 Val = nullptr; 12624 12625 if (Val) 12626 Val = DefaultLvalueConversion(Val).get(); 12627 12628 if (Val) { 12629 if (Enum->isDependentType() || Val->isTypeDependent()) 12630 EltTy = Context.DependentTy; 12631 else { 12632 SourceLocation ExpLoc; 12633 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12634 !getLangOpts().MSVCCompat) { 12635 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12636 // constant-expression in the enumerator-definition shall be a converted 12637 // constant expression of the underlying type. 12638 EltTy = Enum->getIntegerType(); 12639 ExprResult Converted = 12640 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12641 CCEK_Enumerator); 12642 if (Converted.isInvalid()) 12643 Val = nullptr; 12644 else 12645 Val = Converted.get(); 12646 } else if (!Val->isValueDependent() && 12647 !(Val = VerifyIntegerConstantExpression(Val, 12648 &EnumVal).get())) { 12649 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12650 } else { 12651 if (Enum->isFixed()) { 12652 EltTy = Enum->getIntegerType(); 12653 12654 // In Obj-C and Microsoft mode, require the enumeration value to be 12655 // representable in the underlying type of the enumeration. In C++11, 12656 // we perform a non-narrowing conversion as part of converted constant 12657 // expression checking. 12658 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12659 if (getLangOpts().MSVCCompat) { 12660 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12661 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 12662 } else 12663 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12664 } else 12665 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 12666 } else if (getLangOpts().CPlusPlus) { 12667 // C++11 [dcl.enum]p5: 12668 // If the underlying type is not fixed, the type of each enumerator 12669 // is the type of its initializing value: 12670 // - If an initializer is specified for an enumerator, the 12671 // initializing value has the same type as the expression. 12672 EltTy = Val->getType(); 12673 } else { 12674 // C99 6.7.2.2p2: 12675 // The expression that defines the value of an enumeration constant 12676 // shall be an integer constant expression that has a value 12677 // representable as an int. 12678 12679 // Complain if the value is not representable in an int. 12680 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12681 Diag(IdLoc, diag::ext_enum_value_not_int) 12682 << EnumVal.toString(10) << Val->getSourceRange() 12683 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12684 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12685 // Force the type of the expression to 'int'. 12686 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 12687 } 12688 EltTy = Val->getType(); 12689 } 12690 } 12691 } 12692 } 12693 12694 if (!Val) { 12695 if (Enum->isDependentType()) 12696 EltTy = Context.DependentTy; 12697 else if (!LastEnumConst) { 12698 // C++0x [dcl.enum]p5: 12699 // If the underlying type is not fixed, the type of each enumerator 12700 // is the type of its initializing value: 12701 // - If no initializer is specified for the first enumerator, the 12702 // initializing value has an unspecified integral type. 12703 // 12704 // GCC uses 'int' for its unspecified integral type, as does 12705 // C99 6.7.2.2p3. 12706 if (Enum->isFixed()) { 12707 EltTy = Enum->getIntegerType(); 12708 } 12709 else { 12710 EltTy = Context.IntTy; 12711 } 12712 } else { 12713 // Assign the last value + 1. 12714 EnumVal = LastEnumConst->getInitVal(); 12715 ++EnumVal; 12716 EltTy = LastEnumConst->getType(); 12717 12718 // Check for overflow on increment. 12719 if (EnumVal < LastEnumConst->getInitVal()) { 12720 // C++0x [dcl.enum]p5: 12721 // If the underlying type is not fixed, the type of each enumerator 12722 // is the type of its initializing value: 12723 // 12724 // - Otherwise the type of the initializing value is the same as 12725 // the type of the initializing value of the preceding enumerator 12726 // unless the incremented value is not representable in that type, 12727 // in which case the type is an unspecified integral type 12728 // sufficient to contain the incremented value. If no such type 12729 // exists, the program is ill-formed. 12730 QualType T = getNextLargerIntegralType(Context, EltTy); 12731 if (T.isNull() || Enum->isFixed()) { 12732 // There is no integral type larger enough to represent this 12733 // value. Complain, then allow the value to wrap around. 12734 EnumVal = LastEnumConst->getInitVal(); 12735 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12736 ++EnumVal; 12737 if (Enum->isFixed()) 12738 // When the underlying type is fixed, this is ill-formed. 12739 Diag(IdLoc, diag::err_enumerator_wrapped) 12740 << EnumVal.toString(10) 12741 << EltTy; 12742 else 12743 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12744 << EnumVal.toString(10); 12745 } else { 12746 EltTy = T; 12747 } 12748 12749 // Retrieve the last enumerator's value, extent that type to the 12750 // type that is supposed to be large enough to represent the incremented 12751 // value, then increment. 12752 EnumVal = LastEnumConst->getInitVal(); 12753 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12754 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12755 ++EnumVal; 12756 12757 // If we're not in C++, diagnose the overflow of enumerator values, 12758 // which in C99 means that the enumerator value is not representable in 12759 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12760 // permits enumerator values that are representable in some larger 12761 // integral type. 12762 if (!getLangOpts().CPlusPlus && !T.isNull()) 12763 Diag(IdLoc, diag::warn_enum_value_overflow); 12764 } else if (!getLangOpts().CPlusPlus && 12765 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12766 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12767 Diag(IdLoc, diag::ext_enum_value_not_int) 12768 << EnumVal.toString(10) << 1; 12769 } 12770 } 12771 } 12772 12773 if (!EltTy->isDependentType()) { 12774 // Make the enumerator value match the signedness and size of the 12775 // enumerator's type. 12776 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12777 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12778 } 12779 12780 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12781 Val, EnumVal); 12782 } 12783 12784 12785 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12786 SourceLocation IdLoc, IdentifierInfo *Id, 12787 AttributeList *Attr, 12788 SourceLocation EqualLoc, Expr *Val) { 12789 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12790 EnumConstantDecl *LastEnumConst = 12791 cast_or_null<EnumConstantDecl>(lastEnumConst); 12792 12793 // The scope passed in may not be a decl scope. Zip up the scope tree until 12794 // we find one that is. 12795 S = getNonFieldDeclScope(S); 12796 12797 // Verify that there isn't already something declared with this name in this 12798 // scope. 12799 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12800 ForRedeclaration); 12801 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12802 // Maybe we will complain about the shadowed template parameter. 12803 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12804 // Just pretend that we didn't see the previous declaration. 12805 PrevDecl = nullptr; 12806 } 12807 12808 if (PrevDecl) { 12809 // When in C++, we may get a TagDecl with the same name; in this case the 12810 // enum constant will 'hide' the tag. 12811 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12812 "Received TagDecl when not in C++!"); 12813 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12814 if (isa<EnumConstantDecl>(PrevDecl)) 12815 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12816 else 12817 Diag(IdLoc, diag::err_redefinition) << Id; 12818 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12819 return nullptr; 12820 } 12821 } 12822 12823 // C++ [class.mem]p15: 12824 // If T is the name of a class, then each of the following shall have a name 12825 // different from T: 12826 // - every enumerator of every member of class T that is an unscoped 12827 // enumerated type 12828 if (CXXRecordDecl *Record 12829 = dyn_cast<CXXRecordDecl>( 12830 TheEnumDecl->getDeclContext()->getRedeclContext())) 12831 if (!TheEnumDecl->isScoped() && 12832 Record->getIdentifier() && Record->getIdentifier() == Id) 12833 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12834 12835 EnumConstantDecl *New = 12836 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12837 12838 if (New) { 12839 // Process attributes. 12840 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12841 12842 // Register this decl in the current scope stack. 12843 New->setAccess(TheEnumDecl->getAccess()); 12844 PushOnScopeChains(New, S); 12845 } 12846 12847 ActOnDocumentableDecl(New); 12848 12849 return New; 12850 } 12851 12852 // Returns true when the enum initial expression does not trigger the 12853 // duplicate enum warning. A few common cases are exempted as follows: 12854 // Element2 = Element1 12855 // Element2 = Element1 + 1 12856 // Element2 = Element1 - 1 12857 // Where Element2 and Element1 are from the same enum. 12858 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12859 Expr *InitExpr = ECD->getInitExpr(); 12860 if (!InitExpr) 12861 return true; 12862 InitExpr = InitExpr->IgnoreImpCasts(); 12863 12864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12865 if (!BO->isAdditiveOp()) 12866 return true; 12867 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12868 if (!IL) 12869 return true; 12870 if (IL->getValue() != 1) 12871 return true; 12872 12873 InitExpr = BO->getLHS(); 12874 } 12875 12876 // This checks if the elements are from the same enum. 12877 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12878 if (!DRE) 12879 return true; 12880 12881 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12882 if (!EnumConstant) 12883 return true; 12884 12885 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12886 Enum) 12887 return true; 12888 12889 return false; 12890 } 12891 12892 struct DupKey { 12893 int64_t val; 12894 bool isTombstoneOrEmptyKey; 12895 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12896 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12897 }; 12898 12899 static DupKey GetDupKey(const llvm::APSInt& Val) { 12900 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12901 false); 12902 } 12903 12904 struct DenseMapInfoDupKey { 12905 static DupKey getEmptyKey() { return DupKey(0, true); } 12906 static DupKey getTombstoneKey() { return DupKey(1, true); } 12907 static unsigned getHashValue(const DupKey Key) { 12908 return (unsigned)(Key.val * 37); 12909 } 12910 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12911 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12912 LHS.val == RHS.val; 12913 } 12914 }; 12915 12916 // Emits a warning when an element is implicitly set a value that 12917 // a previous element has already been set to. 12918 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12919 EnumDecl *Enum, 12920 QualType EnumType) { 12921 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 12922 return; 12923 // Avoid anonymous enums 12924 if (!Enum->getIdentifier()) 12925 return; 12926 12927 // Only check for small enums. 12928 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12929 return; 12930 12931 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12932 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12933 12934 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12935 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12936 ValueToVectorMap; 12937 12938 DuplicatesVector DupVector; 12939 ValueToVectorMap EnumMap; 12940 12941 // Populate the EnumMap with all values represented by enum constants without 12942 // an initialier. 12943 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12944 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12945 12946 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12947 // this constant. Skip this enum since it may be ill-formed. 12948 if (!ECD) { 12949 return; 12950 } 12951 12952 if (ECD->getInitExpr()) 12953 continue; 12954 12955 DupKey Key = GetDupKey(ECD->getInitVal()); 12956 DeclOrVector &Entry = EnumMap[Key]; 12957 12958 // First time encountering this value. 12959 if (Entry.isNull()) 12960 Entry = ECD; 12961 } 12962 12963 // Create vectors for any values that has duplicates. 12964 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12965 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12966 if (!ValidDuplicateEnum(ECD, Enum)) 12967 continue; 12968 12969 DupKey Key = GetDupKey(ECD->getInitVal()); 12970 12971 DeclOrVector& Entry = EnumMap[Key]; 12972 if (Entry.isNull()) 12973 continue; 12974 12975 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12976 // Ensure constants are different. 12977 if (D == ECD) 12978 continue; 12979 12980 // Create new vector and push values onto it. 12981 ECDVector *Vec = new ECDVector(); 12982 Vec->push_back(D); 12983 Vec->push_back(ECD); 12984 12985 // Update entry to point to the duplicates vector. 12986 Entry = Vec; 12987 12988 // Store the vector somewhere we can consult later for quick emission of 12989 // diagnostics. 12990 DupVector.push_back(Vec); 12991 continue; 12992 } 12993 12994 ECDVector *Vec = Entry.get<ECDVector*>(); 12995 // Make sure constants are not added more than once. 12996 if (*Vec->begin() == ECD) 12997 continue; 12998 12999 Vec->push_back(ECD); 13000 } 13001 13002 // Emit diagnostics. 13003 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13004 DupVectorEnd = DupVector.end(); 13005 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13006 ECDVector *Vec = *DupVectorIter; 13007 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13008 13009 // Emit warning for one enum constant. 13010 ECDVector::iterator I = Vec->begin(); 13011 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13012 << (*I)->getName() << (*I)->getInitVal().toString(10) 13013 << (*I)->getSourceRange(); 13014 ++I; 13015 13016 // Emit one note for each of the remaining enum constants with 13017 // the same value. 13018 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13019 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13020 << (*I)->getName() << (*I)->getInitVal().toString(10) 13021 << (*I)->getSourceRange(); 13022 delete Vec; 13023 } 13024 } 13025 13026 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13027 SourceLocation RBraceLoc, Decl *EnumDeclX, 13028 ArrayRef<Decl *> Elements, 13029 Scope *S, AttributeList *Attr) { 13030 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13031 QualType EnumType = Context.getTypeDeclType(Enum); 13032 13033 if (Attr) 13034 ProcessDeclAttributeList(S, Enum, Attr); 13035 13036 if (Enum->isDependentType()) { 13037 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13038 EnumConstantDecl *ECD = 13039 cast_or_null<EnumConstantDecl>(Elements[i]); 13040 if (!ECD) continue; 13041 13042 ECD->setType(EnumType); 13043 } 13044 13045 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13046 return; 13047 } 13048 13049 // TODO: If the result value doesn't fit in an int, it must be a long or long 13050 // long value. ISO C does not support this, but GCC does as an extension, 13051 // emit a warning. 13052 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13053 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13054 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13055 13056 // Verify that all the values are okay, compute the size of the values, and 13057 // reverse the list. 13058 unsigned NumNegativeBits = 0; 13059 unsigned NumPositiveBits = 0; 13060 13061 // Keep track of whether all elements have type int. 13062 bool AllElementsInt = true; 13063 13064 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13065 EnumConstantDecl *ECD = 13066 cast_or_null<EnumConstantDecl>(Elements[i]); 13067 if (!ECD) continue; // Already issued a diagnostic. 13068 13069 const llvm::APSInt &InitVal = ECD->getInitVal(); 13070 13071 // Keep track of the size of positive and negative values. 13072 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13073 NumPositiveBits = std::max(NumPositiveBits, 13074 (unsigned)InitVal.getActiveBits()); 13075 else 13076 NumNegativeBits = std::max(NumNegativeBits, 13077 (unsigned)InitVal.getMinSignedBits()); 13078 13079 // Keep track of whether every enum element has type int (very commmon). 13080 if (AllElementsInt) 13081 AllElementsInt = ECD->getType() == Context.IntTy; 13082 } 13083 13084 // Figure out the type that should be used for this enum. 13085 QualType BestType; 13086 unsigned BestWidth; 13087 13088 // C++0x N3000 [conv.prom]p3: 13089 // An rvalue of an unscoped enumeration type whose underlying 13090 // type is not fixed can be converted to an rvalue of the first 13091 // of the following types that can represent all the values of 13092 // the enumeration: int, unsigned int, long int, unsigned long 13093 // int, long long int, or unsigned long long int. 13094 // C99 6.4.4.3p2: 13095 // An identifier declared as an enumeration constant has type int. 13096 // The C99 rule is modified by a gcc extension 13097 QualType BestPromotionType; 13098 13099 bool Packed = Enum->hasAttr<PackedAttr>(); 13100 // -fshort-enums is the equivalent to specifying the packed attribute on all 13101 // enum definitions. 13102 if (LangOpts.ShortEnums) 13103 Packed = true; 13104 13105 if (Enum->isFixed()) { 13106 BestType = Enum->getIntegerType(); 13107 if (BestType->isPromotableIntegerType()) 13108 BestPromotionType = Context.getPromotedIntegerType(BestType); 13109 else 13110 BestPromotionType = BestType; 13111 // We don't need to set BestWidth, because BestType is going to be the type 13112 // of the enumerators, but we do anyway because otherwise some compilers 13113 // warn that it might be used uninitialized. 13114 BestWidth = CharWidth; 13115 } 13116 else if (NumNegativeBits) { 13117 // If there is a negative value, figure out the smallest integer type (of 13118 // int/long/longlong) that fits. 13119 // If it's packed, check also if it fits a char or a short. 13120 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13121 BestType = Context.SignedCharTy; 13122 BestWidth = CharWidth; 13123 } else if (Packed && NumNegativeBits <= ShortWidth && 13124 NumPositiveBits < ShortWidth) { 13125 BestType = Context.ShortTy; 13126 BestWidth = ShortWidth; 13127 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13128 BestType = Context.IntTy; 13129 BestWidth = IntWidth; 13130 } else { 13131 BestWidth = Context.getTargetInfo().getLongWidth(); 13132 13133 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13134 BestType = Context.LongTy; 13135 } else { 13136 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13137 13138 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13139 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13140 BestType = Context.LongLongTy; 13141 } 13142 } 13143 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13144 } else { 13145 // If there is no negative value, figure out the smallest type that fits 13146 // all of the enumerator values. 13147 // If it's packed, check also if it fits a char or a short. 13148 if (Packed && NumPositiveBits <= CharWidth) { 13149 BestType = Context.UnsignedCharTy; 13150 BestPromotionType = Context.IntTy; 13151 BestWidth = CharWidth; 13152 } else if (Packed && NumPositiveBits <= ShortWidth) { 13153 BestType = Context.UnsignedShortTy; 13154 BestPromotionType = Context.IntTy; 13155 BestWidth = ShortWidth; 13156 } else if (NumPositiveBits <= IntWidth) { 13157 BestType = Context.UnsignedIntTy; 13158 BestWidth = IntWidth; 13159 BestPromotionType 13160 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13161 ? Context.UnsignedIntTy : Context.IntTy; 13162 } else if (NumPositiveBits <= 13163 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13164 BestType = Context.UnsignedLongTy; 13165 BestPromotionType 13166 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13167 ? Context.UnsignedLongTy : Context.LongTy; 13168 } else { 13169 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13170 assert(NumPositiveBits <= BestWidth && 13171 "How could an initializer get larger than ULL?"); 13172 BestType = Context.UnsignedLongLongTy; 13173 BestPromotionType 13174 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13175 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13176 } 13177 } 13178 13179 // Loop over all of the enumerator constants, changing their types to match 13180 // the type of the enum if needed. 13181 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13182 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13183 if (!ECD) continue; // Already issued a diagnostic. 13184 13185 // Standard C says the enumerators have int type, but we allow, as an 13186 // extension, the enumerators to be larger than int size. If each 13187 // enumerator value fits in an int, type it as an int, otherwise type it the 13188 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13189 // that X has type 'int', not 'unsigned'. 13190 13191 // Determine whether the value fits into an int. 13192 llvm::APSInt InitVal = ECD->getInitVal(); 13193 13194 // If it fits into an integer type, force it. Otherwise force it to match 13195 // the enum decl type. 13196 QualType NewTy; 13197 unsigned NewWidth; 13198 bool NewSign; 13199 if (!getLangOpts().CPlusPlus && 13200 !Enum->isFixed() && 13201 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13202 NewTy = Context.IntTy; 13203 NewWidth = IntWidth; 13204 NewSign = true; 13205 } else if (ECD->getType() == BestType) { 13206 // Already the right type! 13207 if (getLangOpts().CPlusPlus) 13208 // C++ [dcl.enum]p4: Following the closing brace of an 13209 // enum-specifier, each enumerator has the type of its 13210 // enumeration. 13211 ECD->setType(EnumType); 13212 continue; 13213 } else { 13214 NewTy = BestType; 13215 NewWidth = BestWidth; 13216 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13217 } 13218 13219 // Adjust the APSInt value. 13220 InitVal = InitVal.extOrTrunc(NewWidth); 13221 InitVal.setIsSigned(NewSign); 13222 ECD->setInitVal(InitVal); 13223 13224 // Adjust the Expr initializer and type. 13225 if (ECD->getInitExpr() && 13226 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13227 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13228 CK_IntegralCast, 13229 ECD->getInitExpr(), 13230 /*base paths*/ nullptr, 13231 VK_RValue)); 13232 if (getLangOpts().CPlusPlus) 13233 // C++ [dcl.enum]p4: Following the closing brace of an 13234 // enum-specifier, each enumerator has the type of its 13235 // enumeration. 13236 ECD->setType(EnumType); 13237 else 13238 ECD->setType(NewTy); 13239 } 13240 13241 Enum->completeDefinition(BestType, BestPromotionType, 13242 NumPositiveBits, NumNegativeBits); 13243 13244 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13245 13246 // Now that the enum type is defined, ensure it's not been underaligned. 13247 if (Enum->hasAttrs()) 13248 CheckAlignasUnderalignment(Enum); 13249 } 13250 13251 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13252 SourceLocation StartLoc, 13253 SourceLocation EndLoc) { 13254 StringLiteral *AsmString = cast<StringLiteral>(expr); 13255 13256 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13257 AsmString, StartLoc, 13258 EndLoc); 13259 CurContext->addDecl(New); 13260 return New; 13261 } 13262 13263 static void checkModuleImportContext(Sema &S, Module *M, 13264 SourceLocation ImportLoc, 13265 DeclContext *DC) { 13266 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13267 switch (LSD->getLanguage()) { 13268 case LinkageSpecDecl::lang_c: 13269 if (!M->IsExternC) { 13270 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13271 << M->getFullModuleName(); 13272 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13273 return; 13274 } 13275 break; 13276 case LinkageSpecDecl::lang_cxx: 13277 break; 13278 } 13279 DC = LSD->getParent(); 13280 } 13281 13282 while (isa<LinkageSpecDecl>(DC)) 13283 DC = DC->getParent(); 13284 if (!isa<TranslationUnitDecl>(DC)) { 13285 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13286 << M->getFullModuleName() << DC; 13287 S.Diag(cast<Decl>(DC)->getLocStart(), 13288 diag::note_module_import_not_at_top_level) 13289 << DC; 13290 } 13291 } 13292 13293 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13294 SourceLocation ImportLoc, 13295 ModuleIdPath Path) { 13296 Module *Mod = 13297 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13298 /*IsIncludeDirective=*/false); 13299 if (!Mod) 13300 return true; 13301 13302 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13303 13304 // FIXME: we should support importing a submodule within a different submodule 13305 // of the same top-level module. Until we do, make it an error rather than 13306 // silently ignoring the import. 13307 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13308 Diag(ImportLoc, diag::err_module_self_import) 13309 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13310 13311 SmallVector<SourceLocation, 2> IdentifierLocs; 13312 Module *ModCheck = Mod; 13313 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13314 // If we've run out of module parents, just drop the remaining identifiers. 13315 // We need the length to be consistent. 13316 if (!ModCheck) 13317 break; 13318 ModCheck = ModCheck->Parent; 13319 13320 IdentifierLocs.push_back(Path[I].second); 13321 } 13322 13323 ImportDecl *Import = ImportDecl::Create(Context, 13324 Context.getTranslationUnitDecl(), 13325 AtLoc.isValid()? AtLoc : ImportLoc, 13326 Mod, IdentifierLocs); 13327 Context.getTranslationUnitDecl()->addDecl(Import); 13328 return Import; 13329 } 13330 13331 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13332 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13333 13334 // FIXME: Should we synthesize an ImportDecl here? 13335 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13336 /*Complain=*/true); 13337 } 13338 13339 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13340 Module *Mod) { 13341 // Bail if we're not allowed to implicitly import a module here. 13342 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13343 return; 13344 13345 // Create the implicit import declaration. 13346 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13347 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13348 Loc, Mod, Loc); 13349 TU->addDecl(ImportD); 13350 Consumer.HandleImplicitImportDecl(ImportD); 13351 13352 // Make the module visible. 13353 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13354 /*Complain=*/false); 13355 } 13356 13357 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13358 IdentifierInfo* AliasName, 13359 SourceLocation PragmaLoc, 13360 SourceLocation NameLoc, 13361 SourceLocation AliasNameLoc) { 13362 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13363 LookupOrdinaryName); 13364 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13365 AliasName->getName(), 0); 13366 13367 if (PrevDecl) 13368 PrevDecl->addAttr(Attr); 13369 else 13370 (void)ExtnameUndeclaredIdentifiers.insert( 13371 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13372 } 13373 13374 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13375 SourceLocation PragmaLoc, 13376 SourceLocation NameLoc) { 13377 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13378 13379 if (PrevDecl) { 13380 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13381 } else { 13382 (void)WeakUndeclaredIdentifiers.insert( 13383 std::pair<IdentifierInfo*,WeakInfo> 13384 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 13385 } 13386 } 13387 13388 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13389 IdentifierInfo* AliasName, 13390 SourceLocation PragmaLoc, 13391 SourceLocation NameLoc, 13392 SourceLocation AliasNameLoc) { 13393 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13394 LookupOrdinaryName); 13395 WeakInfo W = WeakInfo(Name, NameLoc); 13396 13397 if (PrevDecl) { 13398 if (!PrevDecl->hasAttr<AliasAttr>()) 13399 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13400 DeclApplyPragmaWeak(TUScope, ND, W); 13401 } else { 13402 (void)WeakUndeclaredIdentifiers.insert( 13403 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13404 } 13405 } 13406 13407 Decl *Sema::getObjCDeclContext() const { 13408 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13409 } 13410 13411 AvailabilityResult Sema::getCurContextAvailability() const { 13412 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13413 // If we are within an Objective-C method, we should consult 13414 // both the availability of the method as well as the 13415 // enclosing class. If the class is (say) deprecated, 13416 // the entire method is considered deprecated from the 13417 // purpose of checking if the current context is deprecated. 13418 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13419 AvailabilityResult R = MD->getAvailability(); 13420 if (R != AR_Available) 13421 return R; 13422 D = MD->getClassInterface(); 13423 } 13424 // If we are within an Objective-c @implementation, it 13425 // gets the same availability context as the @interface. 13426 else if (const ObjCImplementationDecl *ID = 13427 dyn_cast<ObjCImplementationDecl>(D)) { 13428 D = ID->getClassInterface(); 13429 } 13430 return D->getAvailability(); 13431 } 13432