SemaDecl.cpp revision ba2bfa07cbcb088e3afc5565a3b301a7873771a3
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/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/CommentDiagnostic.h" 21#include "clang/AST/DeclCXX.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/DeclTemplate.h" 24#include "clang/AST/EvaluatedExprVisitor.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/StmtCXX.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Basic/SourceManager.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 31#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 32#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 33#include "clang/Parse/ParseDiagnostic.h" 34#include "clang/Sema/CXXFieldCollector.h" 35#include "clang/Sema/DeclSpec.h" 36#include "clang/Sema/DelayedDiagnostic.h" 37#include "clang/Sema/Initialization.h" 38#include "clang/Sema/Lookup.h" 39#include "clang/Sema/ParsedTemplate.h" 40#include "clang/Sema/Scope.h" 41#include "clang/Sema/ScopeInfo.h" 42#include "llvm/ADT/SmallString.h" 43#include "llvm/ADT/Triple.h" 44#include <algorithm> 45#include <cstring> 46#include <functional> 47using namespace clang; 48using namespace sema; 49 50Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 51 if (OwnedType) { 52 Decl *Group[2] = { OwnedType, Ptr }; 53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 54 } 55 56 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 57} 58 59namespace { 60 61class TypeNameValidatorCCC : public CorrectionCandidateCallback { 62 public: 63 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 64 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 65 WantExpressionKeywords = false; 66 WantCXXNamedCasts = false; 67 WantRemainingKeywords = false; 68 } 69 70 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 71 if (NamedDecl *ND = candidate.getCorrectionDecl()) 72 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 73 (AllowInvalidDecl || !ND->isInvalidDecl()); 74 else 75 return !WantClassName && candidate.isKeyword(); 76 } 77 78 private: 79 bool AllowInvalidDecl; 80 bool WantClassName; 81}; 82 83} 84 85/// \brief Determine whether the token kind starts a simple-type-specifier. 86bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 87 switch (Kind) { 88 // FIXME: Take into account the current language when deciding whether a 89 // token kind is a valid type specifier 90 case tok::kw_short: 91 case tok::kw_long: 92 case tok::kw___int64: 93 case tok::kw___int128: 94 case tok::kw_signed: 95 case tok::kw_unsigned: 96 case tok::kw_void: 97 case tok::kw_char: 98 case tok::kw_int: 99 case tok::kw_half: 100 case tok::kw_float: 101 case tok::kw_double: 102 case tok::kw_wchar_t: 103 case tok::kw_bool: 104 case tok::kw___underlying_type: 105 return true; 106 107 case tok::annot_typename: 108 case tok::kw_char16_t: 109 case tok::kw_char32_t: 110 case tok::kw_typeof: 111 case tok::kw_decltype: 112 return getLangOpts().CPlusPlus; 113 114 default: 115 break; 116 } 117 118 return false; 119} 120 121/// \brief If the identifier refers to a type name within this scope, 122/// return the declaration of that type. 123/// 124/// This routine performs ordinary name lookup of the identifier II 125/// within the given scope, with optional C++ scope specifier SS, to 126/// determine whether the name refers to a type. If so, returns an 127/// opaque pointer (actually a QualType) corresponding to that 128/// type. Otherwise, returns NULL. 129/// 130/// If name lookup results in an ambiguity, this routine will complain 131/// and then return NULL. 132ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 133 Scope *S, CXXScopeSpec *SS, 134 bool isClassName, bool HasTrailingDot, 135 ParsedType ObjectTypePtr, 136 bool IsCtorOrDtorName, 137 bool WantNontrivialTypeSourceInfo, 138 IdentifierInfo **CorrectedII) { 139 // Determine where we will perform name lookup. 140 DeclContext *LookupCtx = 0; 141 if (ObjectTypePtr) { 142 QualType ObjectType = ObjectTypePtr.get(); 143 if (ObjectType->isRecordType()) 144 LookupCtx = computeDeclContext(ObjectType); 145 } else if (SS && SS->isNotEmpty()) { 146 LookupCtx = computeDeclContext(*SS, false); 147 148 if (!LookupCtx) { 149 if (isDependentScopeSpecifier(*SS)) { 150 // C++ [temp.res]p3: 151 // A qualified-id that refers to a type and in which the 152 // nested-name-specifier depends on a template-parameter (14.6.2) 153 // shall be prefixed by the keyword typename to indicate that the 154 // qualified-id denotes a type, forming an 155 // elaborated-type-specifier (7.1.5.3). 156 // 157 // We therefore do not perform any name lookup if the result would 158 // refer to a member of an unknown specialization. 159 if (!isClassName && !IsCtorOrDtorName) 160 return ParsedType(); 161 162 // We know from the grammar that this name refers to a type, 163 // so build a dependent node to describe the type. 164 if (WantNontrivialTypeSourceInfo) 165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 166 167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 168 QualType T = 169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 170 II, NameLoc); 171 172 return ParsedType::make(T); 173 } 174 175 return ParsedType(); 176 } 177 178 if (!LookupCtx->isDependentContext() && 179 RequireCompleteDeclContext(*SS, LookupCtx)) 180 return ParsedType(); 181 } 182 183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 184 // lookup for class-names. 185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 186 LookupOrdinaryName; 187 LookupResult Result(*this, &II, NameLoc, Kind); 188 if (LookupCtx) { 189 // Perform "qualified" name lookup into the declaration context we 190 // computed, which is either the type of the base of a member access 191 // expression or the declaration context associated with a prior 192 // nested-name-specifier. 193 LookupQualifiedName(Result, LookupCtx); 194 195 if (ObjectTypePtr && Result.empty()) { 196 // C++ [basic.lookup.classref]p3: 197 // If the unqualified-id is ~type-name, the type-name is looked up 198 // in the context of the entire postfix-expression. If the type T of 199 // the object expression is of a class type C, the type-name is also 200 // looked up in the scope of class C. At least one of the lookups shall 201 // find a name that refers to (possibly cv-qualified) T. 202 LookupName(Result, S); 203 } 204 } else { 205 // Perform unqualified name lookup. 206 LookupName(Result, S); 207 } 208 209 NamedDecl *IIDecl = 0; 210 switch (Result.getResultKind()) { 211 case LookupResult::NotFound: 212 case LookupResult::NotFoundInCurrentInstantiation: 213 if (CorrectedII) { 214 TypeNameValidatorCCC Validator(true, isClassName); 215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 216 Kind, S, SS, Validator); 217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 218 TemplateTy Template; 219 bool MemberOfUnknownSpecialization; 220 UnqualifiedId TemplateName; 221 TemplateName.setIdentifier(NewII, NameLoc); 222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 223 CXXScopeSpec NewSS, *NewSSPtr = SS; 224 if (SS && NNS) { 225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 226 NewSSPtr = &NewSS; 227 } 228 if (Correction && (NNS || NewII != &II) && 229 // Ignore a correction to a template type as the to-be-corrected 230 // identifier is not a template (typo correction for template names 231 // is handled elsewhere). 232 !(getLangOpts().CPlusPlus && NewSSPtr && 233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 234 false, Template, MemberOfUnknownSpecialization))) { 235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 236 isClassName, HasTrailingDot, ObjectTypePtr, 237 IsCtorOrDtorName, 238 WantNontrivialTypeSourceInfo); 239 if (Ty) { 240 std::string CorrectedStr(Correction.getAsString(getLangOpts())); 241 std::string CorrectedQuotedStr( 242 Correction.getQuoted(getLangOpts())); 243 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest) 244 << Result.getLookupName() << CorrectedQuotedStr << isClassName 245 << FixItHint::CreateReplacement(SourceRange(NameLoc), 246 CorrectedStr); 247 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 248 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 249 << CorrectedQuotedStr; 250 251 if (SS && NNS) 252 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 253 *CorrectedII = NewII; 254 return Ty; 255 } 256 } 257 } 258 // If typo correction failed or was not performed, fall through 259 case LookupResult::FoundOverloaded: 260 case LookupResult::FoundUnresolvedValue: 261 Result.suppressDiagnostics(); 262 return ParsedType(); 263 264 case LookupResult::Ambiguous: 265 // Recover from type-hiding ambiguities by hiding the type. We'll 266 // do the lookup again when looking for an object, and we can 267 // diagnose the error then. If we don't do this, then the error 268 // about hiding the type will be immediately followed by an error 269 // that only makes sense if the identifier was treated like a type. 270 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 271 Result.suppressDiagnostics(); 272 return ParsedType(); 273 } 274 275 // Look to see if we have a type anywhere in the list of results. 276 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 277 Res != ResEnd; ++Res) { 278 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 279 if (!IIDecl || 280 (*Res)->getLocation().getRawEncoding() < 281 IIDecl->getLocation().getRawEncoding()) 282 IIDecl = *Res; 283 } 284 } 285 286 if (!IIDecl) { 287 // None of the entities we found is a type, so there is no way 288 // to even assume that the result is a type. In this case, don't 289 // complain about the ambiguity. The parser will either try to 290 // perform this lookup again (e.g., as an object name), which 291 // will produce the ambiguity, or will complain that it expected 292 // a type name. 293 Result.suppressDiagnostics(); 294 return ParsedType(); 295 } 296 297 // We found a type within the ambiguous lookup; diagnose the 298 // ambiguity and then return that type. This might be the right 299 // answer, or it might not be, but it suppresses any attempt to 300 // perform the name lookup again. 301 break; 302 303 case LookupResult::Found: 304 IIDecl = Result.getFoundDecl(); 305 break; 306 } 307 308 assert(IIDecl && "Didn't find decl"); 309 310 QualType T; 311 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 312 DiagnoseUseOfDecl(IIDecl, NameLoc); 313 314 if (T.isNull()) 315 T = Context.getTypeDeclType(TD); 316 317 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 318 // constructor or destructor name (in such a case, the scope specifier 319 // will be attached to the enclosing Expr or Decl node). 320 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 321 if (WantNontrivialTypeSourceInfo) { 322 // Construct a type with type-source information. 323 TypeLocBuilder Builder; 324 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 325 326 T = getElaboratedType(ETK_None, *SS, T); 327 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 328 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 329 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 330 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 331 } else { 332 T = getElaboratedType(ETK_None, *SS, T); 333 } 334 } 335 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 336 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 337 if (!HasTrailingDot) 338 T = Context.getObjCInterfaceType(IDecl); 339 } 340 341 if (T.isNull()) { 342 // If it's not plausibly a type, suppress diagnostics. 343 Result.suppressDiagnostics(); 344 return ParsedType(); 345 } 346 return ParsedType::make(T); 347} 348 349/// isTagName() - This method is called *for error recovery purposes only* 350/// to determine if the specified name is a valid tag name ("struct foo"). If 351/// so, this returns the TST for the tag corresponding to it (TST_enum, 352/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 353/// cases in C where the user forgot to specify the tag. 354DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 355 // Do a tag name lookup in this scope. 356 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 357 LookupName(R, S, false); 358 R.suppressDiagnostics(); 359 if (R.getResultKind() == LookupResult::Found) 360 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 361 switch (TD->getTagKind()) { 362 case TTK_Struct: return DeclSpec::TST_struct; 363 case TTK_Interface: return DeclSpec::TST_interface; 364 case TTK_Union: return DeclSpec::TST_union; 365 case TTK_Class: return DeclSpec::TST_class; 366 case TTK_Enum: return DeclSpec::TST_enum; 367 } 368 } 369 370 return DeclSpec::TST_unspecified; 371} 372 373/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 374/// if a CXXScopeSpec's type is equal to the type of one of the base classes 375/// then downgrade the missing typename error to a warning. 376/// This is needed for MSVC compatibility; Example: 377/// @code 378/// template<class T> class A { 379/// public: 380/// typedef int TYPE; 381/// }; 382/// template<class T> class B : public A<T> { 383/// public: 384/// A<T>::TYPE a; // no typename required because A<T> is a base class. 385/// }; 386/// @endcode 387bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 388 if (CurContext->isRecord()) { 389 const Type *Ty = SS->getScopeRep()->getAsType(); 390 391 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 392 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 393 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 394 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 395 return true; 396 return S->isFunctionPrototypeScope(); 397 } 398 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 399} 400 401bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 402 SourceLocation IILoc, 403 Scope *S, 404 CXXScopeSpec *SS, 405 ParsedType &SuggestedType) { 406 // We don't have anything to suggest (yet). 407 SuggestedType = ParsedType(); 408 409 // There may have been a typo in the name of the type. Look up typo 410 // results, in case we have something that we can suggest. 411 TypeNameValidatorCCC Validator(false); 412 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 413 LookupOrdinaryName, S, SS, 414 Validator)) { 415 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 416 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 417 418 if (Corrected.isKeyword()) { 419 // We corrected to a keyword. 420 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo(); 421 if (!isSimpleTypeSpecifier(NewII->getTokenID())) 422 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr; 423 Diag(IILoc, diag::err_unknown_typename_suggest) 424 << II << CorrectedQuotedStr 425 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 426 II = NewII; 427 } else { 428 NamedDecl *Result = Corrected.getCorrectionDecl(); 429 // We found a similarly-named type or interface; suggest that. 430 if (!SS || !SS->isSet()) 431 Diag(IILoc, diag::err_unknown_typename_suggest) 432 << II << CorrectedQuotedStr 433 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 434 else if (DeclContext *DC = computeDeclContext(*SS, false)) 435 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 436 << II << DC << CorrectedQuotedStr << SS->getRange() 437 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 438 CorrectedStr); 439 else 440 llvm_unreachable("could not have corrected a typo here"); 441 442 Diag(Result->getLocation(), diag::note_previous_decl) 443 << CorrectedQuotedStr; 444 445 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 446 false, false, ParsedType(), 447 /*IsCtorOrDtorName=*/false, 448 /*NonTrivialTypeSourceInfo=*/true); 449 } 450 return true; 451 } 452 453 if (getLangOpts().CPlusPlus) { 454 // See if II is a class template that the user forgot to pass arguments to. 455 UnqualifiedId Name; 456 Name.setIdentifier(II, IILoc); 457 CXXScopeSpec EmptySS; 458 TemplateTy TemplateResult; 459 bool MemberOfUnknownSpecialization; 460 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 461 Name, ParsedType(), true, TemplateResult, 462 MemberOfUnknownSpecialization) == TNK_Type_template) { 463 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 464 Diag(IILoc, diag::err_template_missing_args) << TplName; 465 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 466 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 467 << TplDecl->getTemplateParameters()->getSourceRange(); 468 } 469 return true; 470 } 471 } 472 473 // FIXME: Should we move the logic that tries to recover from a missing tag 474 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 475 476 if (!SS || (!SS->isSet() && !SS->isInvalid())) 477 Diag(IILoc, diag::err_unknown_typename) << II; 478 else if (DeclContext *DC = computeDeclContext(*SS, false)) 479 Diag(IILoc, diag::err_typename_nested_not_found) 480 << II << DC << SS->getRange(); 481 else if (isDependentScopeSpecifier(*SS)) { 482 unsigned DiagID = diag::err_typename_missing; 483 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 484 DiagID = diag::warn_typename_missing; 485 486 Diag(SS->getRange().getBegin(), DiagID) 487 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 488 << SourceRange(SS->getRange().getBegin(), IILoc) 489 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 490 SuggestedType = ActOnTypenameType(S, SourceLocation(), 491 *SS, *II, IILoc).get(); 492 } else { 493 assert(SS && SS->isInvalid() && 494 "Invalid scope specifier has already been diagnosed"); 495 } 496 497 return true; 498} 499 500/// \brief Determine whether the given result set contains either a type name 501/// or 502static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 503 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 504 NextToken.is(tok::less); 505 506 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 507 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 508 return true; 509 510 if (CheckTemplate && isa<TemplateDecl>(*I)) 511 return true; 512 } 513 514 return false; 515} 516 517static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 518 Scope *S, CXXScopeSpec &SS, 519 IdentifierInfo *&Name, 520 SourceLocation NameLoc) { 521 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 522 SemaRef.LookupParsedName(R, S, &SS); 523 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 524 const char *TagName = 0; 525 const char *FixItTagName = 0; 526 switch (Tag->getTagKind()) { 527 case TTK_Class: 528 TagName = "class"; 529 FixItTagName = "class "; 530 break; 531 532 case TTK_Enum: 533 TagName = "enum"; 534 FixItTagName = "enum "; 535 break; 536 537 case TTK_Struct: 538 TagName = "struct"; 539 FixItTagName = "struct "; 540 break; 541 542 case TTK_Interface: 543 TagName = "__interface"; 544 FixItTagName = "__interface "; 545 break; 546 547 case TTK_Union: 548 TagName = "union"; 549 FixItTagName = "union "; 550 break; 551 } 552 553 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 554 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 555 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 556 557 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 558 I != IEnd; ++I) 559 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 560 << Name << TagName; 561 562 // Replace lookup results with just the tag decl. 563 Result.clear(Sema::LookupTagName); 564 SemaRef.LookupParsedName(Result, S, &SS); 565 return true; 566 } 567 568 return false; 569} 570 571/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 572static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 573 QualType T, SourceLocation NameLoc) { 574 ASTContext &Context = S.Context; 575 576 TypeLocBuilder Builder; 577 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 578 579 T = S.getElaboratedType(ETK_None, SS, T); 580 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 581 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 582 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 583 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 584} 585 586Sema::NameClassification Sema::ClassifyName(Scope *S, 587 CXXScopeSpec &SS, 588 IdentifierInfo *&Name, 589 SourceLocation NameLoc, 590 const Token &NextToken, 591 bool IsAddressOfOperand, 592 CorrectionCandidateCallback *CCC) { 593 DeclarationNameInfo NameInfo(Name, NameLoc); 594 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 595 596 if (NextToken.is(tok::coloncolon)) { 597 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 598 QualType(), false, SS, 0, false); 599 600 } 601 602 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 603 LookupParsedName(Result, S, &SS, !CurMethod); 604 605 // Perform lookup for Objective-C instance variables (including automatically 606 // synthesized instance variables), if we're in an Objective-C method. 607 // FIXME: This lookup really, really needs to be folded in to the normal 608 // unqualified lookup mechanism. 609 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 610 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 611 if (E.get() || E.isInvalid()) 612 return E; 613 } 614 615 bool SecondTry = false; 616 bool IsFilteredTemplateName = false; 617 618Corrected: 619 switch (Result.getResultKind()) { 620 case LookupResult::NotFound: 621 // If an unqualified-id is followed by a '(', then we have a function 622 // call. 623 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 624 // In C++, this is an ADL-only call. 625 // FIXME: Reference? 626 if (getLangOpts().CPlusPlus) 627 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 628 629 // C90 6.3.2.2: 630 // If the expression that precedes the parenthesized argument list in a 631 // function call consists solely of an identifier, and if no 632 // declaration is visible for this identifier, the identifier is 633 // implicitly declared exactly as if, in the innermost block containing 634 // the function call, the declaration 635 // 636 // extern int identifier (); 637 // 638 // appeared. 639 // 640 // We also allow this in C99 as an extension. 641 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 642 Result.addDecl(D); 643 Result.resolveKind(); 644 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 645 } 646 } 647 648 // In C, we first see whether there is a tag type by the same name, in 649 // which case it's likely that the user just forget to write "enum", 650 // "struct", or "union". 651 if (!getLangOpts().CPlusPlus && !SecondTry && 652 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 653 break; 654 } 655 656 // Perform typo correction to determine if there is another name that is 657 // close to this name. 658 if (!SecondTry && CCC) { 659 SecondTry = true; 660 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 661 Result.getLookupKind(), S, 662 &SS, *CCC)) { 663 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 664 unsigned QualifiedDiag = diag::err_no_member_suggest; 665 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 666 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 667 668 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 669 NamedDecl *UnderlyingFirstDecl 670 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 671 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 672 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 673 UnqualifiedDiag = diag::err_no_template_suggest; 674 QualifiedDiag = diag::err_no_member_template_suggest; 675 } else if (UnderlyingFirstDecl && 676 (isa<TypeDecl>(UnderlyingFirstDecl) || 677 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 678 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 679 UnqualifiedDiag = diag::err_unknown_typename_suggest; 680 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 681 } 682 683 if (SS.isEmpty()) 684 Diag(NameLoc, UnqualifiedDiag) 685 << Name << CorrectedQuotedStr 686 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 687 else // FIXME: is this even reachable? Test it. 688 Diag(NameLoc, QualifiedDiag) 689 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 690 << SS.getRange() 691 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 692 CorrectedStr); 693 694 // Update the name, so that the caller has the new name. 695 Name = Corrected.getCorrectionAsIdentifierInfo(); 696 697 // Typo correction corrected to a keyword. 698 if (Corrected.isKeyword()) 699 return Corrected.getCorrectionAsIdentifierInfo(); 700 701 // Also update the LookupResult... 702 // FIXME: This should probably go away at some point 703 Result.clear(); 704 Result.setLookupName(Corrected.getCorrection()); 705 if (FirstDecl) { 706 Result.addDecl(FirstDecl); 707 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 708 << CorrectedQuotedStr; 709 } 710 711 // If we found an Objective-C instance variable, let 712 // LookupInObjCMethod build the appropriate expression to 713 // reference the ivar. 714 // FIXME: This is a gross hack. 715 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 716 Result.clear(); 717 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 718 return E; 719 } 720 721 goto Corrected; 722 } 723 } 724 725 // We failed to correct; just fall through and let the parser deal with it. 726 Result.suppressDiagnostics(); 727 return NameClassification::Unknown(); 728 729 case LookupResult::NotFoundInCurrentInstantiation: { 730 // We performed name lookup into the current instantiation, and there were 731 // dependent bases, so we treat this result the same way as any other 732 // dependent nested-name-specifier. 733 734 // C++ [temp.res]p2: 735 // A name used in a template declaration or definition and that is 736 // dependent on a template-parameter is assumed not to name a type 737 // unless the applicable name lookup finds a type name or the name is 738 // qualified by the keyword typename. 739 // 740 // FIXME: If the next token is '<', we might want to ask the parser to 741 // perform some heroics to see if we actually have a 742 // template-argument-list, which would indicate a missing 'template' 743 // keyword here. 744 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 745 NameInfo, IsAddressOfOperand, 746 /*TemplateArgs=*/0); 747 } 748 749 case LookupResult::Found: 750 case LookupResult::FoundOverloaded: 751 case LookupResult::FoundUnresolvedValue: 752 break; 753 754 case LookupResult::Ambiguous: 755 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 756 hasAnyAcceptableTemplateNames(Result)) { 757 // C++ [temp.local]p3: 758 // A lookup that finds an injected-class-name (10.2) can result in an 759 // ambiguity in certain cases (for example, if it is found in more than 760 // one base class). If all of the injected-class-names that are found 761 // refer to specializations of the same class template, and if the name 762 // is followed by a template-argument-list, the reference refers to the 763 // class template itself and not a specialization thereof, and is not 764 // ambiguous. 765 // 766 // This filtering can make an ambiguous result into an unambiguous one, 767 // so try again after filtering out template names. 768 FilterAcceptableTemplateNames(Result); 769 if (!Result.isAmbiguous()) { 770 IsFilteredTemplateName = true; 771 break; 772 } 773 } 774 775 // Diagnose the ambiguity and return an error. 776 return NameClassification::Error(); 777 } 778 779 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 780 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 781 // C++ [temp.names]p3: 782 // After name lookup (3.4) finds that a name is a template-name or that 783 // an operator-function-id or a literal- operator-id refers to a set of 784 // overloaded functions any member of which is a function template if 785 // this is followed by a <, the < is always taken as the delimiter of a 786 // template-argument-list and never as the less-than operator. 787 if (!IsFilteredTemplateName) 788 FilterAcceptableTemplateNames(Result); 789 790 if (!Result.empty()) { 791 bool IsFunctionTemplate; 792 TemplateName Template; 793 if (Result.end() - Result.begin() > 1) { 794 IsFunctionTemplate = true; 795 Template = Context.getOverloadedTemplateName(Result.begin(), 796 Result.end()); 797 } else { 798 TemplateDecl *TD 799 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 800 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 801 802 if (SS.isSet() && !SS.isInvalid()) 803 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 804 /*TemplateKeyword=*/false, 805 TD); 806 else 807 Template = TemplateName(TD); 808 } 809 810 if (IsFunctionTemplate) { 811 // Function templates always go through overload resolution, at which 812 // point we'll perform the various checks (e.g., accessibility) we need 813 // to based on which function we selected. 814 Result.suppressDiagnostics(); 815 816 return NameClassification::FunctionTemplate(Template); 817 } 818 819 return NameClassification::TypeTemplate(Template); 820 } 821 } 822 823 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 824 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 825 DiagnoseUseOfDecl(Type, NameLoc); 826 QualType T = Context.getTypeDeclType(Type); 827 if (SS.isNotEmpty()) 828 return buildNestedType(*this, SS, T, NameLoc); 829 return ParsedType::make(T); 830 } 831 832 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 833 if (!Class) { 834 // FIXME: It's unfortunate that we don't have a Type node for handling this. 835 if (ObjCCompatibleAliasDecl *Alias 836 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 837 Class = Alias->getClassInterface(); 838 } 839 840 if (Class) { 841 DiagnoseUseOfDecl(Class, NameLoc); 842 843 if (NextToken.is(tok::period)) { 844 // Interface. <something> is parsed as a property reference expression. 845 // Just return "unknown" as a fall-through for now. 846 Result.suppressDiagnostics(); 847 return NameClassification::Unknown(); 848 } 849 850 QualType T = Context.getObjCInterfaceType(Class); 851 return ParsedType::make(T); 852 } 853 854 // We can have a type template here if we're classifying a template argument. 855 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 856 return NameClassification::TypeTemplate( 857 TemplateName(cast<TemplateDecl>(FirstDecl))); 858 859 // Check for a tag type hidden by a non-type decl in a few cases where it 860 // seems likely a type is wanted instead of the non-type that was found. 861 if (!getLangOpts().ObjC1) { 862 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 863 if ((NextToken.is(tok::identifier) || 864 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 865 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 866 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 867 DiagnoseUseOfDecl(Type, NameLoc); 868 QualType T = Context.getTypeDeclType(Type); 869 if (SS.isNotEmpty()) 870 return buildNestedType(*this, SS, T, NameLoc); 871 return ParsedType::make(T); 872 } 873 } 874 875 if (FirstDecl->isCXXClassMember()) 876 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 877 878 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 879 return BuildDeclarationNameExpr(SS, Result, ADL); 880} 881 882// Determines the context to return to after temporarily entering a 883// context. This depends in an unnecessarily complicated way on the 884// exact ordering of callbacks from the parser. 885DeclContext *Sema::getContainingDC(DeclContext *DC) { 886 887 // Functions defined inline within classes aren't parsed until we've 888 // finished parsing the top-level class, so the top-level class is 889 // the context we'll need to return to. 890 if (isa<FunctionDecl>(DC)) { 891 DC = DC->getLexicalParent(); 892 893 // A function not defined within a class will always return to its 894 // lexical context. 895 if (!isa<CXXRecordDecl>(DC)) 896 return DC; 897 898 // A C++ inline method/friend is parsed *after* the topmost class 899 // it was declared in is fully parsed ("complete"); the topmost 900 // class is the context we need to return to. 901 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 902 DC = RD; 903 904 // Return the declaration context of the topmost class the inline method is 905 // declared in. 906 return DC; 907 } 908 909 return DC->getLexicalParent(); 910} 911 912void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 913 assert(getContainingDC(DC) == CurContext && 914 "The next DeclContext should be lexically contained in the current one."); 915 CurContext = DC; 916 S->setEntity(DC); 917} 918 919void Sema::PopDeclContext() { 920 assert(CurContext && "DeclContext imbalance!"); 921 922 CurContext = getContainingDC(CurContext); 923 assert(CurContext && "Popped translation unit!"); 924} 925 926/// EnterDeclaratorContext - Used when we must lookup names in the context 927/// of a declarator's nested name specifier. 928/// 929void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 930 // C++0x [basic.lookup.unqual]p13: 931 // A name used in the definition of a static data member of class 932 // X (after the qualified-id of the static member) is looked up as 933 // if the name was used in a member function of X. 934 // C++0x [basic.lookup.unqual]p14: 935 // If a variable member of a namespace is defined outside of the 936 // scope of its namespace then any name used in the definition of 937 // the variable member (after the declarator-id) is looked up as 938 // if the definition of the variable member occurred in its 939 // namespace. 940 // Both of these imply that we should push a scope whose context 941 // is the semantic context of the declaration. We can't use 942 // PushDeclContext here because that context is not necessarily 943 // lexically contained in the current context. Fortunately, 944 // the containing scope should have the appropriate information. 945 946 assert(!S->getEntity() && "scope already has entity"); 947 948#ifndef NDEBUG 949 Scope *Ancestor = S->getParent(); 950 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 951 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 952#endif 953 954 CurContext = DC; 955 S->setEntity(DC); 956} 957 958void Sema::ExitDeclaratorContext(Scope *S) { 959 assert(S->getEntity() == CurContext && "Context imbalance!"); 960 961 // Switch back to the lexical context. The safety of this is 962 // enforced by an assert in EnterDeclaratorContext. 963 Scope *Ancestor = S->getParent(); 964 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 965 CurContext = (DeclContext*) Ancestor->getEntity(); 966 967 // We don't need to do anything with the scope, which is going to 968 // disappear. 969} 970 971 972void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 973 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 974 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 975 // We assume that the caller has already called 976 // ActOnReenterTemplateScope 977 FD = TFD->getTemplatedDecl(); 978 } 979 if (!FD) 980 return; 981 982 // Same implementation as PushDeclContext, but enters the context 983 // from the lexical parent, rather than the top-level class. 984 assert(CurContext == FD->getLexicalParent() && 985 "The next DeclContext should be lexically contained in the current one."); 986 CurContext = FD; 987 S->setEntity(CurContext); 988 989 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 990 ParmVarDecl *Param = FD->getParamDecl(P); 991 // If the parameter has an identifier, then add it to the scope 992 if (Param->getIdentifier()) { 993 S->AddDecl(Param); 994 IdResolver.AddDecl(Param); 995 } 996 } 997} 998 999 1000void Sema::ActOnExitFunctionContext() { 1001 // Same implementation as PopDeclContext, but returns to the lexical parent, 1002 // rather than the top-level class. 1003 assert(CurContext && "DeclContext imbalance!"); 1004 CurContext = CurContext->getLexicalParent(); 1005 assert(CurContext && "Popped translation unit!"); 1006} 1007 1008 1009/// \brief Determine whether we allow overloading of the function 1010/// PrevDecl with another declaration. 1011/// 1012/// This routine determines whether overloading is possible, not 1013/// whether some new function is actually an overload. It will return 1014/// true in C++ (where we can always provide overloads) or, as an 1015/// extension, in C when the previous function is already an 1016/// overloaded function declaration or has the "overloadable" 1017/// attribute. 1018static bool AllowOverloadingOfFunction(LookupResult &Previous, 1019 ASTContext &Context) { 1020 if (Context.getLangOpts().CPlusPlus) 1021 return true; 1022 1023 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1024 return true; 1025 1026 return (Previous.getResultKind() == LookupResult::Found 1027 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1028} 1029 1030/// Add this decl to the scope shadowed decl chains. 1031void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1032 // Move up the scope chain until we find the nearest enclosing 1033 // non-transparent context. The declaration will be introduced into this 1034 // scope. 1035 while (S->getEntity() && 1036 ((DeclContext *)S->getEntity())->isTransparentContext()) 1037 S = S->getParent(); 1038 1039 // Add scoped declarations into their context, so that they can be 1040 // found later. Declarations without a context won't be inserted 1041 // into any context. 1042 if (AddToContext) 1043 CurContext->addDecl(D); 1044 1045 // Out-of-line definitions shouldn't be pushed into scope in C++. 1046 // Out-of-line variable and function definitions shouldn't even in C. 1047 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 1048 D->isOutOfLine() && 1049 !D->getDeclContext()->getRedeclContext()->Equals( 1050 D->getLexicalDeclContext()->getRedeclContext())) 1051 return; 1052 1053 // Template instantiations should also not be pushed into scope. 1054 if (isa<FunctionDecl>(D) && 1055 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1056 return; 1057 1058 // If this replaces anything in the current scope, 1059 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1060 IEnd = IdResolver.end(); 1061 for (; I != IEnd; ++I) { 1062 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1063 S->RemoveDecl(*I); 1064 IdResolver.RemoveDecl(*I); 1065 1066 // Should only need to replace one decl. 1067 break; 1068 } 1069 } 1070 1071 S->AddDecl(D); 1072 1073 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1074 // Implicitly-generated labels may end up getting generated in an order that 1075 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1076 // the label at the appropriate place in the identifier chain. 1077 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1078 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1079 if (IDC == CurContext) { 1080 if (!S->isDeclScope(*I)) 1081 continue; 1082 } else if (IDC->Encloses(CurContext)) 1083 break; 1084 } 1085 1086 IdResolver.InsertDeclAfter(I, D); 1087 } else { 1088 IdResolver.AddDecl(D); 1089 } 1090} 1091 1092void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1093 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1094 TUScope->AddDecl(D); 1095} 1096 1097bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 1098 bool ExplicitInstantiationOrSpecialization) { 1099 return IdResolver.isDeclInScope(D, Ctx, S, 1100 ExplicitInstantiationOrSpecialization); 1101} 1102 1103Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1104 DeclContext *TargetDC = DC->getPrimaryContext(); 1105 do { 1106 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 1107 if (ScopeDC->getPrimaryContext() == TargetDC) 1108 return S; 1109 } while ((S = S->getParent())); 1110 1111 return 0; 1112} 1113 1114static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1115 DeclContext*, 1116 ASTContext&); 1117 1118/// Filters out lookup results that don't fall within the given scope 1119/// as determined by isDeclInScope. 1120void Sema::FilterLookupForScope(LookupResult &R, 1121 DeclContext *Ctx, Scope *S, 1122 bool ConsiderLinkage, 1123 bool ExplicitInstantiationOrSpecialization) { 1124 LookupResult::Filter F = R.makeFilter(); 1125 while (F.hasNext()) { 1126 NamedDecl *D = F.next(); 1127 1128 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1129 continue; 1130 1131 if (ConsiderLinkage && 1132 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1133 continue; 1134 1135 F.erase(); 1136 } 1137 1138 F.done(); 1139} 1140 1141static bool isUsingDecl(NamedDecl *D) { 1142 return isa<UsingShadowDecl>(D) || 1143 isa<UnresolvedUsingTypenameDecl>(D) || 1144 isa<UnresolvedUsingValueDecl>(D); 1145} 1146 1147/// Removes using shadow declarations from the lookup results. 1148static void RemoveUsingDecls(LookupResult &R) { 1149 LookupResult::Filter F = R.makeFilter(); 1150 while (F.hasNext()) 1151 if (isUsingDecl(F.next())) 1152 F.erase(); 1153 1154 F.done(); 1155} 1156 1157/// \brief Check for this common pattern: 1158/// @code 1159/// class S { 1160/// S(const S&); // DO NOT IMPLEMENT 1161/// void operator=(const S&); // DO NOT IMPLEMENT 1162/// }; 1163/// @endcode 1164static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1165 // FIXME: Should check for private access too but access is set after we get 1166 // the decl here. 1167 if (D->doesThisDeclarationHaveABody()) 1168 return false; 1169 1170 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1171 return CD->isCopyConstructor(); 1172 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1173 return Method->isCopyAssignmentOperator(); 1174 return false; 1175} 1176 1177// We need this to handle 1178// 1179// typedef struct { 1180// void *foo() { return 0; } 1181// } A; 1182// 1183// When we see foo we don't know if after the typedef we will get 'A' or '*A' 1184// for example. If 'A', foo will have external linkage. If we have '*A', 1185// foo will have no linkage. Since we can't know untill we get to the end 1186// of the typedef, this function finds out if D might have non external linkage. 1187// Callers should verify at the end of the TU if it D has external linkage or 1188// not. 1189bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1190 const DeclContext *DC = D->getDeclContext(); 1191 while (!DC->isTranslationUnit()) { 1192 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1193 if (!RD->hasNameForLinkage()) 1194 return true; 1195 } 1196 DC = DC->getParent(); 1197 } 1198 1199 return !D->hasExternalLinkage(); 1200} 1201 1202bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1203 assert(D); 1204 1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1206 return false; 1207 1208 // Ignore class templates. 1209 if (D->getDeclContext()->isDependentContext() || 1210 D->getLexicalDeclContext()->isDependentContext()) 1211 return false; 1212 1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1215 return false; 1216 1217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1219 return false; 1220 } else { 1221 // 'static inline' functions are used in headers; don't warn. 1222 if (FD->getStorageClass() == SC_Static && 1223 FD->isInlineSpecified()) 1224 return false; 1225 } 1226 1227 if (FD->doesThisDeclarationHaveABody() && 1228 Context.DeclMustBeEmitted(FD)) 1229 return false; 1230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1231 // Don't warn on variables of const-qualified or reference type, since their 1232 // values can be used even if though they're not odr-used, and because const 1233 // qualified variables can appear in headers in contexts where they're not 1234 // intended to be used. 1235 // FIXME: Use more principled rules for these exemptions. 1236 if (!VD->isFileVarDecl() || 1237 VD->getType().isConstQualified() || 1238 VD->getType()->isReferenceType() || 1239 Context.DeclMustBeEmitted(VD)) 1240 return false; 1241 1242 if (VD->isStaticDataMember() && 1243 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1244 return false; 1245 1246 } else { 1247 return false; 1248 } 1249 1250 // Only warn for unused decls internal to the translation unit. 1251 return mightHaveNonExternalLinkage(D); 1252} 1253 1254void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1255 if (!D) 1256 return; 1257 1258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1259 const FunctionDecl *First = FD->getFirstDeclaration(); 1260 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1261 return; // First should already be in the vector. 1262 } 1263 1264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1265 const VarDecl *First = VD->getFirstDeclaration(); 1266 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1267 return; // First should already be in the vector. 1268 } 1269 1270 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1271 UnusedFileScopedDecls.push_back(D); 1272} 1273 1274static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1275 if (D->isInvalidDecl()) 1276 return false; 1277 1278 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1279 return false; 1280 1281 if (isa<LabelDecl>(D)) 1282 return true; 1283 1284 // White-list anything that isn't a local variable. 1285 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1286 !D->getDeclContext()->isFunctionOrMethod()) 1287 return false; 1288 1289 // Types of valid local variables should be complete, so this should succeed. 1290 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1291 1292 // White-list anything with an __attribute__((unused)) type. 1293 QualType Ty = VD->getType(); 1294 1295 // Only look at the outermost level of typedef. 1296 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1297 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1298 return false; 1299 } 1300 1301 // If we failed to complete the type for some reason, or if the type is 1302 // dependent, don't diagnose the variable. 1303 if (Ty->isIncompleteType() || Ty->isDependentType()) 1304 return false; 1305 1306 if (const TagType *TT = Ty->getAs<TagType>()) { 1307 const TagDecl *Tag = TT->getDecl(); 1308 if (Tag->hasAttr<UnusedAttr>()) 1309 return false; 1310 1311 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1312 if (!RD->hasTrivialDestructor()) 1313 return false; 1314 1315 if (const Expr *Init = VD->getInit()) { 1316 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1317 Init = Cleanups->getSubExpr(); 1318 const CXXConstructExpr *Construct = 1319 dyn_cast<CXXConstructExpr>(Init); 1320 if (Construct && !Construct->isElidable()) { 1321 CXXConstructorDecl *CD = Construct->getConstructor(); 1322 if (!CD->isTrivial()) 1323 return false; 1324 } 1325 } 1326 } 1327 } 1328 1329 // TODO: __attribute__((unused)) templates? 1330 } 1331 1332 return true; 1333} 1334 1335static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1336 FixItHint &Hint) { 1337 if (isa<LabelDecl>(D)) { 1338 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1339 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1340 if (AfterColon.isInvalid()) 1341 return; 1342 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1343 getCharRange(D->getLocStart(), AfterColon)); 1344 } 1345 return; 1346} 1347 1348/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1349/// unless they are marked attr(unused). 1350void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1351 FixItHint Hint; 1352 if (!ShouldDiagnoseUnusedDecl(D)) 1353 return; 1354 1355 GenerateFixForUnusedDecl(D, Context, Hint); 1356 1357 unsigned DiagID; 1358 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1359 DiagID = diag::warn_unused_exception_param; 1360 else if (isa<LabelDecl>(D)) 1361 DiagID = diag::warn_unused_label; 1362 else 1363 DiagID = diag::warn_unused_variable; 1364 1365 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1366} 1367 1368static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1369 // Verify that we have no forward references left. If so, there was a goto 1370 // or address of a label taken, but no definition of it. Label fwd 1371 // definitions are indicated with a null substmt. 1372 if (L->getStmt() == 0) 1373 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1374} 1375 1376void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1377 if (S->decl_empty()) return; 1378 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1379 "Scope shouldn't contain decls!"); 1380 1381 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1382 I != E; ++I) { 1383 Decl *TmpD = (*I); 1384 assert(TmpD && "This decl didn't get pushed??"); 1385 1386 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1387 NamedDecl *D = cast<NamedDecl>(TmpD); 1388 1389 if (!D->getDeclName()) continue; 1390 1391 // Diagnose unused variables in this scope. 1392 if (!S->hasUnrecoverableErrorOccurred()) 1393 DiagnoseUnusedDecl(D); 1394 1395 // If this was a forward reference to a label, verify it was defined. 1396 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1397 CheckPoppedLabel(LD, *this); 1398 1399 // Remove this name from our lexical scope. 1400 IdResolver.RemoveDecl(D); 1401 } 1402} 1403 1404void Sema::ActOnStartFunctionDeclarator() { 1405 ++InFunctionDeclarator; 1406} 1407 1408void Sema::ActOnEndFunctionDeclarator() { 1409 assert(InFunctionDeclarator); 1410 --InFunctionDeclarator; 1411} 1412 1413/// \brief Look for an Objective-C class in the translation unit. 1414/// 1415/// \param Id The name of the Objective-C class we're looking for. If 1416/// typo-correction fixes this name, the Id will be updated 1417/// to the fixed name. 1418/// 1419/// \param IdLoc The location of the name in the translation unit. 1420/// 1421/// \param DoTypoCorrection If true, this routine will attempt typo correction 1422/// if there is no class with the given name. 1423/// 1424/// \returns The declaration of the named Objective-C class, or NULL if the 1425/// class could not be found. 1426ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1427 SourceLocation IdLoc, 1428 bool DoTypoCorrection) { 1429 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1430 // creation from this context. 1431 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1432 1433 if (!IDecl && DoTypoCorrection) { 1434 // Perform typo correction at the given location, but only if we 1435 // find an Objective-C class name. 1436 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1437 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1438 LookupOrdinaryName, TUScope, NULL, 1439 Validator)) { 1440 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1441 Diag(IdLoc, diag::err_undef_interface_suggest) 1442 << Id << IDecl->getDeclName() 1443 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1444 Diag(IDecl->getLocation(), diag::note_previous_decl) 1445 << IDecl->getDeclName(); 1446 1447 Id = IDecl->getIdentifier(); 1448 } 1449 } 1450 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1451 // This routine must always return a class definition, if any. 1452 if (Def && Def->getDefinition()) 1453 Def = Def->getDefinition(); 1454 return Def; 1455} 1456 1457/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1458/// from S, where a non-field would be declared. This routine copes 1459/// with the difference between C and C++ scoping rules in structs and 1460/// unions. For example, the following code is well-formed in C but 1461/// ill-formed in C++: 1462/// @code 1463/// struct S6 { 1464/// enum { BAR } e; 1465/// }; 1466/// 1467/// void test_S6() { 1468/// struct S6 a; 1469/// a.e = BAR; 1470/// } 1471/// @endcode 1472/// For the declaration of BAR, this routine will return a different 1473/// scope. The scope S will be the scope of the unnamed enumeration 1474/// within S6. In C++, this routine will return the scope associated 1475/// with S6, because the enumeration's scope is a transparent 1476/// context but structures can contain non-field names. In C, this 1477/// routine will return the translation unit scope, since the 1478/// enumeration's scope is a transparent context and structures cannot 1479/// contain non-field names. 1480Scope *Sema::getNonFieldDeclScope(Scope *S) { 1481 while (((S->getFlags() & Scope::DeclScope) == 0) || 1482 (S->getEntity() && 1483 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1484 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1485 S = S->getParent(); 1486 return S; 1487} 1488 1489/// \brief Looks up the declaration of "struct objc_super" and 1490/// saves it for later use in building builtin declaration of 1491/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1492/// pre-existing declaration exists no action takes place. 1493static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1494 IdentifierInfo *II) { 1495 if (!II->isStr("objc_msgSendSuper")) 1496 return; 1497 ASTContext &Context = ThisSema.Context; 1498 1499 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1500 SourceLocation(), Sema::LookupTagName); 1501 ThisSema.LookupName(Result, S); 1502 if (Result.getResultKind() == LookupResult::Found) 1503 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1504 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1505} 1506 1507/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1508/// file scope. lazily create a decl for it. ForRedeclaration is true 1509/// if we're creating this built-in in anticipation of redeclaring the 1510/// built-in. 1511NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1512 Scope *S, bool ForRedeclaration, 1513 SourceLocation Loc) { 1514 LookupPredefedObjCSuperType(*this, S, II); 1515 1516 Builtin::ID BID = (Builtin::ID)bid; 1517 1518 ASTContext::GetBuiltinTypeError Error; 1519 QualType R = Context.GetBuiltinType(BID, Error); 1520 switch (Error) { 1521 case ASTContext::GE_None: 1522 // Okay 1523 break; 1524 1525 case ASTContext::GE_Missing_stdio: 1526 if (ForRedeclaration) 1527 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1528 << Context.BuiltinInfo.GetName(BID); 1529 return 0; 1530 1531 case ASTContext::GE_Missing_setjmp: 1532 if (ForRedeclaration) 1533 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1534 << Context.BuiltinInfo.GetName(BID); 1535 return 0; 1536 1537 case ASTContext::GE_Missing_ucontext: 1538 if (ForRedeclaration) 1539 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1540 << Context.BuiltinInfo.GetName(BID); 1541 return 0; 1542 } 1543 1544 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1545 Diag(Loc, diag::ext_implicit_lib_function_decl) 1546 << Context.BuiltinInfo.GetName(BID) 1547 << R; 1548 if (Context.BuiltinInfo.getHeaderName(BID) && 1549 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1550 != DiagnosticsEngine::Ignored) 1551 Diag(Loc, diag::note_please_include_header) 1552 << Context.BuiltinInfo.getHeaderName(BID) 1553 << Context.BuiltinInfo.GetName(BID); 1554 } 1555 1556 FunctionDecl *New = FunctionDecl::Create(Context, 1557 Context.getTranslationUnitDecl(), 1558 Loc, Loc, II, R, /*TInfo=*/0, 1559 SC_Extern, 1560 false, 1561 /*hasPrototype=*/true); 1562 New->setImplicit(); 1563 1564 // Create Decl objects for each parameter, adding them to the 1565 // FunctionDecl. 1566 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1567 SmallVector<ParmVarDecl*, 16> Params; 1568 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1569 ParmVarDecl *parm = 1570 ParmVarDecl::Create(Context, New, SourceLocation(), 1571 SourceLocation(), 0, 1572 FT->getArgType(i), /*TInfo=*/0, 1573 SC_None, 0); 1574 parm->setScopeInfo(0, i); 1575 Params.push_back(parm); 1576 } 1577 New->setParams(Params); 1578 } 1579 1580 AddKnownFunctionAttributes(New); 1581 1582 // TUScope is the translation-unit scope to insert this function into. 1583 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1584 // relate Scopes to DeclContexts, and probably eliminate CurContext 1585 // entirely, but we're not there yet. 1586 DeclContext *SavedContext = CurContext; 1587 CurContext = Context.getTranslationUnitDecl(); 1588 PushOnScopeChains(New, TUScope); 1589 CurContext = SavedContext; 1590 return New; 1591} 1592 1593/// \brief Filter out any previous declarations that the given declaration 1594/// should not consider because they are not permitted to conflict, e.g., 1595/// because they come from hidden sub-modules and do not refer to the same 1596/// entity. 1597static void filterNonConflictingPreviousDecls(ASTContext &context, 1598 NamedDecl *decl, 1599 LookupResult &previous){ 1600 // This is only interesting when modules are enabled. 1601 if (!context.getLangOpts().Modules) 1602 return; 1603 1604 // Empty sets are uninteresting. 1605 if (previous.empty()) 1606 return; 1607 1608 LookupResult::Filter filter = previous.makeFilter(); 1609 while (filter.hasNext()) { 1610 NamedDecl *old = filter.next(); 1611 1612 // Non-hidden declarations are never ignored. 1613 if (!old->isHidden()) 1614 continue; 1615 1616 // If either has no-external linkage, ignore the old declaration. 1617 // If this declaration would have external linkage if it were the first 1618 // declaration of this name, then it may in fact be a redeclaration of 1619 // some hidden declaration, so include those too. We don't need to worry 1620 // about some previous visible declaration giving this declaration external 1621 // linkage, because in that case, we'll mark this declaration as a redecl 1622 // of the visible decl, and that decl will already be a redecl of the 1623 // hidden declaration if that's appropriate. 1624 // 1625 // Don't cache this linkage computation, because it's not yet correct: we 1626 // may later give this declaration a previous declaration which changes 1627 // its linkage. 1628 if (old->getLinkage() != ExternalLinkage || 1629 !decl->hasExternalLinkageUncached()) 1630 filter.erase(); 1631 } 1632 1633 filter.done(); 1634} 1635 1636bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1637 QualType OldType; 1638 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1639 OldType = OldTypedef->getUnderlyingType(); 1640 else 1641 OldType = Context.getTypeDeclType(Old); 1642 QualType NewType = New->getUnderlyingType(); 1643 1644 if (NewType->isVariablyModifiedType()) { 1645 // Must not redefine a typedef with a variably-modified type. 1646 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1647 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1648 << Kind << NewType; 1649 if (Old->getLocation().isValid()) 1650 Diag(Old->getLocation(), diag::note_previous_definition); 1651 New->setInvalidDecl(); 1652 return true; 1653 } 1654 1655 if (OldType != NewType && 1656 !OldType->isDependentType() && 1657 !NewType->isDependentType() && 1658 !Context.hasSameType(OldType, NewType)) { 1659 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1660 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1661 << Kind << NewType << OldType; 1662 if (Old->getLocation().isValid()) 1663 Diag(Old->getLocation(), diag::note_previous_definition); 1664 New->setInvalidDecl(); 1665 return true; 1666 } 1667 return false; 1668} 1669 1670/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1671/// same name and scope as a previous declaration 'Old'. Figure out 1672/// how to resolve this situation, merging decls or emitting 1673/// diagnostics as appropriate. If there was an error, set New to be invalid. 1674/// 1675void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1676 // If the new decl is known invalid already, don't bother doing any 1677 // merging checks. 1678 if (New->isInvalidDecl()) return; 1679 1680 // Allow multiple definitions for ObjC built-in typedefs. 1681 // FIXME: Verify the underlying types are equivalent! 1682 if (getLangOpts().ObjC1) { 1683 const IdentifierInfo *TypeID = New->getIdentifier(); 1684 switch (TypeID->getLength()) { 1685 default: break; 1686 case 2: 1687 { 1688 if (!TypeID->isStr("id")) 1689 break; 1690 QualType T = New->getUnderlyingType(); 1691 if (!T->isPointerType()) 1692 break; 1693 if (!T->isVoidPointerType()) { 1694 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1695 if (!PT->isStructureType()) 1696 break; 1697 } 1698 Context.setObjCIdRedefinitionType(T); 1699 // Install the built-in type for 'id', ignoring the current definition. 1700 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1701 return; 1702 } 1703 case 5: 1704 if (!TypeID->isStr("Class")) 1705 break; 1706 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1707 // Install the built-in type for 'Class', ignoring the current definition. 1708 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1709 return; 1710 case 3: 1711 if (!TypeID->isStr("SEL")) 1712 break; 1713 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1714 // Install the built-in type for 'SEL', ignoring the current definition. 1715 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1716 return; 1717 } 1718 // Fall through - the typedef name was not a builtin type. 1719 } 1720 1721 // Verify the old decl was also a type. 1722 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1723 if (!Old) { 1724 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1725 << New->getDeclName(); 1726 1727 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1728 if (OldD->getLocation().isValid()) 1729 Diag(OldD->getLocation(), diag::note_previous_definition); 1730 1731 return New->setInvalidDecl(); 1732 } 1733 1734 // If the old declaration is invalid, just give up here. 1735 if (Old->isInvalidDecl()) 1736 return New->setInvalidDecl(); 1737 1738 // If the typedef types are not identical, reject them in all languages and 1739 // with any extensions enabled. 1740 if (isIncompatibleTypedef(Old, New)) 1741 return; 1742 1743 // The types match. Link up the redeclaration chain if the old 1744 // declaration was a typedef. 1745 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1746 New->setPreviousDeclaration(Typedef); 1747 1748 if (getLangOpts().MicrosoftExt) 1749 return; 1750 1751 if (getLangOpts().CPlusPlus) { 1752 // C++ [dcl.typedef]p2: 1753 // In a given non-class scope, a typedef specifier can be used to 1754 // redefine the name of any type declared in that scope to refer 1755 // to the type to which it already refers. 1756 if (!isa<CXXRecordDecl>(CurContext)) 1757 return; 1758 1759 // C++0x [dcl.typedef]p4: 1760 // In a given class scope, a typedef specifier can be used to redefine 1761 // any class-name declared in that scope that is not also a typedef-name 1762 // to refer to the type to which it already refers. 1763 // 1764 // This wording came in via DR424, which was a correction to the 1765 // wording in DR56, which accidentally banned code like: 1766 // 1767 // struct S { 1768 // typedef struct A { } A; 1769 // }; 1770 // 1771 // in the C++03 standard. We implement the C++0x semantics, which 1772 // allow the above but disallow 1773 // 1774 // struct S { 1775 // typedef int I; 1776 // typedef int I; 1777 // }; 1778 // 1779 // since that was the intent of DR56. 1780 if (!isa<TypedefNameDecl>(Old)) 1781 return; 1782 1783 Diag(New->getLocation(), diag::err_redefinition) 1784 << New->getDeclName(); 1785 Diag(Old->getLocation(), diag::note_previous_definition); 1786 return New->setInvalidDecl(); 1787 } 1788 1789 // Modules always permit redefinition of typedefs, as does C11. 1790 if (getLangOpts().Modules || getLangOpts().C11) 1791 return; 1792 1793 // If we have a redefinition of a typedef in C, emit a warning. This warning 1794 // is normally mapped to an error, but can be controlled with 1795 // -Wtypedef-redefinition. If either the original or the redefinition is 1796 // in a system header, don't emit this for compatibility with GCC. 1797 if (getDiagnostics().getSuppressSystemWarnings() && 1798 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1799 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1800 return; 1801 1802 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1803 << New->getDeclName(); 1804 Diag(Old->getLocation(), diag::note_previous_definition); 1805 return; 1806} 1807 1808/// DeclhasAttr - returns true if decl Declaration already has the target 1809/// attribute. 1810static bool 1811DeclHasAttr(const Decl *D, const Attr *A) { 1812 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1813 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1814 // responsible for making sure they are consistent. 1815 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1816 if (AA) 1817 return false; 1818 1819 // The following thread safety attributes can also be duplicated. 1820 switch (A->getKind()) { 1821 case attr::ExclusiveLocksRequired: 1822 case attr::SharedLocksRequired: 1823 case attr::LocksExcluded: 1824 case attr::ExclusiveLockFunction: 1825 case attr::SharedLockFunction: 1826 case attr::UnlockFunction: 1827 case attr::ExclusiveTrylockFunction: 1828 case attr::SharedTrylockFunction: 1829 case attr::GuardedBy: 1830 case attr::PtGuardedBy: 1831 case attr::AcquiredBefore: 1832 case attr::AcquiredAfter: 1833 return false; 1834 default: 1835 ; 1836 } 1837 1838 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1839 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1840 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1841 if ((*i)->getKind() == A->getKind()) { 1842 if (Ann) { 1843 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1844 return true; 1845 continue; 1846 } 1847 // FIXME: Don't hardcode this check 1848 if (OA && isa<OwnershipAttr>(*i)) 1849 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1850 return true; 1851 } 1852 1853 return false; 1854} 1855 1856static bool isAttributeTargetADefinition(Decl *D) { 1857 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1858 return VD->isThisDeclarationADefinition(); 1859 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1860 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1861 return true; 1862} 1863 1864/// Merge alignment attributes from \p Old to \p New, taking into account the 1865/// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1866/// 1867/// \return \c true if any attributes were added to \p New. 1868static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1869 // Look for alignas attributes on Old, and pick out whichever attribute 1870 // specifies the strictest alignment requirement. 1871 AlignedAttr *OldAlignasAttr = 0; 1872 AlignedAttr *OldStrictestAlignAttr = 0; 1873 unsigned OldAlign = 0; 1874 for (specific_attr_iterator<AlignedAttr> 1875 I = Old->specific_attr_begin<AlignedAttr>(), 1876 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1877 // FIXME: We have no way of representing inherited dependent alignments 1878 // in a case like: 1879 // template<int A, int B> struct alignas(A) X; 1880 // template<int A, int B> struct alignas(B) X {}; 1881 // For now, we just ignore any alignas attributes which are not on the 1882 // definition in such a case. 1883 if (I->isAlignmentDependent()) 1884 return false; 1885 1886 if (I->isAlignas()) 1887 OldAlignasAttr = *I; 1888 1889 unsigned Align = I->getAlignment(S.Context); 1890 if (Align > OldAlign) { 1891 OldAlign = Align; 1892 OldStrictestAlignAttr = *I; 1893 } 1894 } 1895 1896 // Look for alignas attributes on New. 1897 AlignedAttr *NewAlignasAttr = 0; 1898 unsigned NewAlign = 0; 1899 for (specific_attr_iterator<AlignedAttr> 1900 I = New->specific_attr_begin<AlignedAttr>(), 1901 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1902 if (I->isAlignmentDependent()) 1903 return false; 1904 1905 if (I->isAlignas()) 1906 NewAlignasAttr = *I; 1907 1908 unsigned Align = I->getAlignment(S.Context); 1909 if (Align > NewAlign) 1910 NewAlign = Align; 1911 } 1912 1913 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1914 // Both declarations have 'alignas' attributes. We require them to match. 1915 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1916 // fall short. (If two declarations both have alignas, they must both match 1917 // every definition, and so must match each other if there is a definition.) 1918 1919 // If either declaration only contains 'alignas(0)' specifiers, then it 1920 // specifies the natural alignment for the type. 1921 if (OldAlign == 0 || NewAlign == 0) { 1922 QualType Ty; 1923 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1924 Ty = VD->getType(); 1925 else 1926 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1927 1928 if (OldAlign == 0) 1929 OldAlign = S.Context.getTypeAlign(Ty); 1930 if (NewAlign == 0) 1931 NewAlign = S.Context.getTypeAlign(Ty); 1932 } 1933 1934 if (OldAlign != NewAlign) { 1935 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1936 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1937 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1938 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1939 } 1940 } 1941 1942 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1943 // C++11 [dcl.align]p6: 1944 // if any declaration of an entity has an alignment-specifier, 1945 // every defining declaration of that entity shall specify an 1946 // equivalent alignment. 1947 // C11 6.7.5/7: 1948 // If the definition of an object does not have an alignment 1949 // specifier, any other declaration of that object shall also 1950 // have no alignment specifier. 1951 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1952 << OldAlignasAttr->isC11(); 1953 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1954 << OldAlignasAttr->isC11(); 1955 } 1956 1957 bool AnyAdded = false; 1958 1959 // Ensure we have an attribute representing the strictest alignment. 1960 if (OldAlign > NewAlign) { 1961 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1962 Clone->setInherited(true); 1963 New->addAttr(Clone); 1964 AnyAdded = true; 1965 } 1966 1967 // Ensure we have an alignas attribute if the old declaration had one. 1968 if (OldAlignasAttr && !NewAlignasAttr && 1969 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1970 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1971 Clone->setInherited(true); 1972 New->addAttr(Clone); 1973 AnyAdded = true; 1974 } 1975 1976 return AnyAdded; 1977} 1978 1979static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1980 bool Override) { 1981 InheritableAttr *NewAttr = NULL; 1982 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1983 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1984 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1985 AA->getIntroduced(), AA->getDeprecated(), 1986 AA->getObsoleted(), AA->getUnavailable(), 1987 AA->getMessage(), Override, 1988 AttrSpellingListIndex); 1989 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1990 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1991 AttrSpellingListIndex); 1992 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1993 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1994 AttrSpellingListIndex); 1995 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1996 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1997 AttrSpellingListIndex); 1998 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1999 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2000 AttrSpellingListIndex); 2001 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 2002 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2003 FA->getFormatIdx(), FA->getFirstArg(), 2004 AttrSpellingListIndex); 2005 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 2006 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2007 AttrSpellingListIndex); 2008 else if (isa<AlignedAttr>(Attr)) 2009 // AlignedAttrs are handled separately, because we need to handle all 2010 // such attributes on a declaration at the same time. 2011 NewAttr = 0; 2012 else if (!DeclHasAttr(D, Attr)) 2013 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2014 2015 if (NewAttr) { 2016 NewAttr->setInherited(true); 2017 D->addAttr(NewAttr); 2018 return true; 2019 } 2020 2021 return false; 2022} 2023 2024static const Decl *getDefinition(const Decl *D) { 2025 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2026 return TD->getDefinition(); 2027 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2028 return VD->getDefinition(); 2029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2030 const FunctionDecl* Def; 2031 if (FD->hasBody(Def)) 2032 return Def; 2033 } 2034 return NULL; 2035} 2036 2037static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2038 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2039 I != E; ++I) { 2040 Attr *Attribute = *I; 2041 if (Attribute->getKind() == Kind) 2042 return true; 2043 } 2044 return false; 2045} 2046 2047/// checkNewAttributesAfterDef - If we already have a definition, check that 2048/// there are no new attributes in this declaration. 2049static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2050 if (!New->hasAttrs()) 2051 return; 2052 2053 const Decl *Def = getDefinition(Old); 2054 if (!Def || Def == New) 2055 return; 2056 2057 AttrVec &NewAttributes = New->getAttrs(); 2058 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2059 const Attr *NewAttribute = NewAttributes[I]; 2060 if (hasAttribute(Def, NewAttribute->getKind())) { 2061 ++I; 2062 continue; // regular attr merging will take care of validating this. 2063 } 2064 2065 if (isa<C11NoReturnAttr>(NewAttribute)) { 2066 // C's _Noreturn is allowed to be added to a function after it is defined. 2067 ++I; 2068 continue; 2069 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2070 if (AA->isAlignas()) { 2071 // C++11 [dcl.align]p6: 2072 // if any declaration of an entity has an alignment-specifier, 2073 // every defining declaration of that entity shall specify an 2074 // equivalent alignment. 2075 // C11 6.7.5/7: 2076 // If the definition of an object does not have an alignment 2077 // specifier, any other declaration of that object shall also 2078 // have no alignment specifier. 2079 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2080 << AA->isC11(); 2081 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2082 << AA->isC11(); 2083 NewAttributes.erase(NewAttributes.begin() + I); 2084 --E; 2085 continue; 2086 } 2087 } 2088 2089 S.Diag(NewAttribute->getLocation(), 2090 diag::warn_attribute_precede_definition); 2091 S.Diag(Def->getLocation(), diag::note_previous_definition); 2092 NewAttributes.erase(NewAttributes.begin() + I); 2093 --E; 2094 } 2095} 2096 2097/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2098void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2099 AvailabilityMergeKind AMK) { 2100 if (!Old->hasAttrs() && !New->hasAttrs()) 2101 return; 2102 2103 // attributes declared post-definition are currently ignored 2104 checkNewAttributesAfterDef(*this, New, Old); 2105 2106 if (!Old->hasAttrs()) 2107 return; 2108 2109 bool foundAny = New->hasAttrs(); 2110 2111 // Ensure that any moving of objects within the allocated map is done before 2112 // we process them. 2113 if (!foundAny) New->setAttrs(AttrVec()); 2114 2115 for (specific_attr_iterator<InheritableAttr> 2116 i = Old->specific_attr_begin<InheritableAttr>(), 2117 e = Old->specific_attr_end<InheritableAttr>(); 2118 i != e; ++i) { 2119 bool Override = false; 2120 // Ignore deprecated/unavailable/availability attributes if requested. 2121 if (isa<DeprecatedAttr>(*i) || 2122 isa<UnavailableAttr>(*i) || 2123 isa<AvailabilityAttr>(*i)) { 2124 switch (AMK) { 2125 case AMK_None: 2126 continue; 2127 2128 case AMK_Redeclaration: 2129 break; 2130 2131 case AMK_Override: 2132 Override = true; 2133 break; 2134 } 2135 } 2136 2137 if (mergeDeclAttribute(*this, New, *i, Override)) 2138 foundAny = true; 2139 } 2140 2141 if (mergeAlignedAttrs(*this, New, Old)) 2142 foundAny = true; 2143 2144 if (!foundAny) New->dropAttrs(); 2145} 2146 2147/// mergeParamDeclAttributes - Copy attributes from the old parameter 2148/// to the new one. 2149static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2150 const ParmVarDecl *oldDecl, 2151 Sema &S) { 2152 // C++11 [dcl.attr.depend]p2: 2153 // The first declaration of a function shall specify the 2154 // carries_dependency attribute for its declarator-id if any declaration 2155 // of the function specifies the carries_dependency attribute. 2156 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2157 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2158 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2159 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2160 // Find the first declaration of the parameter. 2161 // FIXME: Should we build redeclaration chains for function parameters? 2162 const FunctionDecl *FirstFD = 2163 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration(); 2164 const ParmVarDecl *FirstVD = 2165 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2166 S.Diag(FirstVD->getLocation(), 2167 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2168 } 2169 2170 if (!oldDecl->hasAttrs()) 2171 return; 2172 2173 bool foundAny = newDecl->hasAttrs(); 2174 2175 // Ensure that any moving of objects within the allocated map is 2176 // done before we process them. 2177 if (!foundAny) newDecl->setAttrs(AttrVec()); 2178 2179 for (specific_attr_iterator<InheritableParamAttr> 2180 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2181 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2182 if (!DeclHasAttr(newDecl, *i)) { 2183 InheritableAttr *newAttr = 2184 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2185 newAttr->setInherited(true); 2186 newDecl->addAttr(newAttr); 2187 foundAny = true; 2188 } 2189 } 2190 2191 if (!foundAny) newDecl->dropAttrs(); 2192} 2193 2194namespace { 2195 2196/// Used in MergeFunctionDecl to keep track of function parameters in 2197/// C. 2198struct GNUCompatibleParamWarning { 2199 ParmVarDecl *OldParm; 2200 ParmVarDecl *NewParm; 2201 QualType PromotedType; 2202}; 2203 2204} 2205 2206/// getSpecialMember - get the special member enum for a method. 2207Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2208 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2209 if (Ctor->isDefaultConstructor()) 2210 return Sema::CXXDefaultConstructor; 2211 2212 if (Ctor->isCopyConstructor()) 2213 return Sema::CXXCopyConstructor; 2214 2215 if (Ctor->isMoveConstructor()) 2216 return Sema::CXXMoveConstructor; 2217 } else if (isa<CXXDestructorDecl>(MD)) { 2218 return Sema::CXXDestructor; 2219 } else if (MD->isCopyAssignmentOperator()) { 2220 return Sema::CXXCopyAssignment; 2221 } else if (MD->isMoveAssignmentOperator()) { 2222 return Sema::CXXMoveAssignment; 2223 } 2224 2225 return Sema::CXXInvalid; 2226} 2227 2228/// canRedefineFunction - checks if a function can be redefined. Currently, 2229/// only extern inline functions can be redefined, and even then only in 2230/// GNU89 mode. 2231static bool canRedefineFunction(const FunctionDecl *FD, 2232 const LangOptions& LangOpts) { 2233 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2234 !LangOpts.CPlusPlus && 2235 FD->isInlineSpecified() && 2236 FD->getStorageClass() == SC_Extern); 2237} 2238 2239/// Is the given calling convention the ABI default for the given 2240/// declaration? 2241static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) { 2242 CallingConv ABIDefaultCC; 2243 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 2244 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic()); 2245 } else { 2246 // Free C function or a static method. 2247 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C); 2248 } 2249 return ABIDefaultCC == CC; 2250} 2251 2252template <typename T> 2253static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2254 const DeclContext *DC = Old->getDeclContext(); 2255 if (DC->isRecord()) 2256 return false; 2257 2258 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2259 if (OldLinkage == CXXLanguageLinkage && 2260 New->getDeclContext()->isExternCContext()) 2261 return true; 2262 if (OldLinkage == CLanguageLinkage && 2263 New->getDeclContext()->isExternCXXContext()) 2264 return true; 2265 return false; 2266} 2267 2268/// MergeFunctionDecl - We just parsed a function 'New' from 2269/// declarator D which has the same name and scope as a previous 2270/// declaration 'Old'. Figure out how to resolve this situation, 2271/// merging decls or emitting diagnostics as appropriate. 2272/// 2273/// In C++, New and Old must be declarations that are not 2274/// overloaded. Use IsOverload to determine whether New and Old are 2275/// overloaded, and to select the Old declaration that New should be 2276/// merged with. 2277/// 2278/// Returns true if there was an error, false otherwise. 2279bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 2280 // Verify the old decl was also a function. 2281 FunctionDecl *Old = 0; 2282 if (FunctionTemplateDecl *OldFunctionTemplate 2283 = dyn_cast<FunctionTemplateDecl>(OldD)) 2284 Old = OldFunctionTemplate->getTemplatedDecl(); 2285 else 2286 Old = dyn_cast<FunctionDecl>(OldD); 2287 if (!Old) { 2288 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2289 if (New->getFriendObjectKind()) { 2290 Diag(New->getLocation(), diag::err_using_decl_friend); 2291 Diag(Shadow->getTargetDecl()->getLocation(), 2292 diag::note_using_decl_target); 2293 Diag(Shadow->getUsingDecl()->getLocation(), 2294 diag::note_using_decl) << 0; 2295 return true; 2296 } 2297 2298 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2299 Diag(Shadow->getTargetDecl()->getLocation(), 2300 diag::note_using_decl_target); 2301 Diag(Shadow->getUsingDecl()->getLocation(), 2302 diag::note_using_decl) << 0; 2303 return true; 2304 } 2305 2306 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2307 << New->getDeclName(); 2308 Diag(OldD->getLocation(), diag::note_previous_definition); 2309 return true; 2310 } 2311 2312 // Determine whether the previous declaration was a definition, 2313 // implicit declaration, or a declaration. 2314 diag::kind PrevDiag; 2315 if (Old->isThisDeclarationADefinition()) 2316 PrevDiag = diag::note_previous_definition; 2317 else if (Old->isImplicit()) 2318 PrevDiag = diag::note_previous_implicit_declaration; 2319 else 2320 PrevDiag = diag::note_previous_declaration; 2321 2322 QualType OldQType = Context.getCanonicalType(Old->getType()); 2323 QualType NewQType = Context.getCanonicalType(New->getType()); 2324 2325 // Don't complain about this if we're in GNU89 mode and the old function 2326 // is an extern inline function. 2327 // Don't complain about specializations. They are not supposed to have 2328 // storage classes. 2329 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2330 New->getStorageClass() == SC_Static && 2331 Old->hasExternalLinkage() && 2332 !New->getTemplateSpecializationInfo() && 2333 !canRedefineFunction(Old, getLangOpts())) { 2334 if (getLangOpts().MicrosoftExt) { 2335 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2336 Diag(Old->getLocation(), PrevDiag); 2337 } else { 2338 Diag(New->getLocation(), diag::err_static_non_static) << New; 2339 Diag(Old->getLocation(), PrevDiag); 2340 return true; 2341 } 2342 } 2343 2344 // If a function is first declared with a calling convention, but is 2345 // later declared or defined without one, the second decl assumes the 2346 // calling convention of the first. 2347 // 2348 // It's OK if a function is first declared without a calling convention, 2349 // but is later declared or defined with the default calling convention. 2350 // 2351 // For the new decl, we have to look at the NON-canonical type to tell the 2352 // difference between a function that really doesn't have a calling 2353 // convention and one that is declared cdecl. That's because in 2354 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 2355 // because it is the default calling convention. 2356 // 2357 // Note also that we DO NOT return at this point, because we still have 2358 // other tests to run. 2359 const FunctionType *OldType = cast<FunctionType>(OldQType); 2360 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2361 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2362 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2363 bool RequiresAdjustment = false; 2364 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) { 2365 // Fast path: nothing to do. 2366 2367 // Inherit the CC from the previous declaration if it was specified 2368 // there but not here. 2369 } else if (NewTypeInfo.getCC() == CC_Default) { 2370 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2371 RequiresAdjustment = true; 2372 2373 // Don't complain about mismatches when the default CC is 2374 // effectively the same as the explict one. Only Old decl contains correct 2375 // information about storage class of CXXMethod. 2376 } else if (OldTypeInfo.getCC() == CC_Default && 2377 isABIDefaultCC(*this, NewTypeInfo.getCC(), Old)) { 2378 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2379 RequiresAdjustment = true; 2380 2381 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2382 NewTypeInfo.getCC())) { 2383 // Calling conventions really aren't compatible, so complain. 2384 Diag(New->getLocation(), diag::err_cconv_change) 2385 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2386 << (OldTypeInfo.getCC() == CC_Default) 2387 << (OldTypeInfo.getCC() == CC_Default ? "" : 2388 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2389 Diag(Old->getLocation(), diag::note_previous_declaration); 2390 return true; 2391 } 2392 2393 // FIXME: diagnose the other way around? 2394 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2395 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2396 RequiresAdjustment = true; 2397 } 2398 2399 // Merge regparm attribute. 2400 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2401 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2402 if (NewTypeInfo.getHasRegParm()) { 2403 Diag(New->getLocation(), diag::err_regparm_mismatch) 2404 << NewType->getRegParmType() 2405 << OldType->getRegParmType(); 2406 Diag(Old->getLocation(), diag::note_previous_declaration); 2407 return true; 2408 } 2409 2410 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2411 RequiresAdjustment = true; 2412 } 2413 2414 // Merge ns_returns_retained attribute. 2415 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2416 if (NewTypeInfo.getProducesResult()) { 2417 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2418 Diag(Old->getLocation(), diag::note_previous_declaration); 2419 return true; 2420 } 2421 2422 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2423 RequiresAdjustment = true; 2424 } 2425 2426 if (RequiresAdjustment) { 2427 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2428 New->setType(QualType(NewType, 0)); 2429 NewQType = Context.getCanonicalType(New->getType()); 2430 } 2431 2432 // If this redeclaration makes the function inline, we may need to add it to 2433 // UndefinedButUsed. 2434 if (!Old->isInlined() && New->isInlined() && 2435 !New->hasAttr<GNUInlineAttr>() && 2436 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2437 Old->isUsed(false) && 2438 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2439 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2440 SourceLocation())); 2441 2442 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2443 // about it. 2444 if (New->hasAttr<GNUInlineAttr>() && 2445 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2446 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2447 } 2448 2449 if (getLangOpts().CPlusPlus) { 2450 // (C++98 13.1p2): 2451 // Certain function declarations cannot be overloaded: 2452 // -- Function declarations that differ only in the return type 2453 // cannot be overloaded. 2454 QualType OldReturnType = OldType->getResultType(); 2455 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2456 QualType ResQT; 2457 if (OldReturnType != NewReturnType) { 2458 if (NewReturnType->isObjCObjectPointerType() 2459 && OldReturnType->isObjCObjectPointerType()) 2460 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2461 if (ResQT.isNull()) { 2462 if (New->isCXXClassMember() && New->isOutOfLine()) 2463 Diag(New->getLocation(), 2464 diag::err_member_def_does_not_match_ret_type) << New; 2465 else 2466 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2467 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2468 return true; 2469 } 2470 else 2471 NewQType = ResQT; 2472 } 2473 2474 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2475 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2476 if (OldMethod && NewMethod) { 2477 // Preserve triviality. 2478 NewMethod->setTrivial(OldMethod->isTrivial()); 2479 2480 // MSVC allows explicit template specialization at class scope: 2481 // 2 CXMethodDecls referring to the same function will be injected. 2482 // We don't want a redeclartion error. 2483 bool IsClassScopeExplicitSpecialization = 2484 OldMethod->isFunctionTemplateSpecialization() && 2485 NewMethod->isFunctionTemplateSpecialization(); 2486 bool isFriend = NewMethod->getFriendObjectKind(); 2487 2488 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2489 !IsClassScopeExplicitSpecialization) { 2490 // -- Member function declarations with the same name and the 2491 // same parameter types cannot be overloaded if any of them 2492 // is a static member function declaration. 2493 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2494 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2495 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2496 return true; 2497 } 2498 2499 // C++ [class.mem]p1: 2500 // [...] A member shall not be declared twice in the 2501 // member-specification, except that a nested class or member 2502 // class template can be declared and then later defined. 2503 if (ActiveTemplateInstantiations.empty()) { 2504 unsigned NewDiag; 2505 if (isa<CXXConstructorDecl>(OldMethod)) 2506 NewDiag = diag::err_constructor_redeclared; 2507 else if (isa<CXXDestructorDecl>(NewMethod)) 2508 NewDiag = diag::err_destructor_redeclared; 2509 else if (isa<CXXConversionDecl>(NewMethod)) 2510 NewDiag = diag::err_conv_function_redeclared; 2511 else 2512 NewDiag = diag::err_member_redeclared; 2513 2514 Diag(New->getLocation(), NewDiag); 2515 } else { 2516 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2517 << New << New->getType(); 2518 } 2519 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2520 2521 // Complain if this is an explicit declaration of a special 2522 // member that was initially declared implicitly. 2523 // 2524 // As an exception, it's okay to befriend such methods in order 2525 // to permit the implicit constructor/destructor/operator calls. 2526 } else if (OldMethod->isImplicit()) { 2527 if (isFriend) { 2528 NewMethod->setImplicit(); 2529 } else { 2530 Diag(NewMethod->getLocation(), 2531 diag::err_definition_of_implicitly_declared_member) 2532 << New << getSpecialMember(OldMethod); 2533 return true; 2534 } 2535 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2536 Diag(NewMethod->getLocation(), 2537 diag::err_definition_of_explicitly_defaulted_member) 2538 << getSpecialMember(OldMethod); 2539 return true; 2540 } 2541 } 2542 2543 // C++11 [dcl.attr.noreturn]p1: 2544 // The first declaration of a function shall specify the noreturn 2545 // attribute if any declaration of that function specifies the noreturn 2546 // attribute. 2547 if (New->hasAttr<CXX11NoReturnAttr>() && 2548 !Old->hasAttr<CXX11NoReturnAttr>()) { 2549 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2550 diag::err_noreturn_missing_on_first_decl); 2551 Diag(Old->getFirstDeclaration()->getLocation(), 2552 diag::note_noreturn_missing_first_decl); 2553 } 2554 2555 // C++11 [dcl.attr.depend]p2: 2556 // The first declaration of a function shall specify the 2557 // carries_dependency attribute for its declarator-id if any declaration 2558 // of the function specifies the carries_dependency attribute. 2559 if (New->hasAttr<CarriesDependencyAttr>() && 2560 !Old->hasAttr<CarriesDependencyAttr>()) { 2561 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2562 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2563 Diag(Old->getFirstDeclaration()->getLocation(), 2564 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2565 } 2566 2567 // (C++98 8.3.5p3): 2568 // All declarations for a function shall agree exactly in both the 2569 // return type and the parameter-type-list. 2570 // We also want to respect all the extended bits except noreturn. 2571 2572 // noreturn should now match unless the old type info didn't have it. 2573 QualType OldQTypeForComparison = OldQType; 2574 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2575 assert(OldQType == QualType(OldType, 0)); 2576 const FunctionType *OldTypeForComparison 2577 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2578 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2579 assert(OldQTypeForComparison.isCanonical()); 2580 } 2581 2582 if (haveIncompatibleLanguageLinkages(Old, New)) { 2583 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2584 Diag(Old->getLocation(), PrevDiag); 2585 return true; 2586 } 2587 2588 if (OldQTypeForComparison == NewQType) 2589 return MergeCompatibleFunctionDecls(New, Old, S); 2590 2591 // Fall through for conflicting redeclarations and redefinitions. 2592 } 2593 2594 // C: Function types need to be compatible, not identical. This handles 2595 // duplicate function decls like "void f(int); void f(enum X);" properly. 2596 if (!getLangOpts().CPlusPlus && 2597 Context.typesAreCompatible(OldQType, NewQType)) { 2598 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2599 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2600 const FunctionProtoType *OldProto = 0; 2601 if (isa<FunctionNoProtoType>(NewFuncType) && 2602 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2603 // The old declaration provided a function prototype, but the 2604 // new declaration does not. Merge in the prototype. 2605 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2606 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2607 OldProto->arg_type_end()); 2608 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2609 ParamTypes, 2610 OldProto->getExtProtoInfo()); 2611 New->setType(NewQType); 2612 New->setHasInheritedPrototype(); 2613 2614 // Synthesize a parameter for each argument type. 2615 SmallVector<ParmVarDecl*, 16> Params; 2616 for (FunctionProtoType::arg_type_iterator 2617 ParamType = OldProto->arg_type_begin(), 2618 ParamEnd = OldProto->arg_type_end(); 2619 ParamType != ParamEnd; ++ParamType) { 2620 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2621 SourceLocation(), 2622 SourceLocation(), 0, 2623 *ParamType, /*TInfo=*/0, 2624 SC_None, 2625 0); 2626 Param->setScopeInfo(0, Params.size()); 2627 Param->setImplicit(); 2628 Params.push_back(Param); 2629 } 2630 2631 New->setParams(Params); 2632 } 2633 2634 return MergeCompatibleFunctionDecls(New, Old, S); 2635 } 2636 2637 // GNU C permits a K&R definition to follow a prototype declaration 2638 // if the declared types of the parameters in the K&R definition 2639 // match the types in the prototype declaration, even when the 2640 // promoted types of the parameters from the K&R definition differ 2641 // from the types in the prototype. GCC then keeps the types from 2642 // the prototype. 2643 // 2644 // If a variadic prototype is followed by a non-variadic K&R definition, 2645 // the K&R definition becomes variadic. This is sort of an edge case, but 2646 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2647 // C99 6.9.1p8. 2648 if (!getLangOpts().CPlusPlus && 2649 Old->hasPrototype() && !New->hasPrototype() && 2650 New->getType()->getAs<FunctionProtoType>() && 2651 Old->getNumParams() == New->getNumParams()) { 2652 SmallVector<QualType, 16> ArgTypes; 2653 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2654 const FunctionProtoType *OldProto 2655 = Old->getType()->getAs<FunctionProtoType>(); 2656 const FunctionProtoType *NewProto 2657 = New->getType()->getAs<FunctionProtoType>(); 2658 2659 // Determine whether this is the GNU C extension. 2660 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2661 NewProto->getResultType()); 2662 bool LooseCompatible = !MergedReturn.isNull(); 2663 for (unsigned Idx = 0, End = Old->getNumParams(); 2664 LooseCompatible && Idx != End; ++Idx) { 2665 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2666 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2667 if (Context.typesAreCompatible(OldParm->getType(), 2668 NewProto->getArgType(Idx))) { 2669 ArgTypes.push_back(NewParm->getType()); 2670 } else if (Context.typesAreCompatible(OldParm->getType(), 2671 NewParm->getType(), 2672 /*CompareUnqualified=*/true)) { 2673 GNUCompatibleParamWarning Warn 2674 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2675 Warnings.push_back(Warn); 2676 ArgTypes.push_back(NewParm->getType()); 2677 } else 2678 LooseCompatible = false; 2679 } 2680 2681 if (LooseCompatible) { 2682 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2683 Diag(Warnings[Warn].NewParm->getLocation(), 2684 diag::ext_param_promoted_not_compatible_with_prototype) 2685 << Warnings[Warn].PromotedType 2686 << Warnings[Warn].OldParm->getType(); 2687 if (Warnings[Warn].OldParm->getLocation().isValid()) 2688 Diag(Warnings[Warn].OldParm->getLocation(), 2689 diag::note_previous_declaration); 2690 } 2691 2692 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2693 OldProto->getExtProtoInfo())); 2694 return MergeCompatibleFunctionDecls(New, Old, S); 2695 } 2696 2697 // Fall through to diagnose conflicting types. 2698 } 2699 2700 // A function that has already been declared has been redeclared or defined 2701 // with a different type- show appropriate diagnostic 2702 if (unsigned BuiltinID = Old->getBuiltinID()) { 2703 // The user has declared a builtin function with an incompatible 2704 // signature. 2705 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2706 // The function the user is redeclaring is a library-defined 2707 // function like 'malloc' or 'printf'. Warn about the 2708 // redeclaration, then pretend that we don't know about this 2709 // library built-in. 2710 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2711 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2712 << Old << Old->getType(); 2713 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2714 Old->setInvalidDecl(); 2715 return false; 2716 } 2717 2718 PrevDiag = diag::note_previous_builtin_declaration; 2719 } 2720 2721 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2722 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2723 return true; 2724} 2725 2726/// \brief Completes the merge of two function declarations that are 2727/// known to be compatible. 2728/// 2729/// This routine handles the merging of attributes and other 2730/// properties of function declarations form the old declaration to 2731/// the new declaration, once we know that New is in fact a 2732/// redeclaration of Old. 2733/// 2734/// \returns false 2735bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2736 Scope *S) { 2737 // Merge the attributes 2738 mergeDeclAttributes(New, Old); 2739 2740 // Merge "pure" flag. 2741 if (Old->isPure()) 2742 New->setPure(); 2743 2744 // Merge "used" flag. 2745 if (Old->isUsed(false)) 2746 New->setUsed(); 2747 2748 // Merge attributes from the parameters. These can mismatch with K&R 2749 // declarations. 2750 if (New->getNumParams() == Old->getNumParams()) 2751 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2752 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2753 *this); 2754 2755 if (getLangOpts().CPlusPlus) 2756 return MergeCXXFunctionDecl(New, Old, S); 2757 2758 // Merge the function types so the we get the composite types for the return 2759 // and argument types. 2760 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2761 if (!Merged.isNull()) 2762 New->setType(Merged); 2763 2764 return false; 2765} 2766 2767 2768void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2769 ObjCMethodDecl *oldMethod) { 2770 2771 // Merge the attributes, including deprecated/unavailable 2772 mergeDeclAttributes(newMethod, oldMethod, AMK_Override); 2773 2774 // Merge attributes from the parameters. 2775 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2776 oe = oldMethod->param_end(); 2777 for (ObjCMethodDecl::param_iterator 2778 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2779 ni != ne && oi != oe; ++ni, ++oi) 2780 mergeParamDeclAttributes(*ni, *oi, *this); 2781 2782 CheckObjCMethodOverride(newMethod, oldMethod); 2783} 2784 2785/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2786/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2787/// emitting diagnostics as appropriate. 2788/// 2789/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2790/// to here in AddInitializerToDecl. We can't check them before the initializer 2791/// is attached. 2792void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool OldWasHidden) { 2793 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2794 return; 2795 2796 QualType MergedT; 2797 if (getLangOpts().CPlusPlus) { 2798 AutoType *AT = New->getType()->getContainedAutoType(); 2799 if (AT && !AT->isDeduced()) { 2800 // We don't know what the new type is until the initializer is attached. 2801 return; 2802 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2803 // These could still be something that needs exception specs checked. 2804 return MergeVarDeclExceptionSpecs(New, Old); 2805 } 2806 // C++ [basic.link]p10: 2807 // [...] the types specified by all declarations referring to a given 2808 // object or function shall be identical, except that declarations for an 2809 // array object can specify array types that differ by the presence or 2810 // absence of a major array bound (8.3.4). 2811 else if (Old->getType()->isIncompleteArrayType() && 2812 New->getType()->isArrayType()) { 2813 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2814 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2815 if (Context.hasSameType(OldArray->getElementType(), 2816 NewArray->getElementType())) 2817 MergedT = New->getType(); 2818 } else if (Old->getType()->isArrayType() && 2819 New->getType()->isIncompleteArrayType()) { 2820 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2821 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2822 if (Context.hasSameType(OldArray->getElementType(), 2823 NewArray->getElementType())) 2824 MergedT = Old->getType(); 2825 } else if (New->getType()->isObjCObjectPointerType() 2826 && Old->getType()->isObjCObjectPointerType()) { 2827 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2828 Old->getType()); 2829 } 2830 } else { 2831 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2832 } 2833 if (MergedT.isNull()) { 2834 Diag(New->getLocation(), diag::err_redefinition_different_type) 2835 << New->getDeclName() << New->getType() << Old->getType(); 2836 Diag(Old->getLocation(), diag::note_previous_definition); 2837 return New->setInvalidDecl(); 2838 } 2839 2840 // Don't actually update the type on the new declaration if the old 2841 // declaration was a extern declaration in a different scope. 2842 if (!OldWasHidden) 2843 New->setType(MergedT); 2844} 2845 2846/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2847/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2848/// situation, merging decls or emitting diagnostics as appropriate. 2849/// 2850/// Tentative definition rules (C99 6.9.2p2) are checked by 2851/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2852/// definitions here, since the initializer hasn't been attached. 2853/// 2854void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous, 2855 bool PreviousWasHidden) { 2856 // If the new decl is already invalid, don't do any other checking. 2857 if (New->isInvalidDecl()) 2858 return; 2859 2860 // Verify the old decl was also a variable. 2861 VarDecl *Old = 0; 2862 if (!Previous.isSingleResult() || 2863 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2864 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2865 << New->getDeclName(); 2866 Diag(Previous.getRepresentativeDecl()->getLocation(), 2867 diag::note_previous_definition); 2868 return New->setInvalidDecl(); 2869 } 2870 2871 // C++ [class.mem]p1: 2872 // A member shall not be declared twice in the member-specification [...] 2873 // 2874 // Here, we need only consider static data members. 2875 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2876 Diag(New->getLocation(), diag::err_duplicate_member) 2877 << New->getIdentifier(); 2878 Diag(Old->getLocation(), diag::note_previous_declaration); 2879 New->setInvalidDecl(); 2880 } 2881 2882 mergeDeclAttributes(New, Old); 2883 // Warn if an already-declared variable is made a weak_import in a subsequent 2884 // declaration 2885 if (New->getAttr<WeakImportAttr>() && 2886 Old->getStorageClass() == SC_None && 2887 !Old->getAttr<WeakImportAttr>()) { 2888 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2889 Diag(Old->getLocation(), diag::note_previous_definition); 2890 // Remove weak_import attribute on new declaration. 2891 New->dropAttr<WeakImportAttr>(); 2892 } 2893 2894 // Merge the types. 2895 MergeVarDeclTypes(New, Old, PreviousWasHidden); 2896 if (New->isInvalidDecl()) 2897 return; 2898 2899 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2900 if (New->getStorageClass() == SC_Static && 2901 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2902 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2903 Diag(Old->getLocation(), diag::note_previous_definition); 2904 return New->setInvalidDecl(); 2905 } 2906 // C99 6.2.2p4: 2907 // For an identifier declared with the storage-class specifier 2908 // extern in a scope in which a prior declaration of that 2909 // identifier is visible,23) if the prior declaration specifies 2910 // internal or external linkage, the linkage of the identifier at 2911 // the later declaration is the same as the linkage specified at 2912 // the prior declaration. If no prior declaration is visible, or 2913 // if the prior declaration specifies no linkage, then the 2914 // identifier has external linkage. 2915 if (New->hasExternalStorage() && Old->hasLinkage()) 2916 /* Okay */; 2917 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 2918 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 2919 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2920 Diag(Old->getLocation(), diag::note_previous_definition); 2921 return New->setInvalidDecl(); 2922 } 2923 2924 // Check if extern is followed by non-extern and vice-versa. 2925 if (New->hasExternalStorage() && 2926 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2927 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2928 Diag(Old->getLocation(), diag::note_previous_definition); 2929 return New->setInvalidDecl(); 2930 } 2931 if (Old->hasLinkage() && New->isLocalVarDecl() && 2932 !New->hasExternalStorage()) { 2933 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2934 Diag(Old->getLocation(), diag::note_previous_definition); 2935 return New->setInvalidDecl(); 2936 } 2937 2938 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2939 2940 // FIXME: The test for external storage here seems wrong? We still 2941 // need to check for mismatches. 2942 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2943 // Don't complain about out-of-line definitions of static members. 2944 !(Old->getLexicalDeclContext()->isRecord() && 2945 !New->getLexicalDeclContext()->isRecord())) { 2946 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2947 Diag(Old->getLocation(), diag::note_previous_definition); 2948 return New->setInvalidDecl(); 2949 } 2950 2951 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2952 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2953 Diag(Old->getLocation(), diag::note_previous_definition); 2954 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2955 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2956 Diag(Old->getLocation(), diag::note_previous_definition); 2957 } 2958 2959 // C++ doesn't have tentative definitions, so go right ahead and check here. 2960 const VarDecl *Def; 2961 if (getLangOpts().CPlusPlus && 2962 New->isThisDeclarationADefinition() == VarDecl::Definition && 2963 (Def = Old->getDefinition())) { 2964 Diag(New->getLocation(), diag::err_redefinition) 2965 << New->getDeclName(); 2966 Diag(Def->getLocation(), diag::note_previous_definition); 2967 New->setInvalidDecl(); 2968 return; 2969 } 2970 2971 if (haveIncompatibleLanguageLinkages(Old, New)) { 2972 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2973 Diag(Old->getLocation(), diag::note_previous_definition); 2974 New->setInvalidDecl(); 2975 return; 2976 } 2977 2978 // Merge "used" flag. 2979 if (Old->isUsed(false)) 2980 New->setUsed(); 2981 2982 // Keep a chain of previous declarations. 2983 New->setPreviousDeclaration(Old); 2984 2985 // Inherit access appropriately. 2986 New->setAccess(Old->getAccess()); 2987} 2988 2989/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2990/// no declarator (e.g. "struct foo;") is parsed. 2991Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2992 DeclSpec &DS) { 2993 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 2994} 2995 2996/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2997/// no declarator (e.g. "struct foo;") is parsed. It also accepts template 2998/// parameters to cope with template friend declarations. 2999Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3000 DeclSpec &DS, 3001 MultiTemplateParamsArg TemplateParams, 3002 bool IsExplicitInstantiation) { 3003 Decl *TagD = 0; 3004 TagDecl *Tag = 0; 3005 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3006 DS.getTypeSpecType() == DeclSpec::TST_struct || 3007 DS.getTypeSpecType() == DeclSpec::TST_interface || 3008 DS.getTypeSpecType() == DeclSpec::TST_union || 3009 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3010 TagD = DS.getRepAsDecl(); 3011 3012 if (!TagD) // We probably had an error 3013 return 0; 3014 3015 // Note that the above type specs guarantee that the 3016 // type rep is a Decl, whereas in many of the others 3017 // it's a Type. 3018 if (isa<TagDecl>(TagD)) 3019 Tag = cast<TagDecl>(TagD); 3020 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3021 Tag = CTD->getTemplatedDecl(); 3022 } 3023 3024 if (Tag) { 3025 getASTContext().addUnnamedTag(Tag); 3026 Tag->setFreeStanding(); 3027 if (Tag->isInvalidDecl()) 3028 return Tag; 3029 } 3030 3031 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3032 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3033 // or incomplete types shall not be restrict-qualified." 3034 if (TypeQuals & DeclSpec::TQ_restrict) 3035 Diag(DS.getRestrictSpecLoc(), 3036 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3037 << DS.getSourceRange(); 3038 } 3039 3040 if (DS.isConstexprSpecified()) { 3041 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3042 // and definitions of functions and variables. 3043 if (Tag) 3044 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3045 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3046 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3047 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3048 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3049 else 3050 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3051 // Don't emit warnings after this error. 3052 return TagD; 3053 } 3054 3055 DiagnoseFunctionSpecifiers(DS); 3056 3057 if (DS.isFriendSpecified()) { 3058 // If we're dealing with a decl but not a TagDecl, assume that 3059 // whatever routines created it handled the friendship aspect. 3060 if (TagD && !Tag) 3061 return 0; 3062 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3063 } 3064 3065 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3066 bool IsExplicitSpecialization = 3067 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3068 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3069 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3070 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3071 // nested-name-specifier unless it is an explicit instantiation 3072 // or an explicit specialization. 3073 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3074 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3075 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3076 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3077 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3078 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3079 << SS.getRange(); 3080 return 0; 3081 } 3082 3083 // Track whether this decl-specifier declares anything. 3084 bool DeclaresAnything = true; 3085 3086 // Handle anonymous struct definitions. 3087 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3088 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3089 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3090 if (getLangOpts().CPlusPlus || 3091 Record->getDeclContext()->isRecord()) 3092 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3093 3094 DeclaresAnything = false; 3095 } 3096 } 3097 3098 // Check for Microsoft C extension: anonymous struct member. 3099 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3100 CurContext->isRecord() && 3101 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3102 // Handle 2 kinds of anonymous struct: 3103 // struct STRUCT; 3104 // and 3105 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3106 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3107 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3108 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3109 DS.getRepAsType().get()->isStructureType())) { 3110 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3111 << DS.getSourceRange(); 3112 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3113 } 3114 } 3115 3116 // Skip all the checks below if we have a type error. 3117 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3118 (TagD && TagD->isInvalidDecl())) 3119 return TagD; 3120 3121 if (getLangOpts().CPlusPlus && 3122 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3123 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3124 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3125 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3126 DeclaresAnything = false; 3127 3128 if (!DS.isMissingDeclaratorOk()) { 3129 // Customize diagnostic for a typedef missing a name. 3130 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3131 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3132 << DS.getSourceRange(); 3133 else 3134 DeclaresAnything = false; 3135 } 3136 3137 if (DS.isModulePrivateSpecified() && 3138 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3139 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3140 << Tag->getTagKind() 3141 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3142 3143 ActOnDocumentableDecl(TagD); 3144 3145 // C 6.7/2: 3146 // A declaration [...] shall declare at least a declarator [...], a tag, 3147 // or the members of an enumeration. 3148 // C++ [dcl.dcl]p3: 3149 // [If there are no declarators], and except for the declaration of an 3150 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3151 // names into the program, or shall redeclare a name introduced by a 3152 // previous declaration. 3153 if (!DeclaresAnything) { 3154 // In C, we allow this as a (popular) extension / bug. Don't bother 3155 // producing further diagnostics for redundant qualifiers after this. 3156 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3157 return TagD; 3158 } 3159 3160 // C++ [dcl.stc]p1: 3161 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3162 // init-declarator-list of the declaration shall not be empty. 3163 // C++ [dcl.fct.spec]p1: 3164 // If a cv-qualifier appears in a decl-specifier-seq, the 3165 // init-declarator-list of the declaration shall not be empty. 3166 // 3167 // Spurious qualifiers here appear to be valid in C. 3168 unsigned DiagID = diag::warn_standalone_specifier; 3169 if (getLangOpts().CPlusPlus) 3170 DiagID = diag::ext_standalone_specifier; 3171 3172 // Note that a linkage-specification sets a storage class, but 3173 // 'extern "C" struct foo;' is actually valid and not theoretically 3174 // useless. 3175 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3176 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3177 Diag(DS.getStorageClassSpecLoc(), DiagID) 3178 << DeclSpec::getSpecifierName(SCS); 3179 3180 if (DS.isThreadSpecified()) 3181 Diag(DS.getThreadSpecLoc(), DiagID) << "__thread"; 3182 if (DS.getTypeQualifiers()) { 3183 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3184 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3185 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3186 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3187 // Restrict is covered above. 3188 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3189 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3190 } 3191 3192 // Warn about ignored type attributes, for example: 3193 // __attribute__((aligned)) struct A; 3194 // Attributes should be placed after tag to apply to type declaration. 3195 if (!DS.getAttributes().empty()) { 3196 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3197 if (TypeSpecType == DeclSpec::TST_class || 3198 TypeSpecType == DeclSpec::TST_struct || 3199 TypeSpecType == DeclSpec::TST_interface || 3200 TypeSpecType == DeclSpec::TST_union || 3201 TypeSpecType == DeclSpec::TST_enum) { 3202 AttributeList* attrs = DS.getAttributes().getList(); 3203 while (attrs) { 3204 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3205 << attrs->getName() 3206 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3207 TypeSpecType == DeclSpec::TST_struct ? 1 : 3208 TypeSpecType == DeclSpec::TST_union ? 2 : 3209 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3210 attrs = attrs->getNext(); 3211 } 3212 } 3213 } 3214 3215 return TagD; 3216} 3217 3218/// We are trying to inject an anonymous member into the given scope; 3219/// check if there's an existing declaration that can't be overloaded. 3220/// 3221/// \return true if this is a forbidden redeclaration 3222static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3223 Scope *S, 3224 DeclContext *Owner, 3225 DeclarationName Name, 3226 SourceLocation NameLoc, 3227 unsigned diagnostic) { 3228 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3229 Sema::ForRedeclaration); 3230 if (!SemaRef.LookupName(R, S)) return false; 3231 3232 if (R.getAsSingle<TagDecl>()) 3233 return false; 3234 3235 // Pick a representative declaration. 3236 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3237 assert(PrevDecl && "Expected a non-null Decl"); 3238 3239 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3240 return false; 3241 3242 SemaRef.Diag(NameLoc, diagnostic) << Name; 3243 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3244 3245 return true; 3246} 3247 3248/// InjectAnonymousStructOrUnionMembers - Inject the members of the 3249/// anonymous struct or union AnonRecord into the owning context Owner 3250/// and scope S. This routine will be invoked just after we realize 3251/// that an unnamed union or struct is actually an anonymous union or 3252/// struct, e.g., 3253/// 3254/// @code 3255/// union { 3256/// int i; 3257/// float f; 3258/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3259/// // f into the surrounding scope.x 3260/// @endcode 3261/// 3262/// This routine is recursive, injecting the names of nested anonymous 3263/// structs/unions into the owning context and scope as well. 3264static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3265 DeclContext *Owner, 3266 RecordDecl *AnonRecord, 3267 AccessSpecifier AS, 3268 SmallVector<NamedDecl*, 2> &Chaining, 3269 bool MSAnonStruct) { 3270 unsigned diagKind 3271 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3272 : diag::err_anonymous_struct_member_redecl; 3273 3274 bool Invalid = false; 3275 3276 // Look every FieldDecl and IndirectFieldDecl with a name. 3277 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3278 DEnd = AnonRecord->decls_end(); 3279 D != DEnd; ++D) { 3280 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3281 cast<NamedDecl>(*D)->getDeclName()) { 3282 ValueDecl *VD = cast<ValueDecl>(*D); 3283 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3284 VD->getLocation(), diagKind)) { 3285 // C++ [class.union]p2: 3286 // The names of the members of an anonymous union shall be 3287 // distinct from the names of any other entity in the 3288 // scope in which the anonymous union is declared. 3289 Invalid = true; 3290 } else { 3291 // C++ [class.union]p2: 3292 // For the purpose of name lookup, after the anonymous union 3293 // definition, the members of the anonymous union are 3294 // considered to have been defined in the scope in which the 3295 // anonymous union is declared. 3296 unsigned OldChainingSize = Chaining.size(); 3297 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3298 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3299 PE = IF->chain_end(); PI != PE; ++PI) 3300 Chaining.push_back(*PI); 3301 else 3302 Chaining.push_back(VD); 3303 3304 assert(Chaining.size() >= 2); 3305 NamedDecl **NamedChain = 3306 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3307 for (unsigned i = 0; i < Chaining.size(); i++) 3308 NamedChain[i] = Chaining[i]; 3309 3310 IndirectFieldDecl* IndirectField = 3311 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3312 VD->getIdentifier(), VD->getType(), 3313 NamedChain, Chaining.size()); 3314 3315 IndirectField->setAccess(AS); 3316 IndirectField->setImplicit(); 3317 SemaRef.PushOnScopeChains(IndirectField, S); 3318 3319 // That includes picking up the appropriate access specifier. 3320 if (AS != AS_none) IndirectField->setAccess(AS); 3321 3322 Chaining.resize(OldChainingSize); 3323 } 3324 } 3325 } 3326 3327 return Invalid; 3328} 3329 3330/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3331/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3332/// illegal input values are mapped to SC_None. 3333static StorageClass 3334StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3335 switch (StorageClassSpec) { 3336 case DeclSpec::SCS_unspecified: return SC_None; 3337 case DeclSpec::SCS_extern: return SC_Extern; 3338 case DeclSpec::SCS_static: return SC_Static; 3339 case DeclSpec::SCS_auto: return SC_Auto; 3340 case DeclSpec::SCS_register: return SC_Register; 3341 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3342 // Illegal SCSs map to None: error reporting is up to the caller. 3343 case DeclSpec::SCS_mutable: // Fall through. 3344 case DeclSpec::SCS_typedef: return SC_None; 3345 } 3346 llvm_unreachable("unknown storage class specifier"); 3347} 3348 3349/// BuildAnonymousStructOrUnion - Handle the declaration of an 3350/// anonymous structure or union. Anonymous unions are a C++ feature 3351/// (C++ [class.union]) and a C11 feature; anonymous structures 3352/// are a C11 feature and GNU C++ extension. 3353Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3354 AccessSpecifier AS, 3355 RecordDecl *Record) { 3356 DeclContext *Owner = Record->getDeclContext(); 3357 3358 // Diagnose whether this anonymous struct/union is an extension. 3359 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3360 Diag(Record->getLocation(), diag::ext_anonymous_union); 3361 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3362 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3363 else if (!Record->isUnion() && !getLangOpts().C11) 3364 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3365 3366 // C and C++ require different kinds of checks for anonymous 3367 // structs/unions. 3368 bool Invalid = false; 3369 if (getLangOpts().CPlusPlus) { 3370 const char* PrevSpec = 0; 3371 unsigned DiagID; 3372 if (Record->isUnion()) { 3373 // C++ [class.union]p6: 3374 // Anonymous unions declared in a named namespace or in the 3375 // global namespace shall be declared static. 3376 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3377 (isa<TranslationUnitDecl>(Owner) || 3378 (isa<NamespaceDecl>(Owner) && 3379 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3380 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3381 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3382 3383 // Recover by adding 'static'. 3384 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3385 PrevSpec, DiagID); 3386 } 3387 // C++ [class.union]p6: 3388 // A storage class is not allowed in a declaration of an 3389 // anonymous union in a class scope. 3390 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3391 isa<RecordDecl>(Owner)) { 3392 Diag(DS.getStorageClassSpecLoc(), 3393 diag::err_anonymous_union_with_storage_spec) 3394 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3395 3396 // Recover by removing the storage specifier. 3397 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3398 SourceLocation(), 3399 PrevSpec, DiagID); 3400 } 3401 } 3402 3403 // Ignore const/volatile/restrict qualifiers. 3404 if (DS.getTypeQualifiers()) { 3405 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3406 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3407 << Record->isUnion() << "const" 3408 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3409 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3410 Diag(DS.getVolatileSpecLoc(), 3411 diag::ext_anonymous_struct_union_qualified) 3412 << Record->isUnion() << "volatile" 3413 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3414 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3415 Diag(DS.getRestrictSpecLoc(), 3416 diag::ext_anonymous_struct_union_qualified) 3417 << Record->isUnion() << "restrict" 3418 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3419 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3420 Diag(DS.getAtomicSpecLoc(), 3421 diag::ext_anonymous_struct_union_qualified) 3422 << Record->isUnion() << "_Atomic" 3423 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3424 3425 DS.ClearTypeQualifiers(); 3426 } 3427 3428 // C++ [class.union]p2: 3429 // The member-specification of an anonymous union shall only 3430 // define non-static data members. [Note: nested types and 3431 // functions cannot be declared within an anonymous union. ] 3432 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3433 MemEnd = Record->decls_end(); 3434 Mem != MemEnd; ++Mem) { 3435 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3436 // C++ [class.union]p3: 3437 // An anonymous union shall not have private or protected 3438 // members (clause 11). 3439 assert(FD->getAccess() != AS_none); 3440 if (FD->getAccess() != AS_public) { 3441 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3442 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3443 Invalid = true; 3444 } 3445 3446 // C++ [class.union]p1 3447 // An object of a class with a non-trivial constructor, a non-trivial 3448 // copy constructor, a non-trivial destructor, or a non-trivial copy 3449 // assignment operator cannot be a member of a union, nor can an 3450 // array of such objects. 3451 if (CheckNontrivialField(FD)) 3452 Invalid = true; 3453 } else if ((*Mem)->isImplicit()) { 3454 // Any implicit members are fine. 3455 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3456 // This is a type that showed up in an 3457 // elaborated-type-specifier inside the anonymous struct or 3458 // union, but which actually declares a type outside of the 3459 // anonymous struct or union. It's okay. 3460 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3461 if (!MemRecord->isAnonymousStructOrUnion() && 3462 MemRecord->getDeclName()) { 3463 // Visual C++ allows type definition in anonymous struct or union. 3464 if (getLangOpts().MicrosoftExt) 3465 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3466 << (int)Record->isUnion(); 3467 else { 3468 // This is a nested type declaration. 3469 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3470 << (int)Record->isUnion(); 3471 Invalid = true; 3472 } 3473 } else { 3474 // This is an anonymous type definition within another anonymous type. 3475 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3476 // not part of standard C++. 3477 Diag(MemRecord->getLocation(), 3478 diag::ext_anonymous_record_with_anonymous_type) 3479 << (int)Record->isUnion(); 3480 } 3481 } else if (isa<AccessSpecDecl>(*Mem)) { 3482 // Any access specifier is fine. 3483 } else { 3484 // We have something that isn't a non-static data 3485 // member. Complain about it. 3486 unsigned DK = diag::err_anonymous_record_bad_member; 3487 if (isa<TypeDecl>(*Mem)) 3488 DK = diag::err_anonymous_record_with_type; 3489 else if (isa<FunctionDecl>(*Mem)) 3490 DK = diag::err_anonymous_record_with_function; 3491 else if (isa<VarDecl>(*Mem)) 3492 DK = diag::err_anonymous_record_with_static; 3493 3494 // Visual C++ allows type definition in anonymous struct or union. 3495 if (getLangOpts().MicrosoftExt && 3496 DK == diag::err_anonymous_record_with_type) 3497 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3498 << (int)Record->isUnion(); 3499 else { 3500 Diag((*Mem)->getLocation(), DK) 3501 << (int)Record->isUnion(); 3502 Invalid = true; 3503 } 3504 } 3505 } 3506 } 3507 3508 if (!Record->isUnion() && !Owner->isRecord()) { 3509 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3510 << (int)getLangOpts().CPlusPlus; 3511 Invalid = true; 3512 } 3513 3514 // Mock up a declarator. 3515 Declarator Dc(DS, Declarator::MemberContext); 3516 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3517 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3518 3519 // Create a declaration for this anonymous struct/union. 3520 NamedDecl *Anon = 0; 3521 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3522 Anon = FieldDecl::Create(Context, OwningClass, 3523 DS.getLocStart(), 3524 Record->getLocation(), 3525 /*IdentifierInfo=*/0, 3526 Context.getTypeDeclType(Record), 3527 TInfo, 3528 /*BitWidth=*/0, /*Mutable=*/false, 3529 /*InitStyle=*/ICIS_NoInit); 3530 Anon->setAccess(AS); 3531 if (getLangOpts().CPlusPlus) 3532 FieldCollector->Add(cast<FieldDecl>(Anon)); 3533 } else { 3534 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3535 assert(SCSpec != DeclSpec::SCS_typedef && 3536 "Parser allowed 'typedef' as storage class VarDecl."); 3537 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3538 if (SCSpec == DeclSpec::SCS_mutable) { 3539 // mutable can only appear on non-static class members, so it's always 3540 // an error here 3541 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3542 Invalid = true; 3543 SC = SC_None; 3544 } 3545 3546 Anon = VarDecl::Create(Context, Owner, 3547 DS.getLocStart(), 3548 Record->getLocation(), /*IdentifierInfo=*/0, 3549 Context.getTypeDeclType(Record), 3550 TInfo, SC); 3551 3552 // Default-initialize the implicit variable. This initialization will be 3553 // trivial in almost all cases, except if a union member has an in-class 3554 // initializer: 3555 // union { int n = 0; }; 3556 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3557 } 3558 Anon->setImplicit(); 3559 3560 // Add the anonymous struct/union object to the current 3561 // context. We'll be referencing this object when we refer to one of 3562 // its members. 3563 Owner->addDecl(Anon); 3564 3565 // Inject the members of the anonymous struct/union into the owning 3566 // context and into the identifier resolver chain for name lookup 3567 // purposes. 3568 SmallVector<NamedDecl*, 2> Chain; 3569 Chain.push_back(Anon); 3570 3571 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3572 Chain, false)) 3573 Invalid = true; 3574 3575 // Mark this as an anonymous struct/union type. Note that we do not 3576 // do this until after we have already checked and injected the 3577 // members of this anonymous struct/union type, because otherwise 3578 // the members could be injected twice: once by DeclContext when it 3579 // builds its lookup table, and once by 3580 // InjectAnonymousStructOrUnionMembers. 3581 Record->setAnonymousStructOrUnion(true); 3582 3583 if (Invalid) 3584 Anon->setInvalidDecl(); 3585 3586 return Anon; 3587} 3588 3589/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3590/// Microsoft C anonymous structure. 3591/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3592/// Example: 3593/// 3594/// struct A { int a; }; 3595/// struct B { struct A; int b; }; 3596/// 3597/// void foo() { 3598/// B var; 3599/// var.a = 3; 3600/// } 3601/// 3602Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3603 RecordDecl *Record) { 3604 3605 // If there is no Record, get the record via the typedef. 3606 if (!Record) 3607 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3608 3609 // Mock up a declarator. 3610 Declarator Dc(DS, Declarator::TypeNameContext); 3611 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3612 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3613 3614 // Create a declaration for this anonymous struct. 3615 NamedDecl* Anon = FieldDecl::Create(Context, 3616 cast<RecordDecl>(CurContext), 3617 DS.getLocStart(), 3618 DS.getLocStart(), 3619 /*IdentifierInfo=*/0, 3620 Context.getTypeDeclType(Record), 3621 TInfo, 3622 /*BitWidth=*/0, /*Mutable=*/false, 3623 /*InitStyle=*/ICIS_NoInit); 3624 Anon->setImplicit(); 3625 3626 // Add the anonymous struct object to the current context. 3627 CurContext->addDecl(Anon); 3628 3629 // Inject the members of the anonymous struct into the current 3630 // context and into the identifier resolver chain for name lookup 3631 // purposes. 3632 SmallVector<NamedDecl*, 2> Chain; 3633 Chain.push_back(Anon); 3634 3635 RecordDecl *RecordDef = Record->getDefinition(); 3636 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3637 RecordDef, AS_none, 3638 Chain, true)) 3639 Anon->setInvalidDecl(); 3640 3641 return Anon; 3642} 3643 3644/// GetNameForDeclarator - Determine the full declaration name for the 3645/// given Declarator. 3646DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3647 return GetNameFromUnqualifiedId(D.getName()); 3648} 3649 3650/// \brief Retrieves the declaration name from a parsed unqualified-id. 3651DeclarationNameInfo 3652Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3653 DeclarationNameInfo NameInfo; 3654 NameInfo.setLoc(Name.StartLocation); 3655 3656 switch (Name.getKind()) { 3657 3658 case UnqualifiedId::IK_ImplicitSelfParam: 3659 case UnqualifiedId::IK_Identifier: 3660 NameInfo.setName(Name.Identifier); 3661 NameInfo.setLoc(Name.StartLocation); 3662 return NameInfo; 3663 3664 case UnqualifiedId::IK_OperatorFunctionId: 3665 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3666 Name.OperatorFunctionId.Operator)); 3667 NameInfo.setLoc(Name.StartLocation); 3668 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3669 = Name.OperatorFunctionId.SymbolLocations[0]; 3670 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3671 = Name.EndLocation.getRawEncoding(); 3672 return NameInfo; 3673 3674 case UnqualifiedId::IK_LiteralOperatorId: 3675 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3676 Name.Identifier)); 3677 NameInfo.setLoc(Name.StartLocation); 3678 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3679 return NameInfo; 3680 3681 case UnqualifiedId::IK_ConversionFunctionId: { 3682 TypeSourceInfo *TInfo; 3683 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3684 if (Ty.isNull()) 3685 return DeclarationNameInfo(); 3686 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3687 Context.getCanonicalType(Ty))); 3688 NameInfo.setLoc(Name.StartLocation); 3689 NameInfo.setNamedTypeInfo(TInfo); 3690 return NameInfo; 3691 } 3692 3693 case UnqualifiedId::IK_ConstructorName: { 3694 TypeSourceInfo *TInfo; 3695 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3696 if (Ty.isNull()) 3697 return DeclarationNameInfo(); 3698 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3699 Context.getCanonicalType(Ty))); 3700 NameInfo.setLoc(Name.StartLocation); 3701 NameInfo.setNamedTypeInfo(TInfo); 3702 return NameInfo; 3703 } 3704 3705 case UnqualifiedId::IK_ConstructorTemplateId: { 3706 // In well-formed code, we can only have a constructor 3707 // template-id that refers to the current context, so go there 3708 // to find the actual type being constructed. 3709 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3710 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3711 return DeclarationNameInfo(); 3712 3713 // Determine the type of the class being constructed. 3714 QualType CurClassType = Context.getTypeDeclType(CurClass); 3715 3716 // FIXME: Check two things: that the template-id names the same type as 3717 // CurClassType, and that the template-id does not occur when the name 3718 // was qualified. 3719 3720 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3721 Context.getCanonicalType(CurClassType))); 3722 NameInfo.setLoc(Name.StartLocation); 3723 // FIXME: should we retrieve TypeSourceInfo? 3724 NameInfo.setNamedTypeInfo(0); 3725 return NameInfo; 3726 } 3727 3728 case UnqualifiedId::IK_DestructorName: { 3729 TypeSourceInfo *TInfo; 3730 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3731 if (Ty.isNull()) 3732 return DeclarationNameInfo(); 3733 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3734 Context.getCanonicalType(Ty))); 3735 NameInfo.setLoc(Name.StartLocation); 3736 NameInfo.setNamedTypeInfo(TInfo); 3737 return NameInfo; 3738 } 3739 3740 case UnqualifiedId::IK_TemplateId: { 3741 TemplateName TName = Name.TemplateId->Template.get(); 3742 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3743 return Context.getNameForTemplate(TName, TNameLoc); 3744 } 3745 3746 } // switch (Name.getKind()) 3747 3748 llvm_unreachable("Unknown name kind"); 3749} 3750 3751static QualType getCoreType(QualType Ty) { 3752 do { 3753 if (Ty->isPointerType() || Ty->isReferenceType()) 3754 Ty = Ty->getPointeeType(); 3755 else if (Ty->isArrayType()) 3756 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3757 else 3758 return Ty.withoutLocalFastQualifiers(); 3759 } while (true); 3760} 3761 3762/// hasSimilarParameters - Determine whether the C++ functions Declaration 3763/// and Definition have "nearly" matching parameters. This heuristic is 3764/// used to improve diagnostics in the case where an out-of-line function 3765/// definition doesn't match any declaration within the class or namespace. 3766/// Also sets Params to the list of indices to the parameters that differ 3767/// between the declaration and the definition. If hasSimilarParameters 3768/// returns true and Params is empty, then all of the parameters match. 3769static bool hasSimilarParameters(ASTContext &Context, 3770 FunctionDecl *Declaration, 3771 FunctionDecl *Definition, 3772 SmallVectorImpl<unsigned> &Params) { 3773 Params.clear(); 3774 if (Declaration->param_size() != Definition->param_size()) 3775 return false; 3776 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3777 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3778 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3779 3780 // The parameter types are identical 3781 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3782 continue; 3783 3784 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3785 QualType DefParamBaseTy = getCoreType(DefParamTy); 3786 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3787 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3788 3789 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3790 (DeclTyName && DeclTyName == DefTyName)) 3791 Params.push_back(Idx); 3792 else // The two parameters aren't even close 3793 return false; 3794 } 3795 3796 return true; 3797} 3798 3799/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3800/// declarator needs to be rebuilt in the current instantiation. 3801/// Any bits of declarator which appear before the name are valid for 3802/// consideration here. That's specifically the type in the decl spec 3803/// and the base type in any member-pointer chunks. 3804static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3805 DeclarationName Name) { 3806 // The types we specifically need to rebuild are: 3807 // - typenames, typeofs, and decltypes 3808 // - types which will become injected class names 3809 // Of course, we also need to rebuild any type referencing such a 3810 // type. It's safest to just say "dependent", but we call out a 3811 // few cases here. 3812 3813 DeclSpec &DS = D.getMutableDeclSpec(); 3814 switch (DS.getTypeSpecType()) { 3815 case DeclSpec::TST_typename: 3816 case DeclSpec::TST_typeofType: 3817 case DeclSpec::TST_underlyingType: 3818 case DeclSpec::TST_atomic: { 3819 // Grab the type from the parser. 3820 TypeSourceInfo *TSI = 0; 3821 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3822 if (T.isNull() || !T->isDependentType()) break; 3823 3824 // Make sure there's a type source info. This isn't really much 3825 // of a waste; most dependent types should have type source info 3826 // attached already. 3827 if (!TSI) 3828 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3829 3830 // Rebuild the type in the current instantiation. 3831 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3832 if (!TSI) return true; 3833 3834 // Store the new type back in the decl spec. 3835 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3836 DS.UpdateTypeRep(LocType); 3837 break; 3838 } 3839 3840 case DeclSpec::TST_decltype: 3841 case DeclSpec::TST_typeofExpr: { 3842 Expr *E = DS.getRepAsExpr(); 3843 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3844 if (Result.isInvalid()) return true; 3845 DS.UpdateExprRep(Result.get()); 3846 break; 3847 } 3848 3849 default: 3850 // Nothing to do for these decl specs. 3851 break; 3852 } 3853 3854 // It doesn't matter what order we do this in. 3855 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3856 DeclaratorChunk &Chunk = D.getTypeObject(I); 3857 3858 // The only type information in the declarator which can come 3859 // before the declaration name is the base type of a member 3860 // pointer. 3861 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3862 continue; 3863 3864 // Rebuild the scope specifier in-place. 3865 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3866 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3867 return true; 3868 } 3869 3870 return false; 3871} 3872 3873Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3874 D.setFunctionDefinitionKind(FDK_Declaration); 3875 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3876 3877 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3878 Dcl && Dcl->getDeclContext()->isFileContext()) 3879 Dcl->setTopLevelDeclInObjCContainer(); 3880 3881 return Dcl; 3882} 3883 3884/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3885/// If T is the name of a class, then each of the following shall have a 3886/// name different from T: 3887/// - every static data member of class T; 3888/// - every member function of class T 3889/// - every member of class T that is itself a type; 3890/// \returns true if the declaration name violates these rules. 3891bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3892 DeclarationNameInfo NameInfo) { 3893 DeclarationName Name = NameInfo.getName(); 3894 3895 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3896 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3897 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3898 return true; 3899 } 3900 3901 return false; 3902} 3903 3904/// \brief Diagnose a declaration whose declarator-id has the given 3905/// nested-name-specifier. 3906/// 3907/// \param SS The nested-name-specifier of the declarator-id. 3908/// 3909/// \param DC The declaration context to which the nested-name-specifier 3910/// resolves. 3911/// 3912/// \param Name The name of the entity being declared. 3913/// 3914/// \param Loc The location of the name of the entity being declared. 3915/// 3916/// \returns true if we cannot safely recover from this error, false otherwise. 3917bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3918 DeclarationName Name, 3919 SourceLocation Loc) { 3920 DeclContext *Cur = CurContext; 3921 while (isa<LinkageSpecDecl>(Cur)) 3922 Cur = Cur->getParent(); 3923 3924 // C++ [dcl.meaning]p1: 3925 // A declarator-id shall not be qualified except for the definition 3926 // of a member function (9.3) or static data member (9.4) outside of 3927 // its class, the definition or explicit instantiation of a function 3928 // or variable member of a namespace outside of its namespace, or the 3929 // definition of an explicit specialization outside of its namespace, 3930 // or the declaration of a friend function that is a member of 3931 // another class or namespace (11.3). [...] 3932 3933 // The user provided a superfluous scope specifier that refers back to the 3934 // class or namespaces in which the entity is already declared. 3935 // 3936 // class X { 3937 // void X::f(); 3938 // }; 3939 if (Cur->Equals(DC)) { 3940 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3941 : diag::err_member_extra_qualification) 3942 << Name << FixItHint::CreateRemoval(SS.getRange()); 3943 SS.clear(); 3944 return false; 3945 } 3946 3947 // Check whether the qualifying scope encloses the scope of the original 3948 // declaration. 3949 if (!Cur->Encloses(DC)) { 3950 if (Cur->isRecord()) 3951 Diag(Loc, diag::err_member_qualification) 3952 << Name << SS.getRange(); 3953 else if (isa<TranslationUnitDecl>(DC)) 3954 Diag(Loc, diag::err_invalid_declarator_global_scope) 3955 << Name << SS.getRange(); 3956 else if (isa<FunctionDecl>(Cur)) 3957 Diag(Loc, diag::err_invalid_declarator_in_function) 3958 << Name << SS.getRange(); 3959 else 3960 Diag(Loc, diag::err_invalid_declarator_scope) 3961 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3962 3963 return true; 3964 } 3965 3966 if (Cur->isRecord()) { 3967 // Cannot qualify members within a class. 3968 Diag(Loc, diag::err_member_qualification) 3969 << Name << SS.getRange(); 3970 SS.clear(); 3971 3972 // C++ constructors and destructors with incorrect scopes can break 3973 // our AST invariants by having the wrong underlying types. If 3974 // that's the case, then drop this declaration entirely. 3975 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3976 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3977 !Context.hasSameType(Name.getCXXNameType(), 3978 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3979 return true; 3980 3981 return false; 3982 } 3983 3984 // C++11 [dcl.meaning]p1: 3985 // [...] "The nested-name-specifier of the qualified declarator-id shall 3986 // not begin with a decltype-specifer" 3987 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3988 while (SpecLoc.getPrefix()) 3989 SpecLoc = SpecLoc.getPrefix(); 3990 if (dyn_cast_or_null<DecltypeType>( 3991 SpecLoc.getNestedNameSpecifier()->getAsType())) 3992 Diag(Loc, diag::err_decltype_in_declarator) 3993 << SpecLoc.getTypeLoc().getSourceRange(); 3994 3995 return false; 3996} 3997 3998NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3999 MultiTemplateParamsArg TemplateParamLists) { 4000 // TODO: consider using NameInfo for diagnostic. 4001 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4002 DeclarationName Name = NameInfo.getName(); 4003 4004 // All of these full declarators require an identifier. If it doesn't have 4005 // one, the ParsedFreeStandingDeclSpec action should be used. 4006 if (!Name) { 4007 if (!D.isInvalidType()) // Reject this if we think it is valid. 4008 Diag(D.getDeclSpec().getLocStart(), 4009 diag::err_declarator_need_ident) 4010 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4011 return 0; 4012 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4013 return 0; 4014 4015 // The scope passed in may not be a decl scope. Zip up the scope tree until 4016 // we find one that is. 4017 while ((S->getFlags() & Scope::DeclScope) == 0 || 4018 (S->getFlags() & Scope::TemplateParamScope) != 0) 4019 S = S->getParent(); 4020 4021 DeclContext *DC = CurContext; 4022 if (D.getCXXScopeSpec().isInvalid()) 4023 D.setInvalidType(); 4024 else if (D.getCXXScopeSpec().isSet()) { 4025 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4026 UPPC_DeclarationQualifier)) 4027 return 0; 4028 4029 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4030 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4031 if (!DC) { 4032 // If we could not compute the declaration context, it's because the 4033 // declaration context is dependent but does not refer to a class, 4034 // class template, or class template partial specialization. Complain 4035 // and return early, to avoid the coming semantic disaster. 4036 Diag(D.getIdentifierLoc(), 4037 diag::err_template_qualified_declarator_no_match) 4038 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4039 << D.getCXXScopeSpec().getRange(); 4040 return 0; 4041 } 4042 bool IsDependentContext = DC->isDependentContext(); 4043 4044 if (!IsDependentContext && 4045 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4046 return 0; 4047 4048 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4049 Diag(D.getIdentifierLoc(), 4050 diag::err_member_def_undefined_record) 4051 << Name << DC << D.getCXXScopeSpec().getRange(); 4052 D.setInvalidType(); 4053 } else if (!D.getDeclSpec().isFriendSpecified()) { 4054 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4055 Name, D.getIdentifierLoc())) { 4056 if (DC->isRecord()) 4057 return 0; 4058 4059 D.setInvalidType(); 4060 } 4061 } 4062 4063 // Check whether we need to rebuild the type of the given 4064 // declaration in the current instantiation. 4065 if (EnteringContext && IsDependentContext && 4066 TemplateParamLists.size() != 0) { 4067 ContextRAII SavedContext(*this, DC); 4068 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4069 D.setInvalidType(); 4070 } 4071 } 4072 4073 if (DiagnoseClassNameShadow(DC, NameInfo)) 4074 // If this is a typedef, we'll end up spewing multiple diagnostics. 4075 // Just return early; it's safer. 4076 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4077 return 0; 4078 4079 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4080 QualType R = TInfo->getType(); 4081 4082 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4083 UPPC_DeclarationType)) 4084 D.setInvalidType(); 4085 4086 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4087 ForRedeclaration); 4088 4089 // See if this is a redefinition of a variable in the same scope. 4090 if (!D.getCXXScopeSpec().isSet()) { 4091 bool IsLinkageLookup = false; 4092 4093 // If the declaration we're planning to build will be a function 4094 // or object with linkage, then look for another declaration with 4095 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4096 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4097 /* Do nothing*/; 4098 else if (R->isFunctionType()) { 4099 if (CurContext->isFunctionOrMethod() || 4100 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4101 IsLinkageLookup = true; 4102 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 4103 IsLinkageLookup = true; 4104 else if (CurContext->getRedeclContext()->isTranslationUnit() && 4105 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4106 IsLinkageLookup = true; 4107 4108 if (IsLinkageLookup) 4109 Previous.clear(LookupRedeclarationWithLinkage); 4110 4111 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 4112 } else { // Something like "int foo::x;" 4113 LookupQualifiedName(Previous, DC); 4114 4115 // C++ [dcl.meaning]p1: 4116 // When the declarator-id is qualified, the declaration shall refer to a 4117 // previously declared member of the class or namespace to which the 4118 // qualifier refers (or, in the case of a namespace, of an element of the 4119 // inline namespace set of that namespace (7.3.1)) or to a specialization 4120 // thereof; [...] 4121 // 4122 // Note that we already checked the context above, and that we do not have 4123 // enough information to make sure that Previous contains the declaration 4124 // we want to match. For example, given: 4125 // 4126 // class X { 4127 // void f(); 4128 // void f(float); 4129 // }; 4130 // 4131 // void X::f(int) { } // ill-formed 4132 // 4133 // In this case, Previous will point to the overload set 4134 // containing the two f's declared in X, but neither of them 4135 // matches. 4136 4137 // C++ [dcl.meaning]p1: 4138 // [...] the member shall not merely have been introduced by a 4139 // using-declaration in the scope of the class or namespace nominated by 4140 // the nested-name-specifier of the declarator-id. 4141 RemoveUsingDecls(Previous); 4142 } 4143 4144 if (Previous.isSingleResult() && 4145 Previous.getFoundDecl()->isTemplateParameter()) { 4146 // Maybe we will complain about the shadowed template parameter. 4147 if (!D.isInvalidType()) 4148 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4149 Previous.getFoundDecl()); 4150 4151 // Just pretend that we didn't see the previous declaration. 4152 Previous.clear(); 4153 } 4154 4155 // In C++, the previous declaration we find might be a tag type 4156 // (class or enum). In this case, the new declaration will hide the 4157 // tag type. Note that this does does not apply if we're declaring a 4158 // typedef (C++ [dcl.typedef]p4). 4159 if (Previous.isSingleTagDecl() && 4160 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4161 Previous.clear(); 4162 4163 // Check that there are no default arguments other than in the parameters 4164 // of a function declaration (C++ only). 4165 if (getLangOpts().CPlusPlus) 4166 CheckExtraCXXDefaultArguments(D); 4167 4168 NamedDecl *New; 4169 4170 bool AddToScope = true; 4171 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4172 if (TemplateParamLists.size()) { 4173 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4174 return 0; 4175 } 4176 4177 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4178 } else if (R->isFunctionType()) { 4179 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4180 TemplateParamLists, 4181 AddToScope); 4182 } else { 4183 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 4184 TemplateParamLists); 4185 } 4186 4187 if (New == 0) 4188 return 0; 4189 4190 // If this has an identifier and is not an invalid redeclaration or 4191 // function template specialization, add it to the scope stack. 4192 if (New->getDeclName() && AddToScope && 4193 !(D.isRedeclaration() && New->isInvalidDecl())) 4194 PushOnScopeChains(New, S); 4195 4196 return New; 4197} 4198 4199/// Helper method to turn variable array types into constant array 4200/// types in certain situations which would otherwise be errors (for 4201/// GCC compatibility). 4202static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4203 ASTContext &Context, 4204 bool &SizeIsNegative, 4205 llvm::APSInt &Oversized) { 4206 // This method tries to turn a variable array into a constant 4207 // array even when the size isn't an ICE. This is necessary 4208 // for compatibility with code that depends on gcc's buggy 4209 // constant expression folding, like struct {char x[(int)(char*)2];} 4210 SizeIsNegative = false; 4211 Oversized = 0; 4212 4213 if (T->isDependentType()) 4214 return QualType(); 4215 4216 QualifierCollector Qs; 4217 const Type *Ty = Qs.strip(T); 4218 4219 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4220 QualType Pointee = PTy->getPointeeType(); 4221 QualType FixedType = 4222 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4223 Oversized); 4224 if (FixedType.isNull()) return FixedType; 4225 FixedType = Context.getPointerType(FixedType); 4226 return Qs.apply(Context, FixedType); 4227 } 4228 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4229 QualType Inner = PTy->getInnerType(); 4230 QualType FixedType = 4231 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4232 Oversized); 4233 if (FixedType.isNull()) return FixedType; 4234 FixedType = Context.getParenType(FixedType); 4235 return Qs.apply(Context, FixedType); 4236 } 4237 4238 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4239 if (!VLATy) 4240 return QualType(); 4241 // FIXME: We should probably handle this case 4242 if (VLATy->getElementType()->isVariablyModifiedType()) 4243 return QualType(); 4244 4245 llvm::APSInt Res; 4246 if (!VLATy->getSizeExpr() || 4247 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4248 return QualType(); 4249 4250 // Check whether the array size is negative. 4251 if (Res.isSigned() && Res.isNegative()) { 4252 SizeIsNegative = true; 4253 return QualType(); 4254 } 4255 4256 // Check whether the array is too large to be addressed. 4257 unsigned ActiveSizeBits 4258 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4259 Res); 4260 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4261 Oversized = Res; 4262 return QualType(); 4263 } 4264 4265 return Context.getConstantArrayType(VLATy->getElementType(), 4266 Res, ArrayType::Normal, 0); 4267} 4268 4269static void 4270FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4271 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4272 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4273 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4274 DstPTL.getPointeeLoc()); 4275 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4276 return; 4277 } 4278 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4279 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4280 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4281 DstPTL.getInnerLoc()); 4282 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4283 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4284 return; 4285 } 4286 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4287 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4288 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4289 TypeLoc DstElemTL = DstATL.getElementLoc(); 4290 DstElemTL.initializeFullCopy(SrcElemTL); 4291 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4292 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4293 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4294} 4295 4296/// Helper method to turn variable array types into constant array 4297/// types in certain situations which would otherwise be errors (for 4298/// GCC compatibility). 4299static TypeSourceInfo* 4300TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4301 ASTContext &Context, 4302 bool &SizeIsNegative, 4303 llvm::APSInt &Oversized) { 4304 QualType FixedTy 4305 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4306 SizeIsNegative, Oversized); 4307 if (FixedTy.isNull()) 4308 return 0; 4309 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4310 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4311 FixedTInfo->getTypeLoc()); 4312 return FixedTInfo; 4313} 4314 4315/// \brief Register the given locally-scoped extern "C" declaration so 4316/// that it can be found later for redeclarations 4317void 4318Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 4319 const LookupResult &Previous, 4320 Scope *S) { 4321 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 4322 "Decl is not a locally-scoped decl!"); 4323 // Note that we have a locally-scoped external with this name. 4324 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4325 4326 if (!Previous.isSingleResult()) 4327 return; 4328 4329 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4330 4331 // If there was a previous declaration of this entity, it may be in 4332 // our identifier chain. Update the identifier chain with the new 4333 // declaration. 4334 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 4335 // The previous declaration was found on the identifer resolver 4336 // chain, so remove it from its scope. 4337 4338 if (S->isDeclScope(PrevDecl)) { 4339 // Special case for redeclarations in the SAME scope. 4340 // Because this declaration is going to be added to the identifier chain 4341 // later, we should temporarily take it OFF the chain. 4342 IdResolver.RemoveDecl(ND); 4343 4344 } else { 4345 // Find the scope for the original declaration. 4346 while (S && !S->isDeclScope(PrevDecl)) 4347 S = S->getParent(); 4348 } 4349 4350 if (S) 4351 S->RemoveDecl(PrevDecl); 4352 } 4353} 4354 4355llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 4356Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4357 if (ExternalSource) { 4358 // Load locally-scoped external decls from the external source. 4359 SmallVector<NamedDecl *, 4> Decls; 4360 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4361 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4362 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4363 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4364 if (Pos == LocallyScopedExternCDecls.end()) 4365 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4366 } 4367 } 4368 4369 return LocallyScopedExternCDecls.find(Name); 4370} 4371 4372/// \brief Diagnose function specifiers on a declaration of an identifier that 4373/// does not identify a function. 4374void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4375 // FIXME: We should probably indicate the identifier in question to avoid 4376 // confusion for constructs like "inline int a(), b;" 4377 if (DS.isInlineSpecified()) 4378 Diag(DS.getInlineSpecLoc(), 4379 diag::err_inline_non_function); 4380 4381 if (DS.isVirtualSpecified()) 4382 Diag(DS.getVirtualSpecLoc(), 4383 diag::err_virtual_non_function); 4384 4385 if (DS.isExplicitSpecified()) 4386 Diag(DS.getExplicitSpecLoc(), 4387 diag::err_explicit_non_function); 4388 4389 if (DS.isNoreturnSpecified()) 4390 Diag(DS.getNoreturnSpecLoc(), 4391 diag::err_noreturn_non_function); 4392} 4393 4394NamedDecl* 4395Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4396 TypeSourceInfo *TInfo, LookupResult &Previous) { 4397 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4398 if (D.getCXXScopeSpec().isSet()) { 4399 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4400 << D.getCXXScopeSpec().getRange(); 4401 D.setInvalidType(); 4402 // Pretend we didn't see the scope specifier. 4403 DC = CurContext; 4404 Previous.clear(); 4405 } 4406 4407 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4408 4409 if (D.getDeclSpec().isThreadSpecified()) 4410 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4411 if (D.getDeclSpec().isConstexprSpecified()) 4412 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4413 << 1; 4414 4415 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4416 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4417 << D.getName().getSourceRange(); 4418 return 0; 4419 } 4420 4421 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4422 if (!NewTD) return 0; 4423 4424 // Handle attributes prior to checking for duplicates in MergeVarDecl 4425 ProcessDeclAttributes(S, NewTD, D); 4426 4427 CheckTypedefForVariablyModifiedType(S, NewTD); 4428 4429 bool Redeclaration = D.isRedeclaration(); 4430 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4431 D.setRedeclaration(Redeclaration); 4432 return ND; 4433} 4434 4435void 4436Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4437 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4438 // then it shall have block scope. 4439 // Note that variably modified types must be fixed before merging the decl so 4440 // that redeclarations will match. 4441 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4442 QualType T = TInfo->getType(); 4443 if (T->isVariablyModifiedType()) { 4444 getCurFunction()->setHasBranchProtectedScope(); 4445 4446 if (S->getFnParent() == 0) { 4447 bool SizeIsNegative; 4448 llvm::APSInt Oversized; 4449 TypeSourceInfo *FixedTInfo = 4450 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4451 SizeIsNegative, 4452 Oversized); 4453 if (FixedTInfo) { 4454 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4455 NewTD->setTypeSourceInfo(FixedTInfo); 4456 } else { 4457 if (SizeIsNegative) 4458 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4459 else if (T->isVariableArrayType()) 4460 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4461 else if (Oversized.getBoolValue()) 4462 Diag(NewTD->getLocation(), diag::err_array_too_large) 4463 << Oversized.toString(10); 4464 else 4465 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4466 NewTD->setInvalidDecl(); 4467 } 4468 } 4469 } 4470} 4471 4472 4473/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4474/// declares a typedef-name, either using the 'typedef' type specifier or via 4475/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4476NamedDecl* 4477Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4478 LookupResult &Previous, bool &Redeclaration) { 4479 // Merge the decl with the existing one if appropriate. If the decl is 4480 // in an outer scope, it isn't the same thing. 4481 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4482 /*ExplicitInstantiationOrSpecialization=*/false); 4483 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4484 if (!Previous.empty()) { 4485 Redeclaration = true; 4486 MergeTypedefNameDecl(NewTD, Previous); 4487 } 4488 4489 // If this is the C FILE type, notify the AST context. 4490 if (IdentifierInfo *II = NewTD->getIdentifier()) 4491 if (!NewTD->isInvalidDecl() && 4492 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4493 if (II->isStr("FILE")) 4494 Context.setFILEDecl(NewTD); 4495 else if (II->isStr("jmp_buf")) 4496 Context.setjmp_bufDecl(NewTD); 4497 else if (II->isStr("sigjmp_buf")) 4498 Context.setsigjmp_bufDecl(NewTD); 4499 else if (II->isStr("ucontext_t")) 4500 Context.setucontext_tDecl(NewTD); 4501 } 4502 4503 return NewTD; 4504} 4505 4506/// \brief Determines whether the given declaration is an out-of-scope 4507/// previous declaration. 4508/// 4509/// This routine should be invoked when name lookup has found a 4510/// previous declaration (PrevDecl) that is not in the scope where a 4511/// new declaration by the same name is being introduced. If the new 4512/// declaration occurs in a local scope, previous declarations with 4513/// linkage may still be considered previous declarations (C99 4514/// 6.2.2p4-5, C++ [basic.link]p6). 4515/// 4516/// \param PrevDecl the previous declaration found by name 4517/// lookup 4518/// 4519/// \param DC the context in which the new declaration is being 4520/// declared. 4521/// 4522/// \returns true if PrevDecl is an out-of-scope previous declaration 4523/// for a new delcaration with the same name. 4524static bool 4525isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4526 ASTContext &Context) { 4527 if (!PrevDecl) 4528 return false; 4529 4530 if (!PrevDecl->hasLinkage()) 4531 return false; 4532 4533 if (Context.getLangOpts().CPlusPlus) { 4534 // C++ [basic.link]p6: 4535 // If there is a visible declaration of an entity with linkage 4536 // having the same name and type, ignoring entities declared 4537 // outside the innermost enclosing namespace scope, the block 4538 // scope declaration declares that same entity and receives the 4539 // linkage of the previous declaration. 4540 DeclContext *OuterContext = DC->getRedeclContext(); 4541 if (!OuterContext->isFunctionOrMethod()) 4542 // This rule only applies to block-scope declarations. 4543 return false; 4544 4545 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4546 if (PrevOuterContext->isRecord()) 4547 // We found a member function: ignore it. 4548 return false; 4549 4550 // Find the innermost enclosing namespace for the new and 4551 // previous declarations. 4552 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4553 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4554 4555 // The previous declaration is in a different namespace, so it 4556 // isn't the same function. 4557 if (!OuterContext->Equals(PrevOuterContext)) 4558 return false; 4559 } 4560 4561 return true; 4562} 4563 4564static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4565 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4566 if (!SS.isSet()) return; 4567 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4568} 4569 4570bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4571 QualType type = decl->getType(); 4572 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4573 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4574 // Various kinds of declaration aren't allowed to be __autoreleasing. 4575 unsigned kind = -1U; 4576 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4577 if (var->hasAttr<BlocksAttr>()) 4578 kind = 0; // __block 4579 else if (!var->hasLocalStorage()) 4580 kind = 1; // global 4581 } else if (isa<ObjCIvarDecl>(decl)) { 4582 kind = 3; // ivar 4583 } else if (isa<FieldDecl>(decl)) { 4584 kind = 2; // field 4585 } 4586 4587 if (kind != -1U) { 4588 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4589 << kind; 4590 } 4591 } else if (lifetime == Qualifiers::OCL_None) { 4592 // Try to infer lifetime. 4593 if (!type->isObjCLifetimeType()) 4594 return false; 4595 4596 lifetime = type->getObjCARCImplicitLifetime(); 4597 type = Context.getLifetimeQualifiedType(type, lifetime); 4598 decl->setType(type); 4599 } 4600 4601 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4602 // Thread-local variables cannot have lifetime. 4603 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4604 var->isThreadSpecified()) { 4605 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4606 << var->getType(); 4607 return true; 4608 } 4609 } 4610 4611 return false; 4612} 4613 4614static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4615 // 'weak' only applies to declarations with external linkage. 4616 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4617 if (ND.getLinkage() != ExternalLinkage) { 4618 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4619 ND.dropAttr<WeakAttr>(); 4620 } 4621 } 4622 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4623 if (ND.hasExternalLinkage()) { 4624 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4625 ND.dropAttr<WeakRefAttr>(); 4626 } 4627 } 4628} 4629 4630/// Given that we are within the definition of the given function, 4631/// will that definition behave like C99's 'inline', where the 4632/// definition is discarded except for optimization purposes? 4633static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4634 // Try to avoid calling GetGVALinkageForFunction. 4635 4636 // All cases of this require the 'inline' keyword. 4637 if (!FD->isInlined()) return false; 4638 4639 // This is only possible in C++ with the gnu_inline attribute. 4640 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4641 return false; 4642 4643 // Okay, go ahead and call the relatively-more-expensive function. 4644 4645#ifndef NDEBUG 4646 // AST quite reasonably asserts that it's working on a function 4647 // definition. We don't really have a way to tell it that we're 4648 // currently defining the function, so just lie to it in +Asserts 4649 // builds. This is an awful hack. 4650 FD->setLazyBody(1); 4651#endif 4652 4653 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4654 4655#ifndef NDEBUG 4656 FD->setLazyBody(0); 4657#endif 4658 4659 return isC99Inline; 4660} 4661 4662static bool shouldConsiderLinkage(const VarDecl *VD) { 4663 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4664 if (DC->isFunctionOrMethod()) 4665 return VD->hasExternalStorage(); 4666 if (DC->isFileContext()) 4667 return true; 4668 if (DC->isRecord()) 4669 return false; 4670 llvm_unreachable("Unexpected context"); 4671} 4672 4673static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4674 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4675 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4676 return true; 4677 if (DC->isRecord()) 4678 return false; 4679 llvm_unreachable("Unexpected context"); 4680} 4681 4682NamedDecl* 4683Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4684 TypeSourceInfo *TInfo, LookupResult &Previous, 4685 MultiTemplateParamsArg TemplateParamLists) { 4686 QualType R = TInfo->getType(); 4687 DeclarationName Name = GetNameForDeclarator(D).getName(); 4688 4689 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4690 assert(SCSpec != DeclSpec::SCS_typedef && 4691 "Parser allowed 'typedef' as storage class VarDecl."); 4692 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4693 4694 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) 4695 { 4696 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4697 // half array type (unless the cl_khr_fp16 extension is enabled). 4698 if (Context.getBaseElementType(R)->isHalfType()) { 4699 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4700 D.setInvalidType(); 4701 } 4702 } 4703 4704 if (SCSpec == DeclSpec::SCS_mutable) { 4705 // mutable can only appear on non-static class members, so it's always 4706 // an error here 4707 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4708 D.setInvalidType(); 4709 SC = SC_None; 4710 } 4711 4712 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4713 if (!II) { 4714 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4715 << Name; 4716 return 0; 4717 } 4718 4719 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4720 4721 if (!DC->isRecord() && S->getFnParent() == 0) { 4722 // C99 6.9p2: The storage-class specifiers auto and register shall not 4723 // appear in the declaration specifiers in an external declaration. 4724 if (SC == SC_Auto || SC == SC_Register) { 4725 4726 // If this is a register variable with an asm label specified, then this 4727 // is a GNU extension. 4728 if (SC == SC_Register && D.getAsmLabel()) 4729 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4730 else 4731 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4732 D.setInvalidType(); 4733 } 4734 } 4735 4736 if (getLangOpts().OpenCL) { 4737 // Set up the special work-group-local storage class for variables in the 4738 // OpenCL __local address space. 4739 if (R.getAddressSpace() == LangAS::opencl_local) { 4740 SC = SC_OpenCLWorkGroupLocal; 4741 } 4742 4743 // OpenCL v1.2 s6.9.b p4: 4744 // The sampler type cannot be used with the __local and __global address 4745 // space qualifiers. 4746 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 4747 R.getAddressSpace() == LangAS::opencl_global)) { 4748 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 4749 } 4750 4751 // OpenCL 1.2 spec, p6.9 r: 4752 // The event type cannot be used to declare a program scope variable. 4753 // The event type cannot be used with the __local, __constant and __global 4754 // address space qualifiers. 4755 if (R->isEventT()) { 4756 if (S->getParent() == 0) { 4757 Diag(D.getLocStart(), diag::err_event_t_global_var); 4758 D.setInvalidType(); 4759 } 4760 4761 if (R.getAddressSpace()) { 4762 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 4763 D.setInvalidType(); 4764 } 4765 } 4766 } 4767 4768 bool isExplicitSpecialization = false; 4769 VarDecl *NewVD; 4770 if (!getLangOpts().CPlusPlus) { 4771 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4772 D.getIdentifierLoc(), II, 4773 R, TInfo, SC); 4774 4775 if (D.isInvalidType()) 4776 NewVD->setInvalidDecl(); 4777 } else { 4778 if (DC->isRecord() && !CurContext->isRecord()) { 4779 // This is an out-of-line definition of a static data member. 4780 if (SC == SC_Static) { 4781 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4782 diag::err_static_out_of_line) 4783 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4784 } else if (SC == SC_None) 4785 SC = SC_Static; 4786 } 4787 if (SC == SC_Static && CurContext->isRecord()) { 4788 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4789 if (RD->isLocalClass()) 4790 Diag(D.getIdentifierLoc(), 4791 diag::err_static_data_member_not_allowed_in_local_class) 4792 << Name << RD->getDeclName(); 4793 4794 // C++98 [class.union]p1: If a union contains a static data member, 4795 // the program is ill-formed. C++11 drops this restriction. 4796 if (RD->isUnion()) 4797 Diag(D.getIdentifierLoc(), 4798 getLangOpts().CPlusPlus11 4799 ? diag::warn_cxx98_compat_static_data_member_in_union 4800 : diag::ext_static_data_member_in_union) << Name; 4801 // We conservatively disallow static data members in anonymous structs. 4802 else if (!RD->getDeclName()) 4803 Diag(D.getIdentifierLoc(), 4804 diag::err_static_data_member_not_allowed_in_anon_struct) 4805 << Name << RD->isUnion(); 4806 } 4807 } 4808 4809 // Match up the template parameter lists with the scope specifier, then 4810 // determine whether we have a template or a template specialization. 4811 isExplicitSpecialization = false; 4812 bool Invalid = false; 4813 if (TemplateParameterList *TemplateParams 4814 = MatchTemplateParametersToScopeSpecifier( 4815 D.getDeclSpec().getLocStart(), 4816 D.getIdentifierLoc(), 4817 D.getCXXScopeSpec(), 4818 TemplateParamLists.data(), 4819 TemplateParamLists.size(), 4820 /*never a friend*/ false, 4821 isExplicitSpecialization, 4822 Invalid)) { 4823 if (TemplateParams->size() > 0) { 4824 // There is no such thing as a variable template. 4825 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4826 << II 4827 << SourceRange(TemplateParams->getTemplateLoc(), 4828 TemplateParams->getRAngleLoc()); 4829 return 0; 4830 } else { 4831 // There is an extraneous 'template<>' for this variable. Complain 4832 // about it, but allow the declaration of the variable. 4833 Diag(TemplateParams->getTemplateLoc(), 4834 diag::err_template_variable_noparams) 4835 << II 4836 << SourceRange(TemplateParams->getTemplateLoc(), 4837 TemplateParams->getRAngleLoc()); 4838 } 4839 } 4840 4841 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4842 D.getIdentifierLoc(), II, 4843 R, TInfo, SC); 4844 4845 // If this decl has an auto type in need of deduction, make a note of the 4846 // Decl so we can diagnose uses of it in its own initializer. 4847 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4848 R->getContainedAutoType()) 4849 ParsingInitForAutoVars.insert(NewVD); 4850 4851 if (D.isInvalidType() || Invalid) 4852 NewVD->setInvalidDecl(); 4853 4854 SetNestedNameSpecifier(NewVD, D); 4855 4856 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4857 NewVD->setTemplateParameterListsInfo(Context, 4858 TemplateParamLists.size(), 4859 TemplateParamLists.data()); 4860 } 4861 4862 if (D.getDeclSpec().isConstexprSpecified()) 4863 NewVD->setConstexpr(true); 4864 } 4865 4866 // Set the lexical context. If the declarator has a C++ scope specifier, the 4867 // lexical context will be different from the semantic context. 4868 NewVD->setLexicalDeclContext(CurContext); 4869 4870 if (D.getDeclSpec().isThreadSpecified()) { 4871 if (NewVD->hasLocalStorage()) 4872 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4873 else if (!Context.getTargetInfo().isTLSSupported()) 4874 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4875 else 4876 NewVD->setThreadSpecified(true); 4877 } 4878 4879 // C99 6.7.4p3 4880 // An inline definition of a function with external linkage shall 4881 // not contain a definition of a modifiable object with static or 4882 // thread storage duration... 4883 // We only apply this when the function is required to be defined 4884 // elsewhere, i.e. when the function is not 'extern inline'. Note 4885 // that a local variable with thread storage duration still has to 4886 // be marked 'static'. Also note that it's possible to get these 4887 // semantics in C++ using __attribute__((gnu_inline)). 4888 if (SC == SC_Static && S->getFnParent() != 0 && 4889 !NewVD->getType().isConstQualified()) { 4890 FunctionDecl *CurFD = getCurFunctionDecl(); 4891 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 4892 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4893 diag::warn_static_local_in_extern_inline); 4894 MaybeSuggestAddingStaticToDecl(CurFD); 4895 } 4896 } 4897 4898 if (D.getDeclSpec().isModulePrivateSpecified()) { 4899 if (isExplicitSpecialization) 4900 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4901 << 2 4902 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4903 else if (NewVD->hasLocalStorage()) 4904 Diag(NewVD->getLocation(), diag::err_module_private_local) 4905 << 0 << NewVD->getDeclName() 4906 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4907 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4908 else 4909 NewVD->setModulePrivate(); 4910 } 4911 4912 // Handle attributes prior to checking for duplicates in MergeVarDecl 4913 ProcessDeclAttributes(S, NewVD, D); 4914 4915 if (NewVD->hasAttrs()) 4916 CheckAlignasUnderalignment(NewVD); 4917 4918 if (getLangOpts().CUDA) { 4919 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4920 // storage [duration]." 4921 if (SC == SC_None && S->getFnParent() != 0 && 4922 (NewVD->hasAttr<CUDASharedAttr>() || 4923 NewVD->hasAttr<CUDAConstantAttr>())) { 4924 NewVD->setStorageClass(SC_Static); 4925 } 4926 } 4927 4928 // In auto-retain/release, infer strong retension for variables of 4929 // retainable type. 4930 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4931 NewVD->setInvalidDecl(); 4932 4933 // Handle GNU asm-label extension (encoded as an attribute). 4934 if (Expr *E = (Expr*)D.getAsmLabel()) { 4935 // The parser guarantees this is a string. 4936 StringLiteral *SE = cast<StringLiteral>(E); 4937 StringRef Label = SE->getString(); 4938 if (S->getFnParent() != 0) { 4939 switch (SC) { 4940 case SC_None: 4941 case SC_Auto: 4942 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4943 break; 4944 case SC_Register: 4945 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4946 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4947 break; 4948 case SC_Static: 4949 case SC_Extern: 4950 case SC_PrivateExtern: 4951 case SC_OpenCLWorkGroupLocal: 4952 break; 4953 } 4954 } 4955 4956 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4957 Context, Label)); 4958 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4959 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4960 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4961 if (I != ExtnameUndeclaredIdentifiers.end()) { 4962 NewVD->addAttr(I->second); 4963 ExtnameUndeclaredIdentifiers.erase(I); 4964 } 4965 } 4966 4967 // Diagnose shadowed variables before filtering for scope. 4968 if (!D.getCXXScopeSpec().isSet()) 4969 CheckShadow(S, NewVD, Previous); 4970 4971 // Don't consider existing declarations that are in a different 4972 // scope and are out-of-semantic-context declarations (if the new 4973 // declaration has linkage). 4974 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewVD), 4975 isExplicitSpecialization); 4976 4977 if (!getLangOpts().CPlusPlus) { 4978 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4979 } else { 4980 // Merge the decl with the existing one if appropriate. 4981 if (!Previous.empty()) { 4982 if (Previous.isSingleResult() && 4983 isa<FieldDecl>(Previous.getFoundDecl()) && 4984 D.getCXXScopeSpec().isSet()) { 4985 // The user tried to define a non-static data member 4986 // out-of-line (C++ [dcl.meaning]p1). 4987 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4988 << D.getCXXScopeSpec().getRange(); 4989 Previous.clear(); 4990 NewVD->setInvalidDecl(); 4991 } 4992 } else if (D.getCXXScopeSpec().isSet()) { 4993 // No previous declaration in the qualifying scope. 4994 Diag(D.getIdentifierLoc(), diag::err_no_member) 4995 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4996 << D.getCXXScopeSpec().getRange(); 4997 NewVD->setInvalidDecl(); 4998 } 4999 5000 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5001 5002 // This is an explicit specialization of a static data member. Check it. 5003 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 5004 CheckMemberSpecialization(NewVD, Previous)) 5005 NewVD->setInvalidDecl(); 5006 } 5007 5008 ProcessPragmaWeak(S, NewVD); 5009 checkAttributesAfterMerging(*this, *NewVD); 5010 5011 // If this is a locally-scoped extern C variable, update the map of 5012 // such variables. 5013 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 5014 !NewVD->isInvalidDecl()) 5015 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 5016 5017 return NewVD; 5018} 5019 5020/// \brief Diagnose variable or built-in function shadowing. Implements 5021/// -Wshadow. 5022/// 5023/// This method is called whenever a VarDecl is added to a "useful" 5024/// scope. 5025/// 5026/// \param S the scope in which the shadowing name is being declared 5027/// \param R the lookup of the name 5028/// 5029void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5030 // Return if warning is ignored. 5031 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5032 DiagnosticsEngine::Ignored) 5033 return; 5034 5035 // Don't diagnose declarations at file scope. 5036 if (D->hasGlobalStorage()) 5037 return; 5038 5039 DeclContext *NewDC = D->getDeclContext(); 5040 5041 // Only diagnose if we're shadowing an unambiguous field or variable. 5042 if (R.getResultKind() != LookupResult::Found) 5043 return; 5044 5045 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5046 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5047 return; 5048 5049 // Fields are not shadowed by variables in C++ static methods. 5050 if (isa<FieldDecl>(ShadowedDecl)) 5051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5052 if (MD->isStatic()) 5053 return; 5054 5055 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5056 if (shadowedVar->isExternC()) { 5057 // For shadowing external vars, make sure that we point to the global 5058 // declaration, not a locally scoped extern declaration. 5059 for (VarDecl::redecl_iterator 5060 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5061 I != E; ++I) 5062 if (I->isFileVarDecl()) { 5063 ShadowedDecl = *I; 5064 break; 5065 } 5066 } 5067 5068 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5069 5070 // Only warn about certain kinds of shadowing for class members. 5071 if (NewDC && NewDC->isRecord()) { 5072 // In particular, don't warn about shadowing non-class members. 5073 if (!OldDC->isRecord()) 5074 return; 5075 5076 // TODO: should we warn about static data members shadowing 5077 // static data members from base classes? 5078 5079 // TODO: don't diagnose for inaccessible shadowed members. 5080 // This is hard to do perfectly because we might friend the 5081 // shadowing context, but that's just a false negative. 5082 } 5083 5084 // Determine what kind of declaration we're shadowing. 5085 unsigned Kind; 5086 if (isa<RecordDecl>(OldDC)) { 5087 if (isa<FieldDecl>(ShadowedDecl)) 5088 Kind = 3; // field 5089 else 5090 Kind = 2; // static data member 5091 } else if (OldDC->isFileContext()) 5092 Kind = 1; // global 5093 else 5094 Kind = 0; // local 5095 5096 DeclarationName Name = R.getLookupName(); 5097 5098 // Emit warning and note. 5099 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5100 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5101} 5102 5103/// \brief Check -Wshadow without the advantage of a previous lookup. 5104void Sema::CheckShadow(Scope *S, VarDecl *D) { 5105 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5106 DiagnosticsEngine::Ignored) 5107 return; 5108 5109 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5110 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5111 LookupName(R, S); 5112 CheckShadow(S, D, R); 5113} 5114 5115template<typename T> 5116static bool mayConflictWithNonVisibleExternC(const T *ND) { 5117 const DeclContext *DC = ND->getDeclContext(); 5118 if (DC->getRedeclContext()->isTranslationUnit()) 5119 return true; 5120 5121 // We know that is the first decl we see, other than function local 5122 // extern C ones. If this is C++ and the decl is not in a extern C context 5123 // it cannot have C language linkage. Avoid calling isExternC in that case. 5124 // We need to this because of code like 5125 // 5126 // namespace { struct bar {}; } 5127 // auto foo = bar(); 5128 // 5129 // This code runs before the init of foo is set, and therefore before 5130 // the type of foo is known. Not knowing the type we cannot know its linkage 5131 // unless it is in an extern C block. 5132 if (!DC->isExternCContext()) { 5133 const ASTContext &Context = ND->getASTContext(); 5134 if (Context.getLangOpts().CPlusPlus) 5135 return false; 5136 } 5137 5138 return ND->isExternC(); 5139} 5140 5141/// \brief Perform semantic checking on a newly-created variable 5142/// declaration. 5143/// 5144/// This routine performs all of the type-checking required for a 5145/// variable declaration once it has been built. It is used both to 5146/// check variables after they have been parsed and their declarators 5147/// have been translated into a declaration, and to check variables 5148/// that have been instantiated from a template. 5149/// 5150/// Sets NewVD->isInvalidDecl() if an error was encountered. 5151/// 5152/// Returns true if the variable declaration is a redeclaration. 5153bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 5154 LookupResult &Previous) { 5155 // If the decl is already known invalid, don't check it. 5156 if (NewVD->isInvalidDecl()) 5157 return false; 5158 5159 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5160 QualType T = TInfo->getType(); 5161 5162 if (T->isObjCObjectType()) { 5163 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5164 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5165 T = Context.getObjCObjectPointerType(T); 5166 NewVD->setType(T); 5167 } 5168 5169 // Emit an error if an address space was applied to decl with local storage. 5170 // This includes arrays of objects with address space qualifiers, but not 5171 // automatic variables that point to other address spaces. 5172 // ISO/IEC TR 18037 S5.1.2 5173 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5174 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5175 NewVD->setInvalidDecl(); 5176 return false; 5177 } 5178 5179 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5180 // scope. 5181 if ((getLangOpts().OpenCLVersion >= 120) 5182 && NewVD->isStaticLocal()) { 5183 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5184 NewVD->setInvalidDecl(); 5185 return false; 5186 } 5187 5188 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5189 && !NewVD->hasAttr<BlocksAttr>()) { 5190 if (getLangOpts().getGC() != LangOptions::NonGC) 5191 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5192 else { 5193 assert(!getLangOpts().ObjCAutoRefCount); 5194 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5195 } 5196 } 5197 5198 bool isVM = T->isVariablyModifiedType(); 5199 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5200 NewVD->hasAttr<BlocksAttr>()) 5201 getCurFunction()->setHasBranchProtectedScope(); 5202 5203 if ((isVM && NewVD->hasLinkage()) || 5204 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5205 bool SizeIsNegative; 5206 llvm::APSInt Oversized; 5207 TypeSourceInfo *FixedTInfo = 5208 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5209 SizeIsNegative, Oversized); 5210 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5211 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5212 // FIXME: This won't give the correct result for 5213 // int a[10][n]; 5214 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5215 5216 if (NewVD->isFileVarDecl()) 5217 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5218 << SizeRange; 5219 else if (NewVD->getStorageClass() == SC_Static) 5220 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5221 << SizeRange; 5222 else 5223 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5224 << SizeRange; 5225 NewVD->setInvalidDecl(); 5226 return false; 5227 } 5228 5229 if (FixedTInfo == 0) { 5230 if (NewVD->isFileVarDecl()) 5231 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5232 else 5233 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5234 NewVD->setInvalidDecl(); 5235 return false; 5236 } 5237 5238 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5239 NewVD->setType(FixedTInfo->getType()); 5240 NewVD->setTypeSourceInfo(FixedTInfo); 5241 } 5242 5243 // If we did not find anything by this name, look for a non-visible 5244 // extern "C" declaration with the same name. 5245 // 5246 // Clang has a lot of problems with extern local declarations. 5247 // The actual standards text here is: 5248 // 5249 // C++11 [basic.link]p6: 5250 // The name of a function declared in block scope and the name 5251 // of a variable declared by a block scope extern declaration 5252 // have linkage. If there is a visible declaration of an entity 5253 // with linkage having the same name and type, ignoring entities 5254 // declared outside the innermost enclosing namespace scope, the 5255 // block scope declaration declares that same entity and 5256 // receives the linkage of the previous declaration. 5257 // 5258 // C11 6.2.7p4: 5259 // For an identifier with internal or external linkage declared 5260 // in a scope in which a prior declaration of that identifier is 5261 // visible, if the prior declaration specifies internal or 5262 // external linkage, the type of the identifier at the later 5263 // declaration becomes the composite type. 5264 // 5265 // The most important point here is that we're not allowed to 5266 // update our understanding of the type according to declarations 5267 // not in scope. 5268 bool PreviousWasHidden = false; 5269 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) { 5270 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5271 = findLocallyScopedExternCDecl(NewVD->getDeclName()); 5272 if (Pos != LocallyScopedExternCDecls.end()) { 5273 Previous.addDecl(Pos->second); 5274 PreviousWasHidden = true; 5275 } 5276 } 5277 5278 // Filter out any non-conflicting previous declarations. 5279 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5280 5281 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 5282 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5283 << T; 5284 NewVD->setInvalidDecl(); 5285 return false; 5286 } 5287 5288 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5289 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5290 NewVD->setInvalidDecl(); 5291 return false; 5292 } 5293 5294 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5295 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5296 NewVD->setInvalidDecl(); 5297 return false; 5298 } 5299 5300 if (NewVD->isConstexpr() && !T->isDependentType() && 5301 RequireLiteralType(NewVD->getLocation(), T, 5302 diag::err_constexpr_var_non_literal)) { 5303 NewVD->setInvalidDecl(); 5304 return false; 5305 } 5306 5307 if (!Previous.empty()) { 5308 MergeVarDecl(NewVD, Previous, PreviousWasHidden); 5309 return true; 5310 } 5311 return false; 5312} 5313 5314/// \brief Data used with FindOverriddenMethod 5315struct FindOverriddenMethodData { 5316 Sema *S; 5317 CXXMethodDecl *Method; 5318}; 5319 5320/// \brief Member lookup function that determines whether a given C++ 5321/// method overrides a method in a base class, to be used with 5322/// CXXRecordDecl::lookupInBases(). 5323static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5324 CXXBasePath &Path, 5325 void *UserData) { 5326 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5327 5328 FindOverriddenMethodData *Data 5329 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5330 5331 DeclarationName Name = Data->Method->getDeclName(); 5332 5333 // FIXME: Do we care about other names here too? 5334 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5335 // We really want to find the base class destructor here. 5336 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5337 CanQualType CT = Data->S->Context.getCanonicalType(T); 5338 5339 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5340 } 5341 5342 for (Path.Decls = BaseRecord->lookup(Name); 5343 !Path.Decls.empty(); 5344 Path.Decls = Path.Decls.slice(1)) { 5345 NamedDecl *D = Path.Decls.front(); 5346 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5347 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5348 return true; 5349 } 5350 } 5351 5352 return false; 5353} 5354 5355namespace { 5356 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5357} 5358/// \brief Report an error regarding overriding, along with any relevant 5359/// overriden methods. 5360/// 5361/// \param DiagID the primary error to report. 5362/// \param MD the overriding method. 5363/// \param OEK which overrides to include as notes. 5364static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5365 OverrideErrorKind OEK = OEK_All) { 5366 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5367 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5368 E = MD->end_overridden_methods(); 5369 I != E; ++I) { 5370 // This check (& the OEK parameter) could be replaced by a predicate, but 5371 // without lambdas that would be overkill. This is still nicer than writing 5372 // out the diag loop 3 times. 5373 if ((OEK == OEK_All) || 5374 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5375 (OEK == OEK_Deleted && (*I)->isDeleted())) 5376 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5377 } 5378} 5379 5380/// AddOverriddenMethods - See if a method overrides any in the base classes, 5381/// and if so, check that it's a valid override and remember it. 5382bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5383 // Look for virtual methods in base classes that this method might override. 5384 CXXBasePaths Paths; 5385 FindOverriddenMethodData Data; 5386 Data.Method = MD; 5387 Data.S = this; 5388 bool hasDeletedOverridenMethods = false; 5389 bool hasNonDeletedOverridenMethods = false; 5390 bool AddedAny = false; 5391 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5392 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5393 E = Paths.found_decls_end(); I != E; ++I) { 5394 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5395 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5396 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5397 !CheckOverridingFunctionAttributes(MD, OldMD) && 5398 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5399 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5400 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5401 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5402 AddedAny = true; 5403 } 5404 } 5405 } 5406 } 5407 5408 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5409 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5410 } 5411 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5412 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5413 } 5414 5415 return AddedAny; 5416} 5417 5418namespace { 5419 // Struct for holding all of the extra arguments needed by 5420 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5421 struct ActOnFDArgs { 5422 Scope *S; 5423 Declarator &D; 5424 MultiTemplateParamsArg TemplateParamLists; 5425 bool AddToScope; 5426 }; 5427} 5428 5429namespace { 5430 5431// Callback to only accept typo corrections that have a non-zero edit distance. 5432// Also only accept corrections that have the same parent decl. 5433class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5434 public: 5435 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5436 CXXRecordDecl *Parent) 5437 : Context(Context), OriginalFD(TypoFD), 5438 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5439 5440 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5441 if (candidate.getEditDistance() == 0) 5442 return false; 5443 5444 SmallVector<unsigned, 1> MismatchedParams; 5445 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5446 CDeclEnd = candidate.end(); 5447 CDecl != CDeclEnd; ++CDecl) { 5448 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5449 5450 if (FD && !FD->hasBody() && 5451 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 5452 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5453 CXXRecordDecl *Parent = MD->getParent(); 5454 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 5455 return true; 5456 } else if (!ExpectedParent) { 5457 return true; 5458 } 5459 } 5460 } 5461 5462 return false; 5463 } 5464 5465 private: 5466 ASTContext &Context; 5467 FunctionDecl *OriginalFD; 5468 CXXRecordDecl *ExpectedParent; 5469}; 5470 5471} 5472 5473/// \brief Generate diagnostics for an invalid function redeclaration. 5474/// 5475/// This routine handles generating the diagnostic messages for an invalid 5476/// function redeclaration, including finding possible similar declarations 5477/// or performing typo correction if there are no previous declarations with 5478/// the same name. 5479/// 5480/// Returns a NamedDecl iff typo correction was performed and substituting in 5481/// the new declaration name does not cause new errors. 5482static NamedDecl* DiagnoseInvalidRedeclaration( 5483 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 5484 ActOnFDArgs &ExtraArgs) { 5485 NamedDecl *Result = NULL; 5486 DeclarationName Name = NewFD->getDeclName(); 5487 DeclContext *NewDC = NewFD->getDeclContext(); 5488 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 5489 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5490 SmallVector<unsigned, 1> MismatchedParams; 5491 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 5492 TypoCorrection Correction; 5493 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 5494 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 5495 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 5496 : diag::err_member_def_does_not_match; 5497 5498 NewFD->setInvalidDecl(); 5499 SemaRef.LookupQualifiedName(Prev, NewDC); 5500 assert(!Prev.isAmbiguous() && 5501 "Cannot have an ambiguity in previous-declaration lookup"); 5502 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5503 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 5504 MD ? MD->getParent() : 0); 5505 if (!Prev.empty()) { 5506 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 5507 Func != FuncEnd; ++Func) { 5508 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 5509 if (FD && 5510 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5511 // Add 1 to the index so that 0 can mean the mismatch didn't 5512 // involve a parameter 5513 unsigned ParamNum = 5514 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 5515 NearMatches.push_back(std::make_pair(FD, ParamNum)); 5516 } 5517 } 5518 // If the qualified name lookup yielded nothing, try typo correction 5519 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 5520 Prev.getLookupKind(), 0, 0, 5521 Validator, NewDC))) { 5522 // Trap errors. 5523 Sema::SFINAETrap Trap(SemaRef); 5524 5525 // Set up everything for the call to ActOnFunctionDeclarator 5526 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 5527 ExtraArgs.D.getIdentifierLoc()); 5528 Previous.clear(); 5529 Previous.setLookupName(Correction.getCorrection()); 5530 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 5531 CDeclEnd = Correction.end(); 5532 CDecl != CDeclEnd; ++CDecl) { 5533 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5534 if (FD && !FD->hasBody() && 5535 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5536 Previous.addDecl(FD); 5537 } 5538 } 5539 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 5540 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 5541 // pieces need to verify the typo-corrected C++ declaraction and hopefully 5542 // eliminate the need for the parameter pack ExtraArgs. 5543 Result = SemaRef.ActOnFunctionDeclarator( 5544 ExtraArgs.S, ExtraArgs.D, 5545 Correction.getCorrectionDecl()->getDeclContext(), 5546 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 5547 ExtraArgs.AddToScope); 5548 if (Trap.hasErrorOccurred()) { 5549 // Pretend the typo correction never occurred 5550 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 5551 ExtraArgs.D.getIdentifierLoc()); 5552 ExtraArgs.D.setRedeclaration(wasRedeclaration); 5553 Previous.clear(); 5554 Previous.setLookupName(Name); 5555 Result = NULL; 5556 } else { 5557 for (LookupResult::iterator Func = Previous.begin(), 5558 FuncEnd = Previous.end(); 5559 Func != FuncEnd; ++Func) { 5560 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 5561 NearMatches.push_back(std::make_pair(FD, 0)); 5562 } 5563 } 5564 if (NearMatches.empty()) { 5565 // Ignore the correction if it didn't yield any close FunctionDecl matches 5566 Correction = TypoCorrection(); 5567 } else { 5568 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 5569 : diag::err_member_def_does_not_match_suggest; 5570 } 5571 } 5572 5573 if (Correction) { 5574 // FIXME: use Correction.getCorrectionRange() instead of computing the range 5575 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in 5576 // turn causes the correction to fully qualify the name. If we fix 5577 // CorrectTypo to minimally qualify then this change should be good. 5578 SourceRange FixItLoc(NewFD->getLocation()); 5579 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 5580 if (Correction.getCorrectionSpecifier() && SS.isValid()) 5581 FixItLoc.setBegin(SS.getBeginLoc()); 5582 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 5583 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 5584 << FixItHint::CreateReplacement( 5585 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 5586 } else { 5587 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 5588 << Name << NewDC << NewFD->getLocation(); 5589 } 5590 5591 bool NewFDisConst = false; 5592 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 5593 NewFDisConst = NewMD->isConst(); 5594 5595 for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator 5596 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 5597 NearMatch != NearMatchEnd; ++NearMatch) { 5598 FunctionDecl *FD = NearMatch->first; 5599 bool FDisConst = false; 5600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 5601 FDisConst = MD->isConst(); 5602 5603 if (unsigned Idx = NearMatch->second) { 5604 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 5605 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 5606 if (Loc.isInvalid()) Loc = FD->getLocation(); 5607 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 5608 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 5609 } else if (Correction) { 5610 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 5611 << Correction.getQuoted(SemaRef.getLangOpts()); 5612 } else if (FDisConst != NewFDisConst) { 5613 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 5614 << NewFDisConst << FD->getSourceRange().getEnd(); 5615 } else 5616 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 5617 } 5618 return Result; 5619} 5620 5621static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 5622 Declarator &D) { 5623 switch (D.getDeclSpec().getStorageClassSpec()) { 5624 default: llvm_unreachable("Unknown storage class!"); 5625 case DeclSpec::SCS_auto: 5626 case DeclSpec::SCS_register: 5627 case DeclSpec::SCS_mutable: 5628 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5629 diag::err_typecheck_sclass_func); 5630 D.setInvalidType(); 5631 break; 5632 case DeclSpec::SCS_unspecified: break; 5633 case DeclSpec::SCS_extern: return SC_Extern; 5634 case DeclSpec::SCS_static: { 5635 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 5636 // C99 6.7.1p5: 5637 // The declaration of an identifier for a function that has 5638 // block scope shall have no explicit storage-class specifier 5639 // other than extern 5640 // See also (C++ [dcl.stc]p4). 5641 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5642 diag::err_static_block_func); 5643 break; 5644 } else 5645 return SC_Static; 5646 } 5647 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5648 } 5649 5650 // No explicit storage class has already been returned 5651 return SC_None; 5652} 5653 5654static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 5655 DeclContext *DC, QualType &R, 5656 TypeSourceInfo *TInfo, 5657 FunctionDecl::StorageClass SC, 5658 bool &IsVirtualOkay) { 5659 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 5660 DeclarationName Name = NameInfo.getName(); 5661 5662 FunctionDecl *NewFD = 0; 5663 bool isInline = D.getDeclSpec().isInlineSpecified(); 5664 5665 if (!SemaRef.getLangOpts().CPlusPlus) { 5666 // Determine whether the function was written with a 5667 // prototype. This true when: 5668 // - there is a prototype in the declarator, or 5669 // - the type R of the function is some kind of typedef or other reference 5670 // to a type name (which eventually refers to a function type). 5671 bool HasPrototype = 5672 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 5673 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 5674 5675 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 5676 D.getLocStart(), NameInfo, R, 5677 TInfo, SC, isInline, 5678 HasPrototype, false); 5679 if (D.isInvalidType()) 5680 NewFD->setInvalidDecl(); 5681 5682 // Set the lexical context. 5683 NewFD->setLexicalDeclContext(SemaRef.CurContext); 5684 5685 return NewFD; 5686 } 5687 5688 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5689 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5690 5691 // Check that the return type is not an abstract class type. 5692 // For record types, this is done by the AbstractClassUsageDiagnoser once 5693 // the class has been completely parsed. 5694 if (!DC->isRecord() && 5695 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 5696 R->getAs<FunctionType>()->getResultType(), 5697 diag::err_abstract_type_in_decl, 5698 SemaRef.AbstractReturnType)) 5699 D.setInvalidType(); 5700 5701 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 5702 // This is a C++ constructor declaration. 5703 assert(DC->isRecord() && 5704 "Constructors can only be declared in a member context"); 5705 5706 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 5707 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5708 D.getLocStart(), NameInfo, 5709 R, TInfo, isExplicit, isInline, 5710 /*isImplicitlyDeclared=*/false, 5711 isConstexpr); 5712 5713 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5714 // This is a C++ destructor declaration. 5715 if (DC->isRecord()) { 5716 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 5717 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 5718 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 5719 SemaRef.Context, Record, 5720 D.getLocStart(), 5721 NameInfo, R, TInfo, isInline, 5722 /*isImplicitlyDeclared=*/false); 5723 5724 // If the class is complete, then we now create the implicit exception 5725 // specification. If the class is incomplete or dependent, we can't do 5726 // it yet. 5727 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 5728 Record->getDefinition() && !Record->isBeingDefined() && 5729 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5730 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5731 } 5732 5733 IsVirtualOkay = true; 5734 return NewDD; 5735 5736 } else { 5737 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5738 D.setInvalidType(); 5739 5740 // Create a FunctionDecl to satisfy the function definition parsing 5741 // code path. 5742 return FunctionDecl::Create(SemaRef.Context, DC, 5743 D.getLocStart(), 5744 D.getIdentifierLoc(), Name, R, TInfo, 5745 SC, isInline, 5746 /*hasPrototype=*/true, isConstexpr); 5747 } 5748 5749 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5750 if (!DC->isRecord()) { 5751 SemaRef.Diag(D.getIdentifierLoc(), 5752 diag::err_conv_function_not_member); 5753 return 0; 5754 } 5755 5756 SemaRef.CheckConversionDeclarator(D, R, SC); 5757 IsVirtualOkay = true; 5758 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5759 D.getLocStart(), NameInfo, 5760 R, TInfo, isInline, isExplicit, 5761 isConstexpr, SourceLocation()); 5762 5763 } else if (DC->isRecord()) { 5764 // If the name of the function is the same as the name of the record, 5765 // then this must be an invalid constructor that has a return type. 5766 // (The parser checks for a return type and makes the declarator a 5767 // constructor if it has no return type). 5768 if (Name.getAsIdentifierInfo() && 5769 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5770 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5771 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5772 << SourceRange(D.getIdentifierLoc()); 5773 return 0; 5774 } 5775 5776 // This is a C++ method declaration. 5777 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 5778 cast<CXXRecordDecl>(DC), 5779 D.getLocStart(), NameInfo, R, 5780 TInfo, SC, isInline, 5781 isConstexpr, SourceLocation()); 5782 IsVirtualOkay = !Ret->isStatic(); 5783 return Ret; 5784 } else { 5785 // Determine whether the function was written with a 5786 // prototype. This true when: 5787 // - we're in C++ (where every function has a prototype), 5788 return FunctionDecl::Create(SemaRef.Context, DC, 5789 D.getLocStart(), 5790 NameInfo, R, TInfo, SC, isInline, 5791 true/*HasPrototype*/, isConstexpr); 5792 } 5793} 5794 5795void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 5796 // In C++, the empty parameter-type-list must be spelled "void"; a 5797 // typedef of void is not permitted. 5798 if (getLangOpts().CPlusPlus && 5799 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5800 bool IsTypeAlias = false; 5801 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5802 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5803 else if (const TemplateSpecializationType *TST = 5804 Param->getType()->getAs<TemplateSpecializationType>()) 5805 IsTypeAlias = TST->isTypeAlias(); 5806 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5807 << IsTypeAlias; 5808 } 5809} 5810 5811NamedDecl* 5812Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5813 TypeSourceInfo *TInfo, LookupResult &Previous, 5814 MultiTemplateParamsArg TemplateParamLists, 5815 bool &AddToScope) { 5816 QualType R = TInfo->getType(); 5817 5818 assert(R.getTypePtr()->isFunctionType()); 5819 5820 // TODO: consider using NameInfo for diagnostic. 5821 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5822 DeclarationName Name = NameInfo.getName(); 5823 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5824 5825 if (D.getDeclSpec().isThreadSpecified()) 5826 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5827 5828 // Do not allow returning a objc interface by-value. 5829 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5830 Diag(D.getIdentifierLoc(), 5831 diag::err_object_cannot_be_passed_returned_by_value) << 0 5832 << R->getAs<FunctionType>()->getResultType() 5833 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5834 5835 QualType T = R->getAs<FunctionType>()->getResultType(); 5836 T = Context.getObjCObjectPointerType(T); 5837 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5838 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5839 R = Context.getFunctionType(T, 5840 ArrayRef<QualType>(FPT->arg_type_begin(), 5841 FPT->getNumArgs()), 5842 EPI); 5843 } 5844 else if (isa<FunctionNoProtoType>(R)) 5845 R = Context.getFunctionNoProtoType(T); 5846 } 5847 5848 bool isFriend = false; 5849 FunctionTemplateDecl *FunctionTemplate = 0; 5850 bool isExplicitSpecialization = false; 5851 bool isFunctionTemplateSpecialization = false; 5852 5853 bool isDependentClassScopeExplicitSpecialization = false; 5854 bool HasExplicitTemplateArgs = false; 5855 TemplateArgumentListInfo TemplateArgs; 5856 5857 bool isVirtualOkay = false; 5858 5859 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5860 isVirtualOkay); 5861 if (!NewFD) return 0; 5862 5863 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5864 NewFD->setTopLevelDeclInObjCContainer(); 5865 5866 if (getLangOpts().CPlusPlus) { 5867 bool isInline = D.getDeclSpec().isInlineSpecified(); 5868 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5869 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5870 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5871 isFriend = D.getDeclSpec().isFriendSpecified(); 5872 if (isFriend && !isInline && D.isFunctionDefinition()) { 5873 // C++ [class.friend]p5 5874 // A function can be defined in a friend declaration of a 5875 // class . . . . Such a function is implicitly inline. 5876 NewFD->setImplicitlyInline(); 5877 } 5878 5879 // If this is a method defined in an __interface, and is not a constructor 5880 // or an overloaded operator, then set the pure flag (isVirtual will already 5881 // return true). 5882 if (const CXXRecordDecl *Parent = 5883 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 5884 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 5885 NewFD->setPure(true); 5886 } 5887 5888 SetNestedNameSpecifier(NewFD, D); 5889 isExplicitSpecialization = false; 5890 isFunctionTemplateSpecialization = false; 5891 if (D.isInvalidType()) 5892 NewFD->setInvalidDecl(); 5893 5894 // Set the lexical context. If the declarator has a C++ 5895 // scope specifier, or is the object of a friend declaration, the 5896 // lexical context will be different from the semantic context. 5897 NewFD->setLexicalDeclContext(CurContext); 5898 5899 // Match up the template parameter lists with the scope specifier, then 5900 // determine whether we have a template or a template specialization. 5901 bool Invalid = false; 5902 if (TemplateParameterList *TemplateParams 5903 = MatchTemplateParametersToScopeSpecifier( 5904 D.getDeclSpec().getLocStart(), 5905 D.getIdentifierLoc(), 5906 D.getCXXScopeSpec(), 5907 TemplateParamLists.data(), 5908 TemplateParamLists.size(), 5909 isFriend, 5910 isExplicitSpecialization, 5911 Invalid)) { 5912 if (TemplateParams->size() > 0) { 5913 // This is a function template 5914 5915 // Check that we can declare a template here. 5916 if (CheckTemplateDeclScope(S, TemplateParams)) 5917 return 0; 5918 5919 // A destructor cannot be a template. 5920 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5921 Diag(NewFD->getLocation(), diag::err_destructor_template); 5922 return 0; 5923 } 5924 5925 // If we're adding a template to a dependent context, we may need to 5926 // rebuilding some of the types used within the template parameter list, 5927 // now that we know what the current instantiation is. 5928 if (DC->isDependentContext()) { 5929 ContextRAII SavedContext(*this, DC); 5930 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5931 Invalid = true; 5932 } 5933 5934 5935 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5936 NewFD->getLocation(), 5937 Name, TemplateParams, 5938 NewFD); 5939 FunctionTemplate->setLexicalDeclContext(CurContext); 5940 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5941 5942 // For source fidelity, store the other template param lists. 5943 if (TemplateParamLists.size() > 1) { 5944 NewFD->setTemplateParameterListsInfo(Context, 5945 TemplateParamLists.size() - 1, 5946 TemplateParamLists.data()); 5947 } 5948 } else { 5949 // This is a function template specialization. 5950 isFunctionTemplateSpecialization = true; 5951 // For source fidelity, store all the template param lists. 5952 NewFD->setTemplateParameterListsInfo(Context, 5953 TemplateParamLists.size(), 5954 TemplateParamLists.data()); 5955 5956 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5957 if (isFriend) { 5958 // We want to remove the "template<>", found here. 5959 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5960 5961 // If we remove the template<> and the name is not a 5962 // template-id, we're actually silently creating a problem: 5963 // the friend declaration will refer to an untemplated decl, 5964 // and clearly the user wants a template specialization. So 5965 // we need to insert '<>' after the name. 5966 SourceLocation InsertLoc; 5967 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5968 InsertLoc = D.getName().getSourceRange().getEnd(); 5969 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5970 } 5971 5972 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5973 << Name << RemoveRange 5974 << FixItHint::CreateRemoval(RemoveRange) 5975 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5976 } 5977 } 5978 } 5979 else { 5980 // All template param lists were matched against the scope specifier: 5981 // this is NOT (an explicit specialization of) a template. 5982 if (TemplateParamLists.size() > 0) 5983 // For source fidelity, store all the template param lists. 5984 NewFD->setTemplateParameterListsInfo(Context, 5985 TemplateParamLists.size(), 5986 TemplateParamLists.data()); 5987 } 5988 5989 if (Invalid) { 5990 NewFD->setInvalidDecl(); 5991 if (FunctionTemplate) 5992 FunctionTemplate->setInvalidDecl(); 5993 } 5994 5995 // C++ [dcl.fct.spec]p5: 5996 // The virtual specifier shall only be used in declarations of 5997 // nonstatic class member functions that appear within a 5998 // member-specification of a class declaration; see 10.3. 5999 // 6000 if (isVirtual && !NewFD->isInvalidDecl()) { 6001 if (!isVirtualOkay) { 6002 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6003 diag::err_virtual_non_function); 6004 } else if (!CurContext->isRecord()) { 6005 // 'virtual' was specified outside of the class. 6006 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6007 diag::err_virtual_out_of_class) 6008 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6009 } else if (NewFD->getDescribedFunctionTemplate()) { 6010 // C++ [temp.mem]p3: 6011 // A member function template shall not be virtual. 6012 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6013 diag::err_virtual_member_function_template) 6014 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6015 } else { 6016 // Okay: Add virtual to the method. 6017 NewFD->setVirtualAsWritten(true); 6018 } 6019 } 6020 6021 // C++ [dcl.fct.spec]p3: 6022 // The inline specifier shall not appear on a block scope function 6023 // declaration. 6024 if (isInline && !NewFD->isInvalidDecl()) { 6025 if (CurContext->isFunctionOrMethod()) { 6026 // 'inline' is not allowed on block scope function declaration. 6027 Diag(D.getDeclSpec().getInlineSpecLoc(), 6028 diag::err_inline_declaration_block_scope) << Name 6029 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6030 } 6031 } 6032 6033 // C++ [dcl.fct.spec]p6: 6034 // The explicit specifier shall be used only in the declaration of a 6035 // constructor or conversion function within its class definition; 6036 // see 12.3.1 and 12.3.2. 6037 if (isExplicit && !NewFD->isInvalidDecl()) { 6038 if (!CurContext->isRecord()) { 6039 // 'explicit' was specified outside of the class. 6040 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6041 diag::err_explicit_out_of_class) 6042 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6043 } else if (!isa<CXXConstructorDecl>(NewFD) && 6044 !isa<CXXConversionDecl>(NewFD)) { 6045 // 'explicit' was specified on a function that wasn't a constructor 6046 // or conversion function. 6047 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6048 diag::err_explicit_non_ctor_or_conv_function) 6049 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6050 } 6051 } 6052 6053 if (isConstexpr) { 6054 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6055 // are implicitly inline. 6056 NewFD->setImplicitlyInline(); 6057 6058 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6059 // be either constructors or to return a literal type. Therefore, 6060 // destructors cannot be declared constexpr. 6061 if (isa<CXXDestructorDecl>(NewFD)) 6062 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6063 } 6064 6065 // If __module_private__ was specified, mark the function accordingly. 6066 if (D.getDeclSpec().isModulePrivateSpecified()) { 6067 if (isFunctionTemplateSpecialization) { 6068 SourceLocation ModulePrivateLoc 6069 = D.getDeclSpec().getModulePrivateSpecLoc(); 6070 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6071 << 0 6072 << FixItHint::CreateRemoval(ModulePrivateLoc); 6073 } else { 6074 NewFD->setModulePrivate(); 6075 if (FunctionTemplate) 6076 FunctionTemplate->setModulePrivate(); 6077 } 6078 } 6079 6080 if (isFriend) { 6081 // For now, claim that the objects have no previous declaration. 6082 if (FunctionTemplate) { 6083 FunctionTemplate->setObjectOfFriendDecl(false); 6084 FunctionTemplate->setAccess(AS_public); 6085 } 6086 NewFD->setObjectOfFriendDecl(false); 6087 NewFD->setAccess(AS_public); 6088 } 6089 6090 // If a function is defined as defaulted or deleted, mark it as such now. 6091 switch (D.getFunctionDefinitionKind()) { 6092 case FDK_Declaration: 6093 case FDK_Definition: 6094 break; 6095 6096 case FDK_Defaulted: 6097 NewFD->setDefaulted(); 6098 break; 6099 6100 case FDK_Deleted: 6101 NewFD->setDeletedAsWritten(); 6102 break; 6103 } 6104 6105 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6106 D.isFunctionDefinition()) { 6107 // C++ [class.mfct]p2: 6108 // A member function may be defined (8.4) in its class definition, in 6109 // which case it is an inline member function (7.1.2) 6110 NewFD->setImplicitlyInline(); 6111 } 6112 6113 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6114 !CurContext->isRecord()) { 6115 // C++ [class.static]p1: 6116 // A data or function member of a class may be declared static 6117 // in a class definition, in which case it is a static member of 6118 // the class. 6119 6120 // Complain about the 'static' specifier if it's on an out-of-line 6121 // member function definition. 6122 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6123 diag::err_static_out_of_line) 6124 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6125 } 6126 6127 // C++11 [except.spec]p15: 6128 // A deallocation function with no exception-specification is treated 6129 // as if it were specified with noexcept(true). 6130 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6131 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6132 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6133 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6134 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6135 EPI.ExceptionSpecType = EST_BasicNoexcept; 6136 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6137 ArrayRef<QualType>(FPT->arg_type_begin(), 6138 FPT->getNumArgs()), 6139 EPI)); 6140 } 6141 } 6142 6143 // Filter out previous declarations that don't match the scope. 6144 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewFD), 6145 isExplicitSpecialization || 6146 isFunctionTemplateSpecialization); 6147 6148 // Handle GNU asm-label extension (encoded as an attribute). 6149 if (Expr *E = (Expr*) D.getAsmLabel()) { 6150 // The parser guarantees this is a string. 6151 StringLiteral *SE = cast<StringLiteral>(E); 6152 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6153 SE->getString())); 6154 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6155 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6156 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6157 if (I != ExtnameUndeclaredIdentifiers.end()) { 6158 NewFD->addAttr(I->second); 6159 ExtnameUndeclaredIdentifiers.erase(I); 6160 } 6161 } 6162 6163 // Copy the parameter declarations from the declarator D to the function 6164 // declaration NewFD, if they are available. First scavenge them into Params. 6165 SmallVector<ParmVarDecl*, 16> Params; 6166 if (D.isFunctionDeclarator()) { 6167 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6168 6169 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6170 // function that takes no arguments, not a function that takes a 6171 // single void argument. 6172 // We let through "const void" here because Sema::GetTypeForDeclarator 6173 // already checks for that case. 6174 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6175 FTI.ArgInfo[0].Param && 6176 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6177 // Empty arg list, don't push any params. 6178 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6179 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6180 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6181 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6182 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6183 Param->setDeclContext(NewFD); 6184 Params.push_back(Param); 6185 6186 if (Param->isInvalidDecl()) 6187 NewFD->setInvalidDecl(); 6188 } 6189 } 6190 6191 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6192 // When we're declaring a function with a typedef, typeof, etc as in the 6193 // following example, we'll need to synthesize (unnamed) 6194 // parameters for use in the declaration. 6195 // 6196 // @code 6197 // typedef void fn(int); 6198 // fn f; 6199 // @endcode 6200 6201 // Synthesize a parameter for each argument type. 6202 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6203 AE = FT->arg_type_end(); AI != AE; ++AI) { 6204 ParmVarDecl *Param = 6205 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6206 Param->setScopeInfo(0, Params.size()); 6207 Params.push_back(Param); 6208 } 6209 } else { 6210 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6211 "Should not need args for typedef of non-prototype fn"); 6212 } 6213 6214 // Finally, we know we have the right number of parameters, install them. 6215 NewFD->setParams(Params); 6216 6217 // Find all anonymous symbols defined during the declaration of this function 6218 // and add to NewFD. This lets us track decls such 'enum Y' in: 6219 // 6220 // void f(enum Y {AA} x) {} 6221 // 6222 // which would otherwise incorrectly end up in the translation unit scope. 6223 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6224 DeclsInPrototypeScope.clear(); 6225 6226 if (D.getDeclSpec().isNoreturnSpecified()) 6227 NewFD->addAttr( 6228 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6229 Context)); 6230 6231 // Process the non-inheritable attributes on this declaration. 6232 ProcessDeclAttributes(S, NewFD, D, 6233 /*NonInheritable=*/true, /*Inheritable=*/false); 6234 6235 // Functions returning a variably modified type violate C99 6.7.5.2p2 6236 // because all functions have linkage. 6237 if (!NewFD->isInvalidDecl() && 6238 NewFD->getResultType()->isVariablyModifiedType()) { 6239 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6240 NewFD->setInvalidDecl(); 6241 } 6242 6243 // Handle attributes. 6244 ProcessDeclAttributes(S, NewFD, D, 6245 /*NonInheritable=*/false, /*Inheritable=*/true); 6246 6247 QualType RetType = NewFD->getResultType(); 6248 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6249 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6250 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6251 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6252 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6253 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) { 6254 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6255 Context)); 6256 } 6257 } 6258 6259 if (!getLangOpts().CPlusPlus) { 6260 // Perform semantic checking on the function declaration. 6261 bool isExplicitSpecialization=false; 6262 if (!NewFD->isInvalidDecl()) { 6263 if (NewFD->isMain()) 6264 CheckMain(NewFD, D.getDeclSpec()); 6265 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6266 isExplicitSpecialization)); 6267 } 6268 // Make graceful recovery from an invalid redeclaration. 6269 else if (!Previous.empty()) 6270 D.setRedeclaration(true); 6271 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6272 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6273 "previous declaration set still overloaded"); 6274 } else { 6275 // If the declarator is a template-id, translate the parser's template 6276 // argument list into our AST format. 6277 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6278 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 6279 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 6280 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 6281 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6282 TemplateId->NumArgs); 6283 translateTemplateArguments(TemplateArgsPtr, 6284 TemplateArgs); 6285 6286 HasExplicitTemplateArgs = true; 6287 6288 if (NewFD->isInvalidDecl()) { 6289 HasExplicitTemplateArgs = false; 6290 } else if (FunctionTemplate) { 6291 // Function template with explicit template arguments. 6292 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 6293 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 6294 6295 HasExplicitTemplateArgs = false; 6296 } else if (!isFunctionTemplateSpecialization && 6297 !D.getDeclSpec().isFriendSpecified()) { 6298 // We have encountered something that the user meant to be a 6299 // specialization (because it has explicitly-specified template 6300 // arguments) but that was not introduced with a "template<>" (or had 6301 // too few of them). 6302 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 6303 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 6304 << FixItHint::CreateInsertion( 6305 D.getDeclSpec().getLocStart(), 6306 "template<> "); 6307 isFunctionTemplateSpecialization = true; 6308 } else { 6309 // "friend void foo<>(int);" is an implicit specialization decl. 6310 isFunctionTemplateSpecialization = true; 6311 } 6312 } else if (isFriend && isFunctionTemplateSpecialization) { 6313 // This combination is only possible in a recovery case; the user 6314 // wrote something like: 6315 // template <> friend void foo(int); 6316 // which we're recovering from as if the user had written: 6317 // friend void foo<>(int); 6318 // Go ahead and fake up a template id. 6319 HasExplicitTemplateArgs = true; 6320 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 6321 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 6322 } 6323 6324 // If it's a friend (and only if it's a friend), it's possible 6325 // that either the specialized function type or the specialized 6326 // template is dependent, and therefore matching will fail. In 6327 // this case, don't check the specialization yet. 6328 bool InstantiationDependent = false; 6329 if (isFunctionTemplateSpecialization && isFriend && 6330 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 6331 TemplateSpecializationType::anyDependentTemplateArguments( 6332 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 6333 InstantiationDependent))) { 6334 assert(HasExplicitTemplateArgs && 6335 "friend function specialization without template args"); 6336 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 6337 Previous)) 6338 NewFD->setInvalidDecl(); 6339 } else if (isFunctionTemplateSpecialization) { 6340 if (CurContext->isDependentContext() && CurContext->isRecord() 6341 && !isFriend) { 6342 isDependentClassScopeExplicitSpecialization = true; 6343 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 6344 diag::ext_function_specialization_in_class : 6345 diag::err_function_specialization_in_class) 6346 << NewFD->getDeclName(); 6347 } else if (CheckFunctionTemplateSpecialization(NewFD, 6348 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 6349 Previous)) 6350 NewFD->setInvalidDecl(); 6351 6352 // C++ [dcl.stc]p1: 6353 // A storage-class-specifier shall not be specified in an explicit 6354 // specialization (14.7.3) 6355 if (SC != SC_None) { 6356 if (SC != NewFD->getTemplateSpecializationInfo()->getTemplate()->getTemplatedDecl()->getStorageClass()) 6357 Diag(NewFD->getLocation(), 6358 diag::err_explicit_specialization_inconsistent_storage_class) 6359 << SC 6360 << FixItHint::CreateRemoval( 6361 D.getDeclSpec().getStorageClassSpecLoc()); 6362 6363 else 6364 Diag(NewFD->getLocation(), 6365 diag::ext_explicit_specialization_storage_class) 6366 << FixItHint::CreateRemoval( 6367 D.getDeclSpec().getStorageClassSpecLoc()); 6368 } 6369 6370 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 6371 if (CheckMemberSpecialization(NewFD, Previous)) 6372 NewFD->setInvalidDecl(); 6373 } 6374 6375 // Perform semantic checking on the function declaration. 6376 if (!isDependentClassScopeExplicitSpecialization) { 6377 if (NewFD->isInvalidDecl()) { 6378 // If this is a class member, mark the class invalid immediately. 6379 // This avoids some consistency errors later. 6380 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 6381 methodDecl->getParent()->setInvalidDecl(); 6382 } else { 6383 if (NewFD->isMain()) 6384 CheckMain(NewFD, D.getDeclSpec()); 6385 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6386 isExplicitSpecialization)); 6387 } 6388 } 6389 6390 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6391 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6392 "previous declaration set still overloaded"); 6393 6394 NamedDecl *PrincipalDecl = (FunctionTemplate 6395 ? cast<NamedDecl>(FunctionTemplate) 6396 : NewFD); 6397 6398 if (isFriend && D.isRedeclaration()) { 6399 AccessSpecifier Access = AS_public; 6400 if (!NewFD->isInvalidDecl()) 6401 Access = NewFD->getPreviousDecl()->getAccess(); 6402 6403 NewFD->setAccess(Access); 6404 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 6405 6406 PrincipalDecl->setObjectOfFriendDecl(true); 6407 } 6408 6409 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 6410 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 6411 PrincipalDecl->setNonMemberOperator(); 6412 6413 // If we have a function template, check the template parameter 6414 // list. This will check and merge default template arguments. 6415 if (FunctionTemplate) { 6416 FunctionTemplateDecl *PrevTemplate = 6417 FunctionTemplate->getPreviousDecl(); 6418 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 6419 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 6420 D.getDeclSpec().isFriendSpecified() 6421 ? (D.isFunctionDefinition() 6422 ? TPC_FriendFunctionTemplateDefinition 6423 : TPC_FriendFunctionTemplate) 6424 : (D.getCXXScopeSpec().isSet() && 6425 DC && DC->isRecord() && 6426 DC->isDependentContext()) 6427 ? TPC_ClassTemplateMember 6428 : TPC_FunctionTemplate); 6429 } 6430 6431 if (NewFD->isInvalidDecl()) { 6432 // Ignore all the rest of this. 6433 } else if (!D.isRedeclaration()) { 6434 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 6435 AddToScope }; 6436 // Fake up an access specifier if it's supposed to be a class member. 6437 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 6438 NewFD->setAccess(AS_public); 6439 6440 // Qualified decls generally require a previous declaration. 6441 if (D.getCXXScopeSpec().isSet()) { 6442 // ...with the major exception of templated-scope or 6443 // dependent-scope friend declarations. 6444 6445 // TODO: we currently also suppress this check in dependent 6446 // contexts because (1) the parameter depth will be off when 6447 // matching friend templates and (2) we might actually be 6448 // selecting a friend based on a dependent factor. But there 6449 // are situations where these conditions don't apply and we 6450 // can actually do this check immediately. 6451 if (isFriend && 6452 (TemplateParamLists.size() || 6453 D.getCXXScopeSpec().getScopeRep()->isDependent() || 6454 CurContext->isDependentContext())) { 6455 // ignore these 6456 } else { 6457 // The user tried to provide an out-of-line definition for a 6458 // function that is a member of a class or namespace, but there 6459 // was no such member function declared (C++ [class.mfct]p2, 6460 // C++ [namespace.memdef]p2). For example: 6461 // 6462 // class X { 6463 // void f() const; 6464 // }; 6465 // 6466 // void X::f() { } // ill-formed 6467 // 6468 // Complain about this problem, and attempt to suggest close 6469 // matches (e.g., those that differ only in cv-qualifiers and 6470 // whether the parameter types are references). 6471 6472 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6473 NewFD, 6474 ExtraArgs)) { 6475 AddToScope = ExtraArgs.AddToScope; 6476 return Result; 6477 } 6478 } 6479 6480 // Unqualified local friend declarations are required to resolve 6481 // to something. 6482 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 6483 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6484 NewFD, 6485 ExtraArgs)) { 6486 AddToScope = ExtraArgs.AddToScope; 6487 return Result; 6488 } 6489 } 6490 6491 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 6492 !isFriend && !isFunctionTemplateSpecialization && 6493 !isExplicitSpecialization) { 6494 // An out-of-line member function declaration must also be a 6495 // definition (C++ [dcl.meaning]p1). 6496 // Note that this is not the case for explicit specializations of 6497 // function templates or member functions of class templates, per 6498 // C++ [temp.expl.spec]p2. We also allow these declarations as an 6499 // extension for compatibility with old SWIG code which likes to 6500 // generate them. 6501 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 6502 << D.getCXXScopeSpec().getRange(); 6503 } 6504 } 6505 6506 ProcessPragmaWeak(S, NewFD); 6507 checkAttributesAfterMerging(*this, *NewFD); 6508 6509 AddKnownFunctionAttributes(NewFD); 6510 6511 if (NewFD->hasAttr<OverloadableAttr>() && 6512 !NewFD->getType()->getAs<FunctionProtoType>()) { 6513 Diag(NewFD->getLocation(), 6514 diag::err_attribute_overloadable_no_prototype) 6515 << NewFD; 6516 6517 // Turn this into a variadic function with no parameters. 6518 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 6519 FunctionProtoType::ExtProtoInfo EPI; 6520 EPI.Variadic = true; 6521 EPI.ExtInfo = FT->getExtInfo(); 6522 6523 QualType R = Context.getFunctionType(FT->getResultType(), 6524 ArrayRef<QualType>(), 6525 EPI); 6526 NewFD->setType(R); 6527 } 6528 6529 // If there's a #pragma GCC visibility in scope, and this isn't a class 6530 // member, set the visibility of this function. 6531 if (!DC->isRecord() && NewFD->hasExternalLinkage()) 6532 AddPushedVisibilityAttribute(NewFD); 6533 6534 // If there's a #pragma clang arc_cf_code_audited in scope, consider 6535 // marking the function. 6536 AddCFAuditedAttribute(NewFD); 6537 6538 // If this is a locally-scoped extern C function, update the 6539 // map of such names. 6540 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 6541 && !NewFD->isInvalidDecl()) 6542 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 6543 6544 // Set this FunctionDecl's range up to the right paren. 6545 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 6546 6547 if (getLangOpts().CPlusPlus) { 6548 if (FunctionTemplate) { 6549 if (NewFD->isInvalidDecl()) 6550 FunctionTemplate->setInvalidDecl(); 6551 return FunctionTemplate; 6552 } 6553 } 6554 6555 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 6556 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 6557 if ((getLangOpts().OpenCLVersion >= 120) 6558 && (SC == SC_Static)) { 6559 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 6560 D.setInvalidType(); 6561 } 6562 6563 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 6564 if (!NewFD->getResultType()->isVoidType()) { 6565 Diag(D.getIdentifierLoc(), 6566 diag::err_expected_kernel_void_return_type); 6567 D.setInvalidType(); 6568 } 6569 6570 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 6571 PE = NewFD->param_end(); PI != PE; ++PI) { 6572 ParmVarDecl *Param = *PI; 6573 QualType PT = Param->getType(); 6574 6575 // OpenCL v1.2 s6.9.a: 6576 // A kernel function argument cannot be declared as a 6577 // pointer to a pointer type. 6578 if (PT->isPointerType() && PT->getPointeeType()->isPointerType()) { 6579 Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_arg); 6580 D.setInvalidType(); 6581 } 6582 6583 // OpenCL v1.2 s6.8 n: 6584 // A kernel function argument cannot be declared 6585 // of event_t type. 6586 if (PT->isEventT()) { 6587 Diag(Param->getLocation(), diag::err_event_t_kernel_arg); 6588 D.setInvalidType(); 6589 } 6590 } 6591 } 6592 6593 MarkUnusedFileScopedDecl(NewFD); 6594 6595 if (getLangOpts().CUDA) 6596 if (IdentifierInfo *II = NewFD->getIdentifier()) 6597 if (!NewFD->isInvalidDecl() && 6598 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6599 if (II->isStr("cudaConfigureCall")) { 6600 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 6601 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 6602 6603 Context.setcudaConfigureCallDecl(NewFD); 6604 } 6605 } 6606 6607 // Here we have an function template explicit specialization at class scope. 6608 // The actually specialization will be postponed to template instatiation 6609 // time via the ClassScopeFunctionSpecializationDecl node. 6610 if (isDependentClassScopeExplicitSpecialization) { 6611 ClassScopeFunctionSpecializationDecl *NewSpec = 6612 ClassScopeFunctionSpecializationDecl::Create( 6613 Context, CurContext, SourceLocation(), 6614 cast<CXXMethodDecl>(NewFD), 6615 HasExplicitTemplateArgs, TemplateArgs); 6616 CurContext->addDecl(NewSpec); 6617 AddToScope = false; 6618 } 6619 6620 return NewFD; 6621} 6622 6623/// \brief Perform semantic checking of a new function declaration. 6624/// 6625/// Performs semantic analysis of the new function declaration 6626/// NewFD. This routine performs all semantic checking that does not 6627/// require the actual declarator involved in the declaration, and is 6628/// used both for the declaration of functions as they are parsed 6629/// (called via ActOnDeclarator) and for the declaration of functions 6630/// that have been instantiated via C++ template instantiation (called 6631/// via InstantiateDecl). 6632/// 6633/// \param IsExplicitSpecialization whether this new function declaration is 6634/// an explicit specialization of the previous declaration. 6635/// 6636/// This sets NewFD->isInvalidDecl() to true if there was an error. 6637/// 6638/// \returns true if the function declaration is a redeclaration. 6639bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 6640 LookupResult &Previous, 6641 bool IsExplicitSpecialization) { 6642 assert(!NewFD->getResultType()->isVariablyModifiedType() 6643 && "Variably modified return types are not handled here"); 6644 6645 // Check for a previous declaration of this name. 6646 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) { 6647 // Since we did not find anything by this name, look for a non-visible 6648 // extern "C" declaration with the same name. 6649 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6650 = findLocallyScopedExternCDecl(NewFD->getDeclName()); 6651 if (Pos != LocallyScopedExternCDecls.end()) 6652 Previous.addDecl(Pos->second); 6653 } 6654 6655 // Filter out any non-conflicting previous declarations. 6656 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 6657 6658 bool Redeclaration = false; 6659 NamedDecl *OldDecl = 0; 6660 6661 // Merge or overload the declaration with an existing declaration of 6662 // the same name, if appropriate. 6663 if (!Previous.empty()) { 6664 // Determine whether NewFD is an overload of PrevDecl or 6665 // a declaration that requires merging. If it's an overload, 6666 // there's no more work to do here; we'll just add the new 6667 // function to the scope. 6668 if (!AllowOverloadingOfFunction(Previous, Context)) { 6669 Redeclaration = true; 6670 OldDecl = Previous.getFoundDecl(); 6671 } else { 6672 switch (CheckOverload(S, NewFD, Previous, OldDecl, 6673 /*NewIsUsingDecl*/ false)) { 6674 case Ovl_Match: 6675 Redeclaration = true; 6676 break; 6677 6678 case Ovl_NonFunction: 6679 Redeclaration = true; 6680 break; 6681 6682 case Ovl_Overload: 6683 Redeclaration = false; 6684 break; 6685 } 6686 6687 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 6688 // If a function name is overloadable in C, then every function 6689 // with that name must be marked "overloadable". 6690 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 6691 << Redeclaration << NewFD; 6692 NamedDecl *OverloadedDecl = 0; 6693 if (Redeclaration) 6694 OverloadedDecl = OldDecl; 6695 else if (!Previous.empty()) 6696 OverloadedDecl = Previous.getRepresentativeDecl(); 6697 if (OverloadedDecl) 6698 Diag(OverloadedDecl->getLocation(), 6699 diag::note_attribute_overloadable_prev_overload); 6700 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 6701 Context)); 6702 } 6703 } 6704 } 6705 6706 // C++11 [dcl.constexpr]p8: 6707 // A constexpr specifier for a non-static member function that is not 6708 // a constructor declares that member function to be const. 6709 // 6710 // This needs to be delayed until we know whether this is an out-of-line 6711 // definition of a static member function. 6712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6713 if (MD && MD->isConstexpr() && !MD->isStatic() && 6714 !isa<CXXConstructorDecl>(MD) && 6715 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 6716 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 6717 if (FunctionTemplateDecl *OldTD = 6718 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 6719 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 6720 if (!OldMD || !OldMD->isStatic()) { 6721 const FunctionProtoType *FPT = 6722 MD->getType()->castAs<FunctionProtoType>(); 6723 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6724 EPI.TypeQuals |= Qualifiers::Const; 6725 MD->setType(Context.getFunctionType(FPT->getResultType(), 6726 ArrayRef<QualType>(FPT->arg_type_begin(), 6727 FPT->getNumArgs()), 6728 EPI)); 6729 } 6730 } 6731 6732 if (Redeclaration) { 6733 // NewFD and OldDecl represent declarations that need to be 6734 // merged. 6735 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 6736 NewFD->setInvalidDecl(); 6737 return Redeclaration; 6738 } 6739 6740 Previous.clear(); 6741 Previous.addDecl(OldDecl); 6742 6743 if (FunctionTemplateDecl *OldTemplateDecl 6744 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 6745 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 6746 FunctionTemplateDecl *NewTemplateDecl 6747 = NewFD->getDescribedFunctionTemplate(); 6748 assert(NewTemplateDecl && "Template/non-template mismatch"); 6749 if (CXXMethodDecl *Method 6750 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 6751 Method->setAccess(OldTemplateDecl->getAccess()); 6752 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 6753 } 6754 6755 // If this is an explicit specialization of a member that is a function 6756 // template, mark it as a member specialization. 6757 if (IsExplicitSpecialization && 6758 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 6759 NewTemplateDecl->setMemberSpecialization(); 6760 assert(OldTemplateDecl->isMemberSpecialization()); 6761 } 6762 6763 } else { 6764 // This needs to happen first so that 'inline' propagates. 6765 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 6766 6767 if (isa<CXXMethodDecl>(NewFD)) { 6768 // A valid redeclaration of a C++ method must be out-of-line, 6769 // but (unfortunately) it's not necessarily a definition 6770 // because of templates, which means that the previous 6771 // declaration is not necessarily from the class definition. 6772 6773 // For just setting the access, that doesn't matter. 6774 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 6775 NewFD->setAccess(oldMethod->getAccess()); 6776 6777 // Update the key-function state if necessary for this ABI. 6778 if (NewFD->isInlined() && 6779 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 6780 // setNonKeyFunction needs to work with the original 6781 // declaration from the class definition, and isVirtual() is 6782 // just faster in that case, so map back to that now. 6783 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration()); 6784 if (oldMethod->isVirtual()) { 6785 Context.setNonKeyFunction(oldMethod); 6786 } 6787 } 6788 } 6789 } 6790 } 6791 6792 // Semantic checking for this function declaration (in isolation). 6793 if (getLangOpts().CPlusPlus) { 6794 // C++-specific checks. 6795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 6796 CheckConstructor(Constructor); 6797 } else if (CXXDestructorDecl *Destructor = 6798 dyn_cast<CXXDestructorDecl>(NewFD)) { 6799 CXXRecordDecl *Record = Destructor->getParent(); 6800 QualType ClassType = Context.getTypeDeclType(Record); 6801 6802 // FIXME: Shouldn't we be able to perform this check even when the class 6803 // type is dependent? Both gcc and edg can handle that. 6804 if (!ClassType->isDependentType()) { 6805 DeclarationName Name 6806 = Context.DeclarationNames.getCXXDestructorName( 6807 Context.getCanonicalType(ClassType)); 6808 if (NewFD->getDeclName() != Name) { 6809 Diag(NewFD->getLocation(), diag::err_destructor_name); 6810 NewFD->setInvalidDecl(); 6811 return Redeclaration; 6812 } 6813 } 6814 } else if (CXXConversionDecl *Conversion 6815 = dyn_cast<CXXConversionDecl>(NewFD)) { 6816 ActOnConversionDeclarator(Conversion); 6817 } 6818 6819 // Find any virtual functions that this function overrides. 6820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 6821 if (!Method->isFunctionTemplateSpecialization() && 6822 !Method->getDescribedFunctionTemplate() && 6823 Method->isCanonicalDecl()) { 6824 if (AddOverriddenMethods(Method->getParent(), Method)) { 6825 // If the function was marked as "static", we have a problem. 6826 if (NewFD->getStorageClass() == SC_Static) { 6827 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 6828 } 6829 } 6830 } 6831 6832 if (Method->isStatic()) 6833 checkThisInStaticMemberFunctionType(Method); 6834 } 6835 6836 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6837 if (NewFD->isOverloadedOperator() && 6838 CheckOverloadedOperatorDeclaration(NewFD)) { 6839 NewFD->setInvalidDecl(); 6840 return Redeclaration; 6841 } 6842 6843 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6844 if (NewFD->getLiteralIdentifier() && 6845 CheckLiteralOperatorDeclaration(NewFD)) { 6846 NewFD->setInvalidDecl(); 6847 return Redeclaration; 6848 } 6849 6850 // In C++, check default arguments now that we have merged decls. Unless 6851 // the lexical context is the class, because in this case this is done 6852 // during delayed parsing anyway. 6853 if (!CurContext->isRecord()) 6854 CheckCXXDefaultArguments(NewFD); 6855 6856 // If this function declares a builtin function, check the type of this 6857 // declaration against the expected type for the builtin. 6858 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6859 ASTContext::GetBuiltinTypeError Error; 6860 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 6861 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6862 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6863 // The type of this function differs from the type of the builtin, 6864 // so forget about the builtin entirely. 6865 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6866 } 6867 } 6868 6869 // If this function is declared as being extern "C", then check to see if 6870 // the function returns a UDT (class, struct, or union type) that is not C 6871 // compatible, and if it does, warn the user. 6872 // But, issue any diagnostic on the first declaration only. 6873 if (NewFD->isExternC() && Previous.empty()) { 6874 QualType R = NewFD->getResultType(); 6875 if (R->isIncompleteType() && !R->isVoidType()) 6876 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6877 << NewFD << R; 6878 else if (!R.isPODType(Context) && !R->isVoidType() && 6879 !R->isObjCObjectPointerType()) 6880 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6881 } 6882 } 6883 return Redeclaration; 6884} 6885 6886static SourceRange getResultSourceRange(const FunctionDecl *FD) { 6887 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6888 if (!TSI) 6889 return SourceRange(); 6890 6891 TypeLoc TL = TSI->getTypeLoc(); 6892 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 6893 if (!FunctionTL) 6894 return SourceRange(); 6895 6896 TypeLoc ResultTL = FunctionTL.getResultLoc(); 6897 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 6898 return ResultTL.getSourceRange(); 6899 6900 return SourceRange(); 6901} 6902 6903void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6904 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6905 // static or constexpr is ill-formed. 6906 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 6907 // appear in a declaration of main. 6908 // static main is not an error under C99, but we should warn about it. 6909 // We accept _Noreturn main as an extension. 6910 if (FD->getStorageClass() == SC_Static) 6911 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6912 ? diag::err_static_main : diag::warn_static_main) 6913 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6914 if (FD->isInlineSpecified()) 6915 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6916 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6917 if (DS.isNoreturnSpecified()) { 6918 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 6919 SourceRange NoreturnRange(NoreturnLoc, 6920 PP.getLocForEndOfToken(NoreturnLoc)); 6921 Diag(NoreturnLoc, diag::ext_noreturn_main); 6922 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 6923 << FixItHint::CreateRemoval(NoreturnRange); 6924 } 6925 if (FD->isConstexpr()) { 6926 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6927 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6928 FD->setConstexpr(false); 6929 } 6930 6931 QualType T = FD->getType(); 6932 assert(T->isFunctionType() && "function decl is not of function type"); 6933 const FunctionType* FT = T->castAs<FunctionType>(); 6934 6935 // All the standards say that main() should should return 'int'. 6936 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6937 // In C and C++, main magically returns 0 if you fall off the end; 6938 // set the flag which tells us that. 6939 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6940 FD->setHasImplicitReturnZero(true); 6941 6942 // In C with GNU extensions we allow main() to have non-integer return 6943 // type, but we should warn about the extension, and we disable the 6944 // implicit-return-zero rule. 6945 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6946 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6947 6948 SourceRange ResultRange = getResultSourceRange(FD); 6949 if (ResultRange.isValid()) 6950 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 6951 << FixItHint::CreateReplacement(ResultRange, "int"); 6952 6953 // Otherwise, this is just a flat-out error. 6954 } else { 6955 SourceRange ResultRange = getResultSourceRange(FD); 6956 if (ResultRange.isValid()) 6957 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 6958 << FixItHint::CreateReplacement(ResultRange, "int"); 6959 else 6960 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6961 6962 FD->setInvalidDecl(true); 6963 } 6964 6965 // Treat protoless main() as nullary. 6966 if (isa<FunctionNoProtoType>(FT)) return; 6967 6968 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6969 unsigned nparams = FTP->getNumArgs(); 6970 assert(FD->getNumParams() == nparams); 6971 6972 bool HasExtraParameters = (nparams > 3); 6973 6974 // Darwin passes an undocumented fourth argument of type char**. If 6975 // other platforms start sprouting these, the logic below will start 6976 // getting shifty. 6977 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6978 HasExtraParameters = false; 6979 6980 if (HasExtraParameters) { 6981 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6982 FD->setInvalidDecl(true); 6983 nparams = 3; 6984 } 6985 6986 // FIXME: a lot of the following diagnostics would be improved 6987 // if we had some location information about types. 6988 6989 QualType CharPP = 6990 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6991 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6992 6993 for (unsigned i = 0; i < nparams; ++i) { 6994 QualType AT = FTP->getArgType(i); 6995 6996 bool mismatch = true; 6997 6998 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6999 mismatch = false; 7000 else if (Expected[i] == CharPP) { 7001 // As an extension, the following forms are okay: 7002 // char const ** 7003 // char const * const * 7004 // char * const * 7005 7006 QualifierCollector qs; 7007 const PointerType* PT; 7008 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7009 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7010 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7011 Context.CharTy)) { 7012 qs.removeConst(); 7013 mismatch = !qs.empty(); 7014 } 7015 } 7016 7017 if (mismatch) { 7018 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7019 // TODO: suggest replacing given type with expected type 7020 FD->setInvalidDecl(true); 7021 } 7022 } 7023 7024 if (nparams == 1 && !FD->isInvalidDecl()) { 7025 Diag(FD->getLocation(), diag::warn_main_one_arg); 7026 } 7027 7028 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7029 Diag(FD->getLocation(), diag::err_main_template_decl); 7030 FD->setInvalidDecl(); 7031 } 7032} 7033 7034bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7035 // FIXME: Need strict checking. In C89, we need to check for 7036 // any assignment, increment, decrement, function-calls, or 7037 // commas outside of a sizeof. In C99, it's the same list, 7038 // except that the aforementioned are allowed in unevaluated 7039 // expressions. Everything else falls under the 7040 // "may accept other forms of constant expressions" exception. 7041 // (We never end up here for C++, so the constant expression 7042 // rules there don't matter.) 7043 if (Init->isConstantInitializer(Context, false)) 7044 return false; 7045 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7046 << Init->getSourceRange(); 7047 return true; 7048} 7049 7050namespace { 7051 // Visits an initialization expression to see if OrigDecl is evaluated in 7052 // its own initialization and throws a warning if it does. 7053 class SelfReferenceChecker 7054 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7055 Sema &S; 7056 Decl *OrigDecl; 7057 bool isRecordType; 7058 bool isPODType; 7059 bool isReferenceType; 7060 7061 public: 7062 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7063 7064 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7065 S(S), OrigDecl(OrigDecl) { 7066 isPODType = false; 7067 isRecordType = false; 7068 isReferenceType = false; 7069 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7070 isPODType = VD->getType().isPODType(S.Context); 7071 isRecordType = VD->getType()->isRecordType(); 7072 isReferenceType = VD->getType()->isReferenceType(); 7073 } 7074 } 7075 7076 // For most expressions, the cast is directly above the DeclRefExpr. 7077 // For conditional operators, the cast can be outside the conditional 7078 // operator if both expressions are DeclRefExpr's. 7079 void HandleValue(Expr *E) { 7080 if (isReferenceType) 7081 return; 7082 E = E->IgnoreParenImpCasts(); 7083 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7084 HandleDeclRefExpr(DRE); 7085 return; 7086 } 7087 7088 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7089 HandleValue(CO->getTrueExpr()); 7090 HandleValue(CO->getFalseExpr()); 7091 return; 7092 } 7093 7094 if (isa<MemberExpr>(E)) { 7095 Expr *Base = E->IgnoreParenImpCasts(); 7096 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7097 // Check for static member variables and don't warn on them. 7098 if (!isa<FieldDecl>(ME->getMemberDecl())) 7099 return; 7100 Base = ME->getBase()->IgnoreParenImpCasts(); 7101 } 7102 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7103 HandleDeclRefExpr(DRE); 7104 return; 7105 } 7106 } 7107 7108 // Reference types are handled here since all uses of references are 7109 // bad, not just r-value uses. 7110 void VisitDeclRefExpr(DeclRefExpr *E) { 7111 if (isReferenceType) 7112 HandleDeclRefExpr(E); 7113 } 7114 7115 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7116 if (E->getCastKind() == CK_LValueToRValue || 7117 (isRecordType && E->getCastKind() == CK_NoOp)) 7118 HandleValue(E->getSubExpr()); 7119 7120 Inherited::VisitImplicitCastExpr(E); 7121 } 7122 7123 void VisitMemberExpr(MemberExpr *E) { 7124 // Don't warn on arrays since they can be treated as pointers. 7125 if (E->getType()->canDecayToPointerType()) return; 7126 7127 // Warn when a non-static method call is followed by non-static member 7128 // field accesses, which is followed by a DeclRefExpr. 7129 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7130 bool Warn = (MD && !MD->isStatic()); 7131 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7132 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7133 if (!isa<FieldDecl>(ME->getMemberDecl())) 7134 Warn = false; 7135 Base = ME->getBase()->IgnoreParenImpCasts(); 7136 } 7137 7138 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7139 if (Warn) 7140 HandleDeclRefExpr(DRE); 7141 return; 7142 } 7143 7144 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7145 // Visit that expression. 7146 Visit(Base); 7147 } 7148 7149 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7150 if (E->getNumArgs() > 0) 7151 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7152 HandleDeclRefExpr(DRE); 7153 7154 Inherited::VisitCXXOperatorCallExpr(E); 7155 } 7156 7157 void VisitUnaryOperator(UnaryOperator *E) { 7158 // For POD record types, addresses of its own members are well-defined. 7159 if (E->getOpcode() == UO_AddrOf && isRecordType && 7160 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7161 if (!isPODType) 7162 HandleValue(E->getSubExpr()); 7163 return; 7164 } 7165 Inherited::VisitUnaryOperator(E); 7166 } 7167 7168 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7169 7170 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7171 Decl* ReferenceDecl = DRE->getDecl(); 7172 if (OrigDecl != ReferenceDecl) return; 7173 unsigned diag; 7174 if (isReferenceType) { 7175 diag = diag::warn_uninit_self_reference_in_reference_init; 7176 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7177 diag = diag::warn_static_self_reference_in_init; 7178 } else { 7179 diag = diag::warn_uninit_self_reference_in_init; 7180 } 7181 7182 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7183 S.PDiag(diag) 7184 << DRE->getNameInfo().getName() 7185 << OrigDecl->getLocation() 7186 << DRE->getSourceRange()); 7187 } 7188 }; 7189 7190 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7191 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7192 bool DirectInit) { 7193 // Parameters arguments are occassionially constructed with itself, 7194 // for instance, in recursive functions. Skip them. 7195 if (isa<ParmVarDecl>(OrigDecl)) 7196 return; 7197 7198 E = E->IgnoreParens(); 7199 7200 // Skip checking T a = a where T is not a record or reference type. 7201 // Doing so is a way to silence uninitialized warnings. 7202 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7204 if (ICE->getCastKind() == CK_LValueToRValue) 7205 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7206 if (DRE->getDecl() == OrigDecl) 7207 return; 7208 7209 SelfReferenceChecker(S, OrigDecl).Visit(E); 7210 } 7211} 7212 7213/// AddInitializerToDecl - Adds the initializer Init to the 7214/// declaration dcl. If DirectInit is true, this is C++ direct 7215/// initialization rather than copy initialization. 7216void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 7217 bool DirectInit, bool TypeMayContainAuto) { 7218 // If there is no declaration, there was an error parsing it. Just ignore 7219 // the initializer. 7220 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 7221 return; 7222 7223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 7224 // With declarators parsed the way they are, the parser cannot 7225 // distinguish between a normal initializer and a pure-specifier. 7226 // Thus this grotesque test. 7227 IntegerLiteral *IL; 7228 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 7229 Context.getCanonicalType(IL->getType()) == Context.IntTy) 7230 CheckPureMethod(Method, Init->getSourceRange()); 7231 else { 7232 Diag(Method->getLocation(), diag::err_member_function_initialization) 7233 << Method->getDeclName() << Init->getSourceRange(); 7234 Method->setInvalidDecl(); 7235 } 7236 return; 7237 } 7238 7239 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 7240 if (!VDecl) { 7241 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 7242 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 7243 RealDecl->setInvalidDecl(); 7244 return; 7245 } 7246 7247 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 7248 7249 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 7250 AutoType *Auto = 0; 7251 if (TypeMayContainAuto && 7252 (Auto = VDecl->getType()->getContainedAutoType()) && 7253 !Auto->isDeduced()) { 7254 Expr *DeduceInit = Init; 7255 // Initializer could be a C++ direct-initializer. Deduction only works if it 7256 // contains exactly one expression. 7257 if (CXXDirectInit) { 7258 if (CXXDirectInit->getNumExprs() == 0) { 7259 // It isn't possible to write this directly, but it is possible to 7260 // end up in this situation with "auto x(some_pack...);" 7261 Diag(CXXDirectInit->getLocStart(), 7262 diag::err_auto_var_init_no_expression) 7263 << VDecl->getDeclName() << VDecl->getType() 7264 << VDecl->getSourceRange(); 7265 RealDecl->setInvalidDecl(); 7266 return; 7267 } else if (CXXDirectInit->getNumExprs() > 1) { 7268 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 7269 diag::err_auto_var_init_multiple_expressions) 7270 << VDecl->getDeclName() << VDecl->getType() 7271 << VDecl->getSourceRange(); 7272 RealDecl->setInvalidDecl(); 7273 return; 7274 } else { 7275 DeduceInit = CXXDirectInit->getExpr(0); 7276 } 7277 } 7278 7279 // Expressions default to 'id' when we're in a debugger. 7280 bool DefaultedToAuto = false; 7281 if (getLangOpts().DebuggerCastResultToId && 7282 Init->getType() == Context.UnknownAnyTy) { 7283 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7284 if (Result.isInvalid()) { 7285 VDecl->setInvalidDecl(); 7286 return; 7287 } 7288 Init = Result.take(); 7289 DefaultedToAuto = true; 7290 } 7291 7292 TypeSourceInfo *DeducedType = 0; 7293 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 7294 DAR_Failed) 7295 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 7296 if (!DeducedType) { 7297 RealDecl->setInvalidDecl(); 7298 return; 7299 } 7300 VDecl->setTypeSourceInfo(DeducedType); 7301 VDecl->setType(DeducedType->getType()); 7302 assert(VDecl->isLinkageValid()); 7303 7304 // In ARC, infer lifetime. 7305 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 7306 VDecl->setInvalidDecl(); 7307 7308 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 7309 // 'id' instead of a specific object type prevents most of our usual checks. 7310 // We only want to warn outside of template instantiations, though: 7311 // inside a template, the 'id' could have come from a parameter. 7312 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 7313 DeducedType->getType()->isObjCIdType()) { 7314 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 7315 Diag(Loc, diag::warn_auto_var_is_id) 7316 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 7317 } 7318 7319 // If this is a redeclaration, check that the type we just deduced matches 7320 // the previously declared type. 7321 if (VarDecl *Old = VDecl->getPreviousDecl()) 7322 MergeVarDeclTypes(VDecl, Old, /*OldWasHidden*/ false); 7323 } 7324 7325 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 7326 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 7327 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 7328 VDecl->setInvalidDecl(); 7329 return; 7330 } 7331 7332 if (!VDecl->getType()->isDependentType()) { 7333 // A definition must end up with a complete type, which means it must be 7334 // complete with the restriction that an array type might be completed by 7335 // the initializer; note that later code assumes this restriction. 7336 QualType BaseDeclType = VDecl->getType(); 7337 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 7338 BaseDeclType = Array->getElementType(); 7339 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 7340 diag::err_typecheck_decl_incomplete_type)) { 7341 RealDecl->setInvalidDecl(); 7342 return; 7343 } 7344 7345 // The variable can not have an abstract class type. 7346 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 7347 diag::err_abstract_type_in_decl, 7348 AbstractVariableType)) 7349 VDecl->setInvalidDecl(); 7350 } 7351 7352 const VarDecl *Def; 7353 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 7354 Diag(VDecl->getLocation(), diag::err_redefinition) 7355 << VDecl->getDeclName(); 7356 Diag(Def->getLocation(), diag::note_previous_definition); 7357 VDecl->setInvalidDecl(); 7358 return; 7359 } 7360 7361 const VarDecl* PrevInit = 0; 7362 if (getLangOpts().CPlusPlus) { 7363 // C++ [class.static.data]p4 7364 // If a static data member is of const integral or const 7365 // enumeration type, its declaration in the class definition can 7366 // specify a constant-initializer which shall be an integral 7367 // constant expression (5.19). In that case, the member can appear 7368 // in integral constant expressions. The member shall still be 7369 // defined in a namespace scope if it is used in the program and the 7370 // namespace scope definition shall not contain an initializer. 7371 // 7372 // We already performed a redefinition check above, but for static 7373 // data members we also need to check whether there was an in-class 7374 // declaration with an initializer. 7375 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 7376 Diag(VDecl->getLocation(), diag::err_redefinition) 7377 << VDecl->getDeclName(); 7378 Diag(PrevInit->getLocation(), diag::note_previous_definition); 7379 return; 7380 } 7381 7382 if (VDecl->hasLocalStorage()) 7383 getCurFunction()->setHasBranchProtectedScope(); 7384 7385 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 7386 VDecl->setInvalidDecl(); 7387 return; 7388 } 7389 } 7390 7391 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 7392 // a kernel function cannot be initialized." 7393 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 7394 Diag(VDecl->getLocation(), diag::err_local_cant_init); 7395 VDecl->setInvalidDecl(); 7396 return; 7397 } 7398 7399 // Get the decls type and save a reference for later, since 7400 // CheckInitializerTypes may change it. 7401 QualType DclT = VDecl->getType(), SavT = DclT; 7402 7403 // Expressions default to 'id' when we're in a debugger 7404 // and we are assigning it to a variable of Objective-C pointer type. 7405 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 7406 Init->getType() == Context.UnknownAnyTy) { 7407 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7408 if (Result.isInvalid()) { 7409 VDecl->setInvalidDecl(); 7410 return; 7411 } 7412 Init = Result.take(); 7413 } 7414 7415 // Perform the initialization. 7416 if (!VDecl->isInvalidDecl()) { 7417 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 7418 InitializationKind Kind 7419 = DirectInit ? 7420 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 7421 Init->getLocStart(), 7422 Init->getLocEnd()) 7423 : InitializationKind::CreateDirectList( 7424 VDecl->getLocation()) 7425 : InitializationKind::CreateCopy(VDecl->getLocation(), 7426 Init->getLocStart()); 7427 7428 Expr **Args = &Init; 7429 unsigned NumArgs = 1; 7430 if (CXXDirectInit) { 7431 Args = CXXDirectInit->getExprs(); 7432 NumArgs = CXXDirectInit->getNumExprs(); 7433 } 7434 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 7435 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 7436 MultiExprArg(Args, NumArgs), &DclT); 7437 if (Result.isInvalid()) { 7438 VDecl->setInvalidDecl(); 7439 return; 7440 } 7441 7442 Init = Result.takeAs<Expr>(); 7443 } 7444 7445 // Check for self-references within variable initializers. 7446 // Variables declared within a function/method body (except for references) 7447 // are handled by a dataflow analysis. 7448 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 7449 VDecl->getType()->isReferenceType()) { 7450 CheckSelfReference(*this, RealDecl, Init, DirectInit); 7451 } 7452 7453 // If the type changed, it means we had an incomplete type that was 7454 // completed by the initializer. For example: 7455 // int ary[] = { 1, 3, 5 }; 7456 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 7457 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 7458 VDecl->setType(DclT); 7459 7460 if (!VDecl->isInvalidDecl()) { 7461 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 7462 7463 if (VDecl->hasAttr<BlocksAttr>()) 7464 checkRetainCycles(VDecl, Init); 7465 7466 // It is safe to assign a weak reference into a strong variable. 7467 // Although this code can still have problems: 7468 // id x = self.weakProp; 7469 // id y = self.weakProp; 7470 // we do not warn to warn spuriously when 'x' and 'y' are on separate 7471 // paths through the function. This should be revisited if 7472 // -Wrepeated-use-of-weak is made flow-sensitive. 7473 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 7474 DiagnosticsEngine::Level Level = 7475 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 7476 Init->getLocStart()); 7477 if (Level != DiagnosticsEngine::Ignored) 7478 getCurFunction()->markSafeWeakUse(Init); 7479 } 7480 } 7481 7482 // The initialization is usually a full-expression. 7483 // 7484 // FIXME: If this is a braced initialization of an aggregate, it is not 7485 // an expression, and each individual field initializer is a separate 7486 // full-expression. For instance, in: 7487 // 7488 // struct Temp { ~Temp(); }; 7489 // struct S { S(Temp); }; 7490 // struct T { S a, b; } t = { Temp(), Temp() } 7491 // 7492 // we should destroy the first Temp before constructing the second. 7493 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 7494 false, 7495 VDecl->isConstexpr()); 7496 if (Result.isInvalid()) { 7497 VDecl->setInvalidDecl(); 7498 return; 7499 } 7500 Init = Result.take(); 7501 7502 // Attach the initializer to the decl. 7503 VDecl->setInit(Init); 7504 7505 if (VDecl->isLocalVarDecl()) { 7506 // C99 6.7.8p4: All the expressions in an initializer for an object that has 7507 // static storage duration shall be constant expressions or string literals. 7508 // C++ does not have this restriction. 7509 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 7510 VDecl->getStorageClass() == SC_Static) 7511 CheckForConstantInitializer(Init, DclT); 7512 } else if (VDecl->isStaticDataMember() && 7513 VDecl->getLexicalDeclContext()->isRecord()) { 7514 // This is an in-class initialization for a static data member, e.g., 7515 // 7516 // struct S { 7517 // static const int value = 17; 7518 // }; 7519 7520 // C++ [class.mem]p4: 7521 // A member-declarator can contain a constant-initializer only 7522 // if it declares a static member (9.4) of const integral or 7523 // const enumeration type, see 9.4.2. 7524 // 7525 // C++11 [class.static.data]p3: 7526 // If a non-volatile const static data member is of integral or 7527 // enumeration type, its declaration in the class definition can 7528 // specify a brace-or-equal-initializer in which every initalizer-clause 7529 // that is an assignment-expression is a constant expression. A static 7530 // data member of literal type can be declared in the class definition 7531 // with the constexpr specifier; if so, its declaration shall specify a 7532 // brace-or-equal-initializer in which every initializer-clause that is 7533 // an assignment-expression is a constant expression. 7534 7535 // Do nothing on dependent types. 7536 if (DclT->isDependentType()) { 7537 7538 // Allow any 'static constexpr' members, whether or not they are of literal 7539 // type. We separately check that every constexpr variable is of literal 7540 // type. 7541 } else if (VDecl->isConstexpr()) { 7542 7543 // Require constness. 7544 } else if (!DclT.isConstQualified()) { 7545 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 7546 << Init->getSourceRange(); 7547 VDecl->setInvalidDecl(); 7548 7549 // We allow integer constant expressions in all cases. 7550 } else if (DclT->isIntegralOrEnumerationType()) { 7551 // Check whether the expression is a constant expression. 7552 SourceLocation Loc; 7553 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 7554 // In C++11, a non-constexpr const static data member with an 7555 // in-class initializer cannot be volatile. 7556 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 7557 else if (Init->isValueDependent()) 7558 ; // Nothing to check. 7559 else if (Init->isIntegerConstantExpr(Context, &Loc)) 7560 ; // Ok, it's an ICE! 7561 else if (Init->isEvaluatable(Context)) { 7562 // If we can constant fold the initializer through heroics, accept it, 7563 // but report this as a use of an extension for -pedantic. 7564 Diag(Loc, diag::ext_in_class_initializer_non_constant) 7565 << Init->getSourceRange(); 7566 } else { 7567 // Otherwise, this is some crazy unknown case. Report the issue at the 7568 // location provided by the isIntegerConstantExpr failed check. 7569 Diag(Loc, diag::err_in_class_initializer_non_constant) 7570 << Init->getSourceRange(); 7571 VDecl->setInvalidDecl(); 7572 } 7573 7574 // We allow foldable floating-point constants as an extension. 7575 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 7576 // In C++98, this is a GNU extension. In C++11, it is not, but we support 7577 // it anyway and provide a fixit to add the 'constexpr'. 7578 if (getLangOpts().CPlusPlus11) { 7579 Diag(VDecl->getLocation(), 7580 diag::ext_in_class_initializer_float_type_cxx11) 7581 << DclT << Init->getSourceRange(); 7582 Diag(VDecl->getLocStart(), 7583 diag::note_in_class_initializer_float_type_cxx11) 7584 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7585 } else { 7586 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 7587 << DclT << Init->getSourceRange(); 7588 7589 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 7590 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 7591 << Init->getSourceRange(); 7592 VDecl->setInvalidDecl(); 7593 } 7594 } 7595 7596 // Suggest adding 'constexpr' in C++11 for literal types. 7597 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) { 7598 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 7599 << DclT << Init->getSourceRange() 7600 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7601 VDecl->setConstexpr(true); 7602 7603 } else { 7604 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 7605 << DclT << Init->getSourceRange(); 7606 VDecl->setInvalidDecl(); 7607 } 7608 } else if (VDecl->isFileVarDecl()) { 7609 if (VDecl->getStorageClass() == SC_Extern && 7610 (!getLangOpts().CPlusPlus || 7611 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 7612 VDecl->isExternC()))) 7613 Diag(VDecl->getLocation(), diag::warn_extern_init); 7614 7615 // C99 6.7.8p4. All file scoped initializers need to be constant. 7616 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 7617 CheckForConstantInitializer(Init, DclT); 7618 } 7619 7620 // We will represent direct-initialization similarly to copy-initialization: 7621 // int x(1); -as-> int x = 1; 7622 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 7623 // 7624 // Clients that want to distinguish between the two forms, can check for 7625 // direct initializer using VarDecl::getInitStyle(). 7626 // A major benefit is that clients that don't particularly care about which 7627 // exactly form was it (like the CodeGen) can handle both cases without 7628 // special case code. 7629 7630 // C++ 8.5p11: 7631 // The form of initialization (using parentheses or '=') is generally 7632 // insignificant, but does matter when the entity being initialized has a 7633 // class type. 7634 if (CXXDirectInit) { 7635 assert(DirectInit && "Call-style initializer must be direct init."); 7636 VDecl->setInitStyle(VarDecl::CallInit); 7637 } else if (DirectInit) { 7638 // This must be list-initialization. No other way is direct-initialization. 7639 VDecl->setInitStyle(VarDecl::ListInit); 7640 } 7641 7642 CheckCompleteVariableDeclaration(VDecl); 7643} 7644 7645/// ActOnInitializerError - Given that there was an error parsing an 7646/// initializer for the given declaration, try to return to some form 7647/// of sanity. 7648void Sema::ActOnInitializerError(Decl *D) { 7649 // Our main concern here is re-establishing invariants like "a 7650 // variable's type is either dependent or complete". 7651 if (!D || D->isInvalidDecl()) return; 7652 7653 VarDecl *VD = dyn_cast<VarDecl>(D); 7654 if (!VD) return; 7655 7656 // Auto types are meaningless if we can't make sense of the initializer. 7657 if (ParsingInitForAutoVars.count(D)) { 7658 D->setInvalidDecl(); 7659 return; 7660 } 7661 7662 QualType Ty = VD->getType(); 7663 if (Ty->isDependentType()) return; 7664 7665 // Require a complete type. 7666 if (RequireCompleteType(VD->getLocation(), 7667 Context.getBaseElementType(Ty), 7668 diag::err_typecheck_decl_incomplete_type)) { 7669 VD->setInvalidDecl(); 7670 return; 7671 } 7672 7673 // Require an abstract type. 7674 if (RequireNonAbstractType(VD->getLocation(), Ty, 7675 diag::err_abstract_type_in_decl, 7676 AbstractVariableType)) { 7677 VD->setInvalidDecl(); 7678 return; 7679 } 7680 7681 // Don't bother complaining about constructors or destructors, 7682 // though. 7683} 7684 7685void Sema::ActOnUninitializedDecl(Decl *RealDecl, 7686 bool TypeMayContainAuto) { 7687 // If there is no declaration, there was an error parsing it. Just ignore it. 7688 if (RealDecl == 0) 7689 return; 7690 7691 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 7692 QualType Type = Var->getType(); 7693 7694 // C++11 [dcl.spec.auto]p3 7695 if (TypeMayContainAuto && Type->getContainedAutoType()) { 7696 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 7697 << Var->getDeclName() << Type; 7698 Var->setInvalidDecl(); 7699 return; 7700 } 7701 7702 // C++11 [class.static.data]p3: A static data member can be declared with 7703 // the constexpr specifier; if so, its declaration shall specify 7704 // a brace-or-equal-initializer. 7705 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 7706 // the definition of a variable [...] or the declaration of a static data 7707 // member. 7708 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 7709 if (Var->isStaticDataMember()) 7710 Diag(Var->getLocation(), 7711 diag::err_constexpr_static_mem_var_requires_init) 7712 << Var->getDeclName(); 7713 else 7714 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 7715 Var->setInvalidDecl(); 7716 return; 7717 } 7718 7719 switch (Var->isThisDeclarationADefinition()) { 7720 case VarDecl::Definition: 7721 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 7722 break; 7723 7724 // We have an out-of-line definition of a static data member 7725 // that has an in-class initializer, so we type-check this like 7726 // a declaration. 7727 // 7728 // Fall through 7729 7730 case VarDecl::DeclarationOnly: 7731 // It's only a declaration. 7732 7733 // Block scope. C99 6.7p7: If an identifier for an object is 7734 // declared with no linkage (C99 6.2.2p6), the type for the 7735 // object shall be complete. 7736 if (!Type->isDependentType() && Var->isLocalVarDecl() && 7737 !Var->getLinkage() && !Var->isInvalidDecl() && 7738 RequireCompleteType(Var->getLocation(), Type, 7739 diag::err_typecheck_decl_incomplete_type)) 7740 Var->setInvalidDecl(); 7741 7742 // Make sure that the type is not abstract. 7743 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7744 RequireNonAbstractType(Var->getLocation(), Type, 7745 diag::err_abstract_type_in_decl, 7746 AbstractVariableType)) 7747 Var->setInvalidDecl(); 7748 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7749 Var->getStorageClass() == SC_PrivateExtern) { 7750 Diag(Var->getLocation(), diag::warn_private_extern); 7751 Diag(Var->getLocation(), diag::note_private_extern); 7752 } 7753 7754 return; 7755 7756 case VarDecl::TentativeDefinition: 7757 // File scope. C99 6.9.2p2: A declaration of an identifier for an 7758 // object that has file scope without an initializer, and without a 7759 // storage-class specifier or with the storage-class specifier "static", 7760 // constitutes a tentative definition. Note: A tentative definition with 7761 // external linkage is valid (C99 6.2.2p5). 7762 if (!Var->isInvalidDecl()) { 7763 if (const IncompleteArrayType *ArrayT 7764 = Context.getAsIncompleteArrayType(Type)) { 7765 if (RequireCompleteType(Var->getLocation(), 7766 ArrayT->getElementType(), 7767 diag::err_illegal_decl_array_incomplete_type)) 7768 Var->setInvalidDecl(); 7769 } else if (Var->getStorageClass() == SC_Static) { 7770 // C99 6.9.2p3: If the declaration of an identifier for an object is 7771 // a tentative definition and has internal linkage (C99 6.2.2p3), the 7772 // declared type shall not be an incomplete type. 7773 // NOTE: code such as the following 7774 // static struct s; 7775 // struct s { int a; }; 7776 // is accepted by gcc. Hence here we issue a warning instead of 7777 // an error and we do not invalidate the static declaration. 7778 // NOTE: to avoid multiple warnings, only check the first declaration. 7779 if (Var->getPreviousDecl() == 0) 7780 RequireCompleteType(Var->getLocation(), Type, 7781 diag::ext_typecheck_decl_incomplete_type); 7782 } 7783 } 7784 7785 // Record the tentative definition; we're done. 7786 if (!Var->isInvalidDecl()) 7787 TentativeDefinitions.push_back(Var); 7788 return; 7789 } 7790 7791 // Provide a specific diagnostic for uninitialized variable 7792 // definitions with incomplete array type. 7793 if (Type->isIncompleteArrayType()) { 7794 Diag(Var->getLocation(), 7795 diag::err_typecheck_incomplete_array_needs_initializer); 7796 Var->setInvalidDecl(); 7797 return; 7798 } 7799 7800 // Provide a specific diagnostic for uninitialized variable 7801 // definitions with reference type. 7802 if (Type->isReferenceType()) { 7803 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 7804 << Var->getDeclName() 7805 << SourceRange(Var->getLocation(), Var->getLocation()); 7806 Var->setInvalidDecl(); 7807 return; 7808 } 7809 7810 // Do not attempt to type-check the default initializer for a 7811 // variable with dependent type. 7812 if (Type->isDependentType()) 7813 return; 7814 7815 if (Var->isInvalidDecl()) 7816 return; 7817 7818 if (RequireCompleteType(Var->getLocation(), 7819 Context.getBaseElementType(Type), 7820 diag::err_typecheck_decl_incomplete_type)) { 7821 Var->setInvalidDecl(); 7822 return; 7823 } 7824 7825 // The variable can not have an abstract class type. 7826 if (RequireNonAbstractType(Var->getLocation(), Type, 7827 diag::err_abstract_type_in_decl, 7828 AbstractVariableType)) { 7829 Var->setInvalidDecl(); 7830 return; 7831 } 7832 7833 // Check for jumps past the implicit initializer. C++0x 7834 // clarifies that this applies to a "variable with automatic 7835 // storage duration", not a "local variable". 7836 // C++11 [stmt.dcl]p3 7837 // A program that jumps from a point where a variable with automatic 7838 // storage duration is not in scope to a point where it is in scope is 7839 // ill-formed unless the variable has scalar type, class type with a 7840 // trivial default constructor and a trivial destructor, a cv-qualified 7841 // version of one of these types, or an array of one of the preceding 7842 // types and is declared without an initializer. 7843 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 7844 if (const RecordType *Record 7845 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 7846 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 7847 // Mark the function for further checking even if the looser rules of 7848 // C++11 do not require such checks, so that we can diagnose 7849 // incompatibilities with C++98. 7850 if (!CXXRecord->isPOD()) 7851 getCurFunction()->setHasBranchProtectedScope(); 7852 } 7853 } 7854 7855 // C++03 [dcl.init]p9: 7856 // If no initializer is specified for an object, and the 7857 // object is of (possibly cv-qualified) non-POD class type (or 7858 // array thereof), the object shall be default-initialized; if 7859 // the object is of const-qualified type, the underlying class 7860 // type shall have a user-declared default 7861 // constructor. Otherwise, if no initializer is specified for 7862 // a non- static object, the object and its subobjects, if 7863 // any, have an indeterminate initial value); if the object 7864 // or any of its subobjects are of const-qualified type, the 7865 // program is ill-formed. 7866 // C++0x [dcl.init]p11: 7867 // If no initializer is specified for an object, the object is 7868 // default-initialized; [...]. 7869 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 7870 InitializationKind Kind 7871 = InitializationKind::CreateDefault(Var->getLocation()); 7872 7873 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 7874 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg()); 7875 if (Init.isInvalid()) 7876 Var->setInvalidDecl(); 7877 else if (Init.get()) { 7878 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 7879 // This is important for template substitution. 7880 Var->setInitStyle(VarDecl::CallInit); 7881 } 7882 7883 CheckCompleteVariableDeclaration(Var); 7884 } 7885} 7886 7887void Sema::ActOnCXXForRangeDecl(Decl *D) { 7888 VarDecl *VD = dyn_cast<VarDecl>(D); 7889 if (!VD) { 7890 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 7891 D->setInvalidDecl(); 7892 return; 7893 } 7894 7895 VD->setCXXForRangeDecl(true); 7896 7897 // for-range-declaration cannot be given a storage class specifier. 7898 int Error = -1; 7899 switch (VD->getStorageClass()) { 7900 case SC_None: 7901 break; 7902 case SC_Extern: 7903 Error = 0; 7904 break; 7905 case SC_Static: 7906 Error = 1; 7907 break; 7908 case SC_PrivateExtern: 7909 Error = 2; 7910 break; 7911 case SC_Auto: 7912 Error = 3; 7913 break; 7914 case SC_Register: 7915 Error = 4; 7916 break; 7917 case SC_OpenCLWorkGroupLocal: 7918 llvm_unreachable("Unexpected storage class"); 7919 } 7920 if (VD->isConstexpr()) 7921 Error = 5; 7922 if (Error != -1) { 7923 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 7924 << VD->getDeclName() << Error; 7925 D->setInvalidDecl(); 7926 } 7927} 7928 7929void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 7930 if (var->isInvalidDecl()) return; 7931 7932 // In ARC, don't allow jumps past the implicit initialization of a 7933 // local retaining variable. 7934 if (getLangOpts().ObjCAutoRefCount && 7935 var->hasLocalStorage()) { 7936 switch (var->getType().getObjCLifetime()) { 7937 case Qualifiers::OCL_None: 7938 case Qualifiers::OCL_ExplicitNone: 7939 case Qualifiers::OCL_Autoreleasing: 7940 break; 7941 7942 case Qualifiers::OCL_Weak: 7943 case Qualifiers::OCL_Strong: 7944 getCurFunction()->setHasBranchProtectedScope(); 7945 break; 7946 } 7947 } 7948 7949 if (var->isThisDeclarationADefinition() && 7950 var->hasExternalLinkage() && 7951 getDiagnostics().getDiagnosticLevel( 7952 diag::warn_missing_variable_declarations, 7953 var->getLocation())) { 7954 // Find a previous declaration that's not a definition. 7955 VarDecl *prev = var->getPreviousDecl(); 7956 while (prev && prev->isThisDeclarationADefinition()) 7957 prev = prev->getPreviousDecl(); 7958 7959 if (!prev) 7960 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 7961 } 7962 7963 // All the following checks are C++ only. 7964 if (!getLangOpts().CPlusPlus) return; 7965 7966 QualType type = var->getType(); 7967 if (type->isDependentType()) return; 7968 7969 // __block variables might require us to capture a copy-initializer. 7970 if (var->hasAttr<BlocksAttr>()) { 7971 // It's currently invalid to ever have a __block variable with an 7972 // array type; should we diagnose that here? 7973 7974 // Regardless, we don't want to ignore array nesting when 7975 // constructing this copy. 7976 if (type->isStructureOrClassType()) { 7977 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 7978 SourceLocation poi = var->getLocation(); 7979 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 7980 ExprResult result 7981 = PerformMoveOrCopyInitialization( 7982 InitializedEntity::InitializeBlock(poi, type, false), 7983 var, var->getType(), varRef, /*AllowNRVO=*/true); 7984 if (!result.isInvalid()) { 7985 result = MaybeCreateExprWithCleanups(result); 7986 Expr *init = result.takeAs<Expr>(); 7987 Context.setBlockVarCopyInits(var, init); 7988 } 7989 } 7990 } 7991 7992 Expr *Init = var->getInit(); 7993 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7994 QualType baseType = Context.getBaseElementType(type); 7995 7996 if (!var->getDeclContext()->isDependentContext() && 7997 Init && !Init->isValueDependent()) { 7998 if (IsGlobal && !var->isConstexpr() && 7999 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8000 var->getLocation()) 8001 != DiagnosticsEngine::Ignored && 8002 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8003 Diag(var->getLocation(), diag::warn_global_constructor) 8004 << Init->getSourceRange(); 8005 8006 if (var->isConstexpr()) { 8007 SmallVector<PartialDiagnosticAt, 8> Notes; 8008 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8009 SourceLocation DiagLoc = var->getLocation(); 8010 // If the note doesn't add any useful information other than a source 8011 // location, fold it into the primary diagnostic. 8012 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8013 diag::note_invalid_subexpr_in_const_expr) { 8014 DiagLoc = Notes[0].first; 8015 Notes.clear(); 8016 } 8017 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8018 << var << Init->getSourceRange(); 8019 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8020 Diag(Notes[I].first, Notes[I].second); 8021 } 8022 } else if (var->isUsableInConstantExpressions(Context)) { 8023 // Check whether the initializer of a const variable of integral or 8024 // enumeration type is an ICE now, since we can't tell whether it was 8025 // initialized by a constant expression if we check later. 8026 var->checkInitIsICE(); 8027 } 8028 } 8029 8030 // Require the destructor. 8031 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8032 FinalizeVarWithDestructor(var, recordType); 8033} 8034 8035/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8036/// any semantic actions necessary after any initializer has been attached. 8037void 8038Sema::FinalizeDeclaration(Decl *ThisDecl) { 8039 // Note that we are no longer parsing the initializer for this declaration. 8040 ParsingInitForAutoVars.erase(ThisDecl); 8041 8042 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8043 if (!VD) 8044 return; 8045 8046 const DeclContext *DC = VD->getDeclContext(); 8047 // If there's a #pragma GCC visibility in scope, and this isn't a class 8048 // member, set the visibility of this variable. 8049 if (!DC->isRecord() && VD->hasExternalLinkage()) 8050 AddPushedVisibilityAttribute(VD); 8051 8052 if (VD->isFileVarDecl()) 8053 MarkUnusedFileScopedDecl(VD); 8054 8055 // Now we have parsed the initializer and can update the table of magic 8056 // tag values. 8057 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8058 !VD->getType()->isIntegralOrEnumerationType()) 8059 return; 8060 8061 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8062 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8063 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8064 I != E; ++I) { 8065 const Expr *MagicValueExpr = VD->getInit(); 8066 if (!MagicValueExpr) { 8067 continue; 8068 } 8069 llvm::APSInt MagicValueInt; 8070 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8071 Diag(I->getRange().getBegin(), 8072 diag::err_type_tag_for_datatype_not_ice) 8073 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8074 continue; 8075 } 8076 if (MagicValueInt.getActiveBits() > 64) { 8077 Diag(I->getRange().getBegin(), 8078 diag::err_type_tag_for_datatype_too_large) 8079 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8080 continue; 8081 } 8082 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8083 RegisterTypeTagForDatatype(I->getArgumentKind(), 8084 MagicValue, 8085 I->getMatchingCType(), 8086 I->getLayoutCompatible(), 8087 I->getMustBeNull()); 8088 } 8089} 8090 8091Sema::DeclGroupPtrTy 8092Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8093 Decl **Group, unsigned NumDecls) { 8094 SmallVector<Decl*, 8> Decls; 8095 8096 if (DS.isTypeSpecOwned()) 8097 Decls.push_back(DS.getRepAsDecl()); 8098 8099 for (unsigned i = 0; i != NumDecls; ++i) 8100 if (Decl *D = Group[i]) 8101 Decls.push_back(D); 8102 8103 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) 8104 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) 8105 getASTContext().addUnnamedTag(Tag); 8106 8107 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 8108 DS.getTypeSpecType() == DeclSpec::TST_auto); 8109} 8110 8111/// BuildDeclaratorGroup - convert a list of declarations into a declaration 8112/// group, performing any necessary semantic checking. 8113Sema::DeclGroupPtrTy 8114Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 8115 bool TypeMayContainAuto) { 8116 // C++0x [dcl.spec.auto]p7: 8117 // If the type deduced for the template parameter U is not the same in each 8118 // deduction, the program is ill-formed. 8119 // FIXME: When initializer-list support is added, a distinction is needed 8120 // between the deduced type U and the deduced type which 'auto' stands for. 8121 // auto a = 0, b = { 1, 2, 3 }; 8122 // is legal because the deduced type U is 'int' in both cases. 8123 if (TypeMayContainAuto && NumDecls > 1) { 8124 QualType Deduced; 8125 CanQualType DeducedCanon; 8126 VarDecl *DeducedDecl = 0; 8127 for (unsigned i = 0; i != NumDecls; ++i) { 8128 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 8129 AutoType *AT = D->getType()->getContainedAutoType(); 8130 // Don't reissue diagnostics when instantiating a template. 8131 if (AT && D->isInvalidDecl()) 8132 break; 8133 if (AT && AT->isDeduced()) { 8134 QualType U = AT->getDeducedType(); 8135 CanQualType UCanon = Context.getCanonicalType(U); 8136 if (Deduced.isNull()) { 8137 Deduced = U; 8138 DeducedCanon = UCanon; 8139 DeducedDecl = D; 8140 } else if (DeducedCanon != UCanon) { 8141 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 8142 diag::err_auto_different_deductions) 8143 << Deduced << DeducedDecl->getDeclName() 8144 << U << D->getDeclName() 8145 << DeducedDecl->getInit()->getSourceRange() 8146 << D->getInit()->getSourceRange(); 8147 D->setInvalidDecl(); 8148 break; 8149 } 8150 } 8151 } 8152 } 8153 } 8154 8155 ActOnDocumentableDecls(Group, NumDecls); 8156 8157 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 8158} 8159 8160void Sema::ActOnDocumentableDecl(Decl *D) { 8161 ActOnDocumentableDecls(&D, 1); 8162} 8163 8164void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 8165 // Don't parse the comment if Doxygen diagnostics are ignored. 8166 if (NumDecls == 0 || !Group[0]) 8167 return; 8168 8169 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 8170 Group[0]->getLocation()) 8171 == DiagnosticsEngine::Ignored) 8172 return; 8173 8174 if (NumDecls >= 2) { 8175 // This is a decl group. Normally it will contain only declarations 8176 // procuded from declarator list. But in case we have any definitions or 8177 // additional declaration references: 8178 // 'typedef struct S {} S;' 8179 // 'typedef struct S *S;' 8180 // 'struct S *pS;' 8181 // FinalizeDeclaratorGroup adds these as separate declarations. 8182 Decl *MaybeTagDecl = Group[0]; 8183 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 8184 Group++; 8185 NumDecls--; 8186 } 8187 } 8188 8189 // See if there are any new comments that are not attached to a decl. 8190 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 8191 if (!Comments.empty() && 8192 !Comments.back()->isAttached()) { 8193 // There is at least one comment that not attached to a decl. 8194 // Maybe it should be attached to one of these decls? 8195 // 8196 // Note that this way we pick up not only comments that precede the 8197 // declaration, but also comments that *follow* the declaration -- thanks to 8198 // the lookahead in the lexer: we've consumed the semicolon and looked 8199 // ahead through comments. 8200 for (unsigned i = 0; i != NumDecls; ++i) 8201 Context.getCommentForDecl(Group[i], &PP); 8202 } 8203} 8204 8205/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 8206/// to introduce parameters into function prototype scope. 8207Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 8208 const DeclSpec &DS = D.getDeclSpec(); 8209 8210 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 8211 // C++03 [dcl.stc]p2 also permits 'auto'. 8212 VarDecl::StorageClass StorageClass = SC_None; 8213 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 8214 StorageClass = SC_Register; 8215 } else if (getLangOpts().CPlusPlus && 8216 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 8217 StorageClass = SC_Auto; 8218 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 8219 Diag(DS.getStorageClassSpecLoc(), 8220 diag::err_invalid_storage_class_in_func_decl); 8221 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8222 } 8223 8224 if (D.getDeclSpec().isThreadSpecified()) 8225 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 8226 if (D.getDeclSpec().isConstexprSpecified()) 8227 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 8228 << 0; 8229 8230 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 8231 8232 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8233 QualType parmDeclType = TInfo->getType(); 8234 8235 if (getLangOpts().CPlusPlus) { 8236 // Check that there are no default arguments inside the type of this 8237 // parameter. 8238 CheckExtraCXXDefaultArguments(D); 8239 8240 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 8241 if (D.getCXXScopeSpec().isSet()) { 8242 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 8243 << D.getCXXScopeSpec().getRange(); 8244 D.getCXXScopeSpec().clear(); 8245 } 8246 } 8247 8248 // Ensure we have a valid name 8249 IdentifierInfo *II = 0; 8250 if (D.hasName()) { 8251 II = D.getIdentifier(); 8252 if (!II) { 8253 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 8254 << GetNameForDeclarator(D).getName().getAsString(); 8255 D.setInvalidType(true); 8256 } 8257 } 8258 8259 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 8260 if (II) { 8261 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 8262 ForRedeclaration); 8263 LookupName(R, S); 8264 if (R.isSingleResult()) { 8265 NamedDecl *PrevDecl = R.getFoundDecl(); 8266 if (PrevDecl->isTemplateParameter()) { 8267 // Maybe we will complain about the shadowed template parameter. 8268 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8269 // Just pretend that we didn't see the previous declaration. 8270 PrevDecl = 0; 8271 } else if (S->isDeclScope(PrevDecl)) { 8272 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 8273 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8274 8275 // Recover by removing the name 8276 II = 0; 8277 D.SetIdentifier(0, D.getIdentifierLoc()); 8278 D.setInvalidType(true); 8279 } 8280 } 8281 } 8282 8283 // Temporarily put parameter variables in the translation unit, not 8284 // the enclosing context. This prevents them from accidentally 8285 // looking like class members in C++. 8286 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 8287 D.getLocStart(), 8288 D.getIdentifierLoc(), II, 8289 parmDeclType, TInfo, 8290 StorageClass); 8291 8292 if (D.isInvalidType()) 8293 New->setInvalidDecl(); 8294 8295 assert(S->isFunctionPrototypeScope()); 8296 assert(S->getFunctionPrototypeDepth() >= 1); 8297 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 8298 S->getNextFunctionPrototypeIndex()); 8299 8300 // Add the parameter declaration into this scope. 8301 S->AddDecl(New); 8302 if (II) 8303 IdResolver.AddDecl(New); 8304 8305 ProcessDeclAttributes(S, New, D); 8306 8307 if (D.getDeclSpec().isModulePrivateSpecified()) 8308 Diag(New->getLocation(), diag::err_module_private_local) 8309 << 1 << New->getDeclName() 8310 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8311 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8312 8313 if (New->hasAttr<BlocksAttr>()) { 8314 Diag(New->getLocation(), diag::err_block_on_nonlocal); 8315 } 8316 return New; 8317} 8318 8319/// \brief Synthesizes a variable for a parameter arising from a 8320/// typedef. 8321ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 8322 SourceLocation Loc, 8323 QualType T) { 8324 /* FIXME: setting StartLoc == Loc. 8325 Would it be worth to modify callers so as to provide proper source 8326 location for the unnamed parameters, embedding the parameter's type? */ 8327 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 8328 T, Context.getTrivialTypeSourceInfo(T, Loc), 8329 SC_None, 0); 8330 Param->setImplicit(); 8331 return Param; 8332} 8333 8334void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 8335 ParmVarDecl * const *ParamEnd) { 8336 // Don't diagnose unused-parameter errors in template instantiations; we 8337 // will already have done so in the template itself. 8338 if (!ActiveTemplateInstantiations.empty()) 8339 return; 8340 8341 for (; Param != ParamEnd; ++Param) { 8342 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 8343 !(*Param)->hasAttr<UnusedAttr>()) { 8344 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 8345 << (*Param)->getDeclName(); 8346 } 8347 } 8348} 8349 8350void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 8351 ParmVarDecl * const *ParamEnd, 8352 QualType ReturnTy, 8353 NamedDecl *D) { 8354 if (LangOpts.NumLargeByValueCopy == 0) // No check. 8355 return; 8356 8357 // Warn if the return value is pass-by-value and larger than the specified 8358 // threshold. 8359 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 8360 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 8361 if (Size > LangOpts.NumLargeByValueCopy) 8362 Diag(D->getLocation(), diag::warn_return_value_size) 8363 << D->getDeclName() << Size; 8364 } 8365 8366 // Warn if any parameter is pass-by-value and larger than the specified 8367 // threshold. 8368 for (; Param != ParamEnd; ++Param) { 8369 QualType T = (*Param)->getType(); 8370 if (T->isDependentType() || !T.isPODType(Context)) 8371 continue; 8372 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 8373 if (Size > LangOpts.NumLargeByValueCopy) 8374 Diag((*Param)->getLocation(), diag::warn_parameter_size) 8375 << (*Param)->getDeclName() << Size; 8376 } 8377} 8378 8379ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 8380 SourceLocation NameLoc, IdentifierInfo *Name, 8381 QualType T, TypeSourceInfo *TSInfo, 8382 VarDecl::StorageClass StorageClass) { 8383 // In ARC, infer a lifetime qualifier for appropriate parameter types. 8384 if (getLangOpts().ObjCAutoRefCount && 8385 T.getObjCLifetime() == Qualifiers::OCL_None && 8386 T->isObjCLifetimeType()) { 8387 8388 Qualifiers::ObjCLifetime lifetime; 8389 8390 // Special cases for arrays: 8391 // - if it's const, use __unsafe_unretained 8392 // - otherwise, it's an error 8393 if (T->isArrayType()) { 8394 if (!T.isConstQualified()) { 8395 DelayedDiagnostics.add( 8396 sema::DelayedDiagnostic::makeForbiddenType( 8397 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 8398 } 8399 lifetime = Qualifiers::OCL_ExplicitNone; 8400 } else { 8401 lifetime = T->getObjCARCImplicitLifetime(); 8402 } 8403 T = Context.getLifetimeQualifiedType(T, lifetime); 8404 } 8405 8406 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 8407 Context.getAdjustedParameterType(T), 8408 TSInfo, 8409 StorageClass, 0); 8410 8411 // Parameters can not be abstract class types. 8412 // For record types, this is done by the AbstractClassUsageDiagnoser once 8413 // the class has been completely parsed. 8414 if (!CurContext->isRecord() && 8415 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 8416 AbstractParamType)) 8417 New->setInvalidDecl(); 8418 8419 // Parameter declarators cannot be interface types. All ObjC objects are 8420 // passed by reference. 8421 if (T->isObjCObjectType()) { 8422 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 8423 Diag(NameLoc, 8424 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 8425 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 8426 T = Context.getObjCObjectPointerType(T); 8427 New->setType(T); 8428 } 8429 8430 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 8431 // duration shall not be qualified by an address-space qualifier." 8432 // Since all parameters have automatic store duration, they can not have 8433 // an address space. 8434 if (T.getAddressSpace() != 0) { 8435 Diag(NameLoc, diag::err_arg_with_address_space); 8436 New->setInvalidDecl(); 8437 } 8438 8439 return New; 8440} 8441 8442void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 8443 SourceLocation LocAfterDecls) { 8444 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8445 8446 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 8447 // for a K&R function. 8448 if (!FTI.hasPrototype) { 8449 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 8450 --i; 8451 if (FTI.ArgInfo[i].Param == 0) { 8452 SmallString<256> Code; 8453 llvm::raw_svector_ostream(Code) << " int " 8454 << FTI.ArgInfo[i].Ident->getName() 8455 << ";\n"; 8456 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 8457 << FTI.ArgInfo[i].Ident 8458 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 8459 8460 // Implicitly declare the argument as type 'int' for lack of a better 8461 // type. 8462 AttributeFactory attrs; 8463 DeclSpec DS(attrs); 8464 const char* PrevSpec; // unused 8465 unsigned DiagID; // unused 8466 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 8467 PrevSpec, DiagID); 8468 // Use the identifier location for the type source range. 8469 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 8470 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 8471 Declarator ParamD(DS, Declarator::KNRTypeListContext); 8472 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 8473 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 8474 } 8475 } 8476 } 8477} 8478 8479Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 8480 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 8481 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 8482 Scope *ParentScope = FnBodyScope->getParent(); 8483 8484 D.setFunctionDefinitionKind(FDK_Definition); 8485 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 8486 return ActOnStartOfFunctionDef(FnBodyScope, DP); 8487} 8488 8489static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 8490 const FunctionDecl*& PossibleZeroParamPrototype) { 8491 // Don't warn about invalid declarations. 8492 if (FD->isInvalidDecl()) 8493 return false; 8494 8495 // Or declarations that aren't global. 8496 if (!FD->isGlobal()) 8497 return false; 8498 8499 // Don't warn about C++ member functions. 8500 if (isa<CXXMethodDecl>(FD)) 8501 return false; 8502 8503 // Don't warn about 'main'. 8504 if (FD->isMain()) 8505 return false; 8506 8507 // Don't warn about inline functions. 8508 if (FD->isInlined()) 8509 return false; 8510 8511 // Don't warn about function templates. 8512 if (FD->getDescribedFunctionTemplate()) 8513 return false; 8514 8515 // Don't warn about function template specializations. 8516 if (FD->isFunctionTemplateSpecialization()) 8517 return false; 8518 8519 // Don't warn for OpenCL kernels. 8520 if (FD->hasAttr<OpenCLKernelAttr>()) 8521 return false; 8522 8523 bool MissingPrototype = true; 8524 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 8525 Prev; Prev = Prev->getPreviousDecl()) { 8526 // Ignore any declarations that occur in function or method 8527 // scope, because they aren't visible from the header. 8528 if (Prev->getDeclContext()->isFunctionOrMethod()) 8529 continue; 8530 8531 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 8532 if (FD->getNumParams() == 0) 8533 PossibleZeroParamPrototype = Prev; 8534 break; 8535 } 8536 8537 return MissingPrototype; 8538} 8539 8540void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 8541 // Don't complain if we're in GNU89 mode and the previous definition 8542 // was an extern inline function. 8543 const FunctionDecl *Definition; 8544 if (FD->isDefined(Definition) && 8545 !canRedefineFunction(Definition, getLangOpts())) { 8546 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 8547 Definition->getStorageClass() == SC_Extern) 8548 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 8549 << FD->getDeclName() << getLangOpts().CPlusPlus; 8550 else 8551 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 8552 Diag(Definition->getLocation(), diag::note_previous_definition); 8553 FD->setInvalidDecl(); 8554 } 8555} 8556 8557Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 8558 // Clear the last template instantiation error context. 8559 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 8560 8561 if (!D) 8562 return D; 8563 FunctionDecl *FD = 0; 8564 8565 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 8566 FD = FunTmpl->getTemplatedDecl(); 8567 else 8568 FD = cast<FunctionDecl>(D); 8569 8570 // Enter a new function scope 8571 PushFunctionScope(); 8572 8573 // See if this is a redefinition. 8574 if (!FD->isLateTemplateParsed()) 8575 CheckForFunctionRedefinition(FD); 8576 8577 // Builtin functions cannot be defined. 8578 if (unsigned BuiltinID = FD->getBuiltinID()) { 8579 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 8580 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 8581 FD->setInvalidDecl(); 8582 } 8583 } 8584 8585 // The return type of a function definition must be complete 8586 // (C99 6.9.1p3, C++ [dcl.fct]p6). 8587 QualType ResultType = FD->getResultType(); 8588 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 8589 !FD->isInvalidDecl() && 8590 RequireCompleteType(FD->getLocation(), ResultType, 8591 diag::err_func_def_incomplete_result)) 8592 FD->setInvalidDecl(); 8593 8594 // GNU warning -Wmissing-prototypes: 8595 // Warn if a global function is defined without a previous 8596 // prototype declaration. This warning is issued even if the 8597 // definition itself provides a prototype. The aim is to detect 8598 // global functions that fail to be declared in header files. 8599 const FunctionDecl *PossibleZeroParamPrototype = 0; 8600 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 8601 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 8602 8603 if (PossibleZeroParamPrototype) { 8604 // We found a declaration that is not a prototype, 8605 // but that could be a zero-parameter prototype 8606 TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo(); 8607 TypeLoc TL = TI->getTypeLoc(); 8608 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 8609 Diag(PossibleZeroParamPrototype->getLocation(), 8610 diag::note_declaration_not_a_prototype) 8611 << PossibleZeroParamPrototype 8612 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 8613 } 8614 } 8615 8616 if (FnBodyScope) 8617 PushDeclContext(FnBodyScope, FD); 8618 8619 // Check the validity of our function parameters 8620 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 8621 /*CheckParameterNames=*/true); 8622 8623 // Introduce our parameters into the function scope 8624 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 8625 ParmVarDecl *Param = FD->getParamDecl(p); 8626 Param->setOwningFunction(FD); 8627 8628 // If this has an identifier, add it to the scope stack. 8629 if (Param->getIdentifier() && FnBodyScope) { 8630 CheckShadow(FnBodyScope, Param); 8631 8632 PushOnScopeChains(Param, FnBodyScope); 8633 } 8634 } 8635 8636 // If we had any tags defined in the function prototype, 8637 // introduce them into the function scope. 8638 if (FnBodyScope) { 8639 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 8640 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 8641 NamedDecl *D = *I; 8642 8643 // Some of these decls (like enums) may have been pinned to the translation unit 8644 // for lack of a real context earlier. If so, remove from the translation unit 8645 // and reattach to the current context. 8646 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 8647 // Is the decl actually in the context? 8648 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 8649 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 8650 if (*DI == D) { 8651 Context.getTranslationUnitDecl()->removeDecl(D); 8652 break; 8653 } 8654 } 8655 // Either way, reassign the lexical decl context to our FunctionDecl. 8656 D->setLexicalDeclContext(CurContext); 8657 } 8658 8659 // If the decl has a non-null name, make accessible in the current scope. 8660 if (!D->getName().empty()) 8661 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 8662 8663 // Similarly, dive into enums and fish their constants out, making them 8664 // accessible in this scope. 8665 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 8666 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 8667 EE = ED->enumerator_end(); EI != EE; ++EI) 8668 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 8669 } 8670 } 8671 } 8672 8673 // Ensure that the function's exception specification is instantiated. 8674 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 8675 ResolveExceptionSpec(D->getLocation(), FPT); 8676 8677 // Checking attributes of current function definition 8678 // dllimport attribute. 8679 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 8680 if (DA && (!FD->getAttr<DLLExportAttr>())) { 8681 // dllimport attribute cannot be directly applied to definition. 8682 // Microsoft accepts dllimport for functions defined within class scope. 8683 if (!DA->isInherited() && 8684 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 8685 Diag(FD->getLocation(), 8686 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 8687 << "dllimport"; 8688 FD->setInvalidDecl(); 8689 return D; 8690 } 8691 8692 // Visual C++ appears to not think this is an issue, so only issue 8693 // a warning when Microsoft extensions are disabled. 8694 if (!LangOpts.MicrosoftExt) { 8695 // If a symbol previously declared dllimport is later defined, the 8696 // attribute is ignored in subsequent references, and a warning is 8697 // emitted. 8698 Diag(FD->getLocation(), 8699 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 8700 << FD->getName() << "dllimport"; 8701 } 8702 } 8703 // We want to attach documentation to original Decl (which might be 8704 // a function template). 8705 ActOnDocumentableDecl(D); 8706 return D; 8707} 8708 8709/// \brief Given the set of return statements within a function body, 8710/// compute the variables that are subject to the named return value 8711/// optimization. 8712/// 8713/// Each of the variables that is subject to the named return value 8714/// optimization will be marked as NRVO variables in the AST, and any 8715/// return statement that has a marked NRVO variable as its NRVO candidate can 8716/// use the named return value optimization. 8717/// 8718/// This function applies a very simplistic algorithm for NRVO: if every return 8719/// statement in the function has the same NRVO candidate, that candidate is 8720/// the NRVO variable. 8721/// 8722/// FIXME: Employ a smarter algorithm that accounts for multiple return 8723/// statements and the lifetimes of the NRVO candidates. We should be able to 8724/// find a maximal set of NRVO variables. 8725void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 8726 ReturnStmt **Returns = Scope->Returns.data(); 8727 8728 const VarDecl *NRVOCandidate = 0; 8729 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 8730 if (!Returns[I]->getNRVOCandidate()) 8731 return; 8732 8733 if (!NRVOCandidate) 8734 NRVOCandidate = Returns[I]->getNRVOCandidate(); 8735 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 8736 return; 8737 } 8738 8739 if (NRVOCandidate) 8740 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 8741} 8742 8743bool Sema::canSkipFunctionBody(Decl *D) { 8744 if (!Consumer.shouldSkipFunctionBody(D)) 8745 return false; 8746 8747 if (isa<ObjCMethodDecl>(D)) 8748 return true; 8749 8750 FunctionDecl *FD = 0; 8751 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 8752 FD = FTD->getTemplatedDecl(); 8753 else 8754 FD = cast<FunctionDecl>(D); 8755 8756 // We cannot skip the body of a function (or function template) which is 8757 // constexpr, since we may need to evaluate its body in order to parse the 8758 // rest of the file. 8759 return !FD->isConstexpr(); 8760} 8761 8762Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 8763 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 8764 FD->setHasSkippedBody(); 8765 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 8766 MD->setHasSkippedBody(); 8767 return ActOnFinishFunctionBody(Decl, 0); 8768} 8769 8770Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 8771 return ActOnFinishFunctionBody(D, BodyArg, false); 8772} 8773 8774Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 8775 bool IsInstantiation) { 8776 FunctionDecl *FD = 0; 8777 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 8778 if (FunTmpl) 8779 FD = FunTmpl->getTemplatedDecl(); 8780 else 8781 FD = dyn_cast_or_null<FunctionDecl>(dcl); 8782 8783 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 8784 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 8785 8786 if (FD) { 8787 FD->setBody(Body); 8788 8789 // The only way to be included in UndefinedButUsed is if there is an 8790 // ODR use before the definition. Avoid the expensive map lookup if this 8791 // is the first declaration. 8792 if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) { 8793 if (FD->getLinkage() != ExternalLinkage) 8794 UndefinedButUsed.erase(FD); 8795 else if (FD->isInlined() && 8796 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 8797 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 8798 UndefinedButUsed.erase(FD); 8799 } 8800 8801 // If the function implicitly returns zero (like 'main') or is naked, 8802 // don't complain about missing return statements. 8803 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 8804 WP.disableCheckFallThrough(); 8805 8806 // MSVC permits the use of pure specifier (=0) on function definition, 8807 // defined at class scope, warn about this non standard construct. 8808 if (getLangOpts().MicrosoftExt && FD->isPure()) 8809 Diag(FD->getLocation(), diag::warn_pure_function_definition); 8810 8811 if (!FD->isInvalidDecl()) { 8812 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 8813 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 8814 FD->getResultType(), FD); 8815 8816 // If this is a constructor, we need a vtable. 8817 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 8818 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 8819 8820 // Try to apply the named return value optimization. We have to check 8821 // if we can do this here because lambdas keep return statements around 8822 // to deduce an implicit return type. 8823 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 8824 !FD->isDependentContext()) 8825 computeNRVO(Body, getCurFunction()); 8826 } 8827 8828 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 8829 "Function parsing confused"); 8830 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 8831 assert(MD == getCurMethodDecl() && "Method parsing confused"); 8832 MD->setBody(Body); 8833 if (!MD->isInvalidDecl()) { 8834 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 8835 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 8836 MD->getResultType(), MD); 8837 8838 if (Body) 8839 computeNRVO(Body, getCurFunction()); 8840 } 8841 if (getCurFunction()->ObjCShouldCallSuper) { 8842 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 8843 << MD->getSelector().getAsString(); 8844 getCurFunction()->ObjCShouldCallSuper = false; 8845 } 8846 } else { 8847 return 0; 8848 } 8849 8850 assert(!getCurFunction()->ObjCShouldCallSuper && 8851 "This should only be set for ObjC methods, which should have been " 8852 "handled in the block above."); 8853 8854 // Verify and clean out per-function state. 8855 if (Body) { 8856 // C++ constructors that have function-try-blocks can't have return 8857 // statements in the handlers of that block. (C++ [except.handle]p14) 8858 // Verify this. 8859 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 8860 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 8861 8862 // Verify that gotos and switch cases don't jump into scopes illegally. 8863 if (getCurFunction()->NeedsScopeChecking() && 8864 !dcl->isInvalidDecl() && 8865 !hasAnyUnrecoverableErrorsInThisFunction() && 8866 !PP.isCodeCompletionEnabled()) 8867 DiagnoseInvalidJumps(Body); 8868 8869 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 8870 if (!Destructor->getParent()->isDependentType()) 8871 CheckDestructor(Destructor); 8872 8873 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8874 Destructor->getParent()); 8875 } 8876 8877 // If any errors have occurred, clear out any temporaries that may have 8878 // been leftover. This ensures that these temporaries won't be picked up for 8879 // deletion in some later function. 8880 if (PP.getDiagnostics().hasErrorOccurred() || 8881 PP.getDiagnostics().getSuppressAllDiagnostics()) { 8882 DiscardCleanupsInEvaluationContext(); 8883 } 8884 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 8885 !isa<FunctionTemplateDecl>(dcl)) { 8886 // Since the body is valid, issue any analysis-based warnings that are 8887 // enabled. 8888 ActivePolicy = &WP; 8889 } 8890 8891 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 8892 (!CheckConstexprFunctionDecl(FD) || 8893 !CheckConstexprFunctionBody(FD, Body))) 8894 FD->setInvalidDecl(); 8895 8896 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 8897 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 8898 assert(MaybeODRUseExprs.empty() && 8899 "Leftover expressions for odr-use checking"); 8900 } 8901 8902 if (!IsInstantiation) 8903 PopDeclContext(); 8904 8905 PopFunctionScopeInfo(ActivePolicy, dcl); 8906 8907 // If any errors have occurred, clear out any temporaries that may have 8908 // been leftover. This ensures that these temporaries won't be picked up for 8909 // deletion in some later function. 8910 if (getDiagnostics().hasErrorOccurred()) { 8911 DiscardCleanupsInEvaluationContext(); 8912 } 8913 8914 return dcl; 8915} 8916 8917 8918/// When we finish delayed parsing of an attribute, we must attach it to the 8919/// relevant Decl. 8920void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 8921 ParsedAttributes &Attrs) { 8922 // Always attach attributes to the underlying decl. 8923 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8924 D = TD->getTemplatedDecl(); 8925 ProcessDeclAttributeList(S, D, Attrs.getList()); 8926 8927 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 8928 if (Method->isStatic()) 8929 checkThisInStaticMemberFunctionAttributes(Method); 8930} 8931 8932 8933/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 8934/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 8935NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 8936 IdentifierInfo &II, Scope *S) { 8937 // Before we produce a declaration for an implicitly defined 8938 // function, see whether there was a locally-scoped declaration of 8939 // this name as a function or variable. If so, use that 8940 // (non-visible) declaration, and complain about it. 8941 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 8942 = findLocallyScopedExternCDecl(&II); 8943 if (Pos != LocallyScopedExternCDecls.end()) { 8944 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 8945 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 8946 return Pos->second; 8947 } 8948 8949 // Extension in C99. Legal in C90, but warn about it. 8950 unsigned diag_id; 8951 if (II.getName().startswith("__builtin_")) 8952 diag_id = diag::warn_builtin_unknown; 8953 else if (getLangOpts().C99) 8954 diag_id = diag::ext_implicit_function_decl; 8955 else 8956 diag_id = diag::warn_implicit_function_decl; 8957 Diag(Loc, diag_id) << &II; 8958 8959 // Because typo correction is expensive, only do it if the implicit 8960 // function declaration is going to be treated as an error. 8961 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 8962 TypoCorrection Corrected; 8963 DeclFilterCCC<FunctionDecl> Validator; 8964 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 8965 LookupOrdinaryName, S, 0, Validator))) { 8966 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 8967 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 8968 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 8969 8970 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 8971 << FixItHint::CreateReplacement(Loc, CorrectedStr); 8972 8973 if (Func->getLocation().isValid() 8974 && !II.getName().startswith("__builtin_")) 8975 Diag(Func->getLocation(), diag::note_previous_decl) 8976 << CorrectedQuotedStr; 8977 } 8978 } 8979 8980 // Set a Declarator for the implicit definition: int foo(); 8981 const char *Dummy; 8982 AttributeFactory attrFactory; 8983 DeclSpec DS(attrFactory); 8984 unsigned DiagID; 8985 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 8986 (void)Error; // Silence warning. 8987 assert(!Error && "Error setting up implicit decl!"); 8988 SourceLocation NoLoc; 8989 Declarator D(DS, Declarator::BlockContext); 8990 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 8991 /*IsAmbiguous=*/false, 8992 /*RParenLoc=*/NoLoc, 8993 /*ArgInfo=*/0, 8994 /*NumArgs=*/0, 8995 /*EllipsisLoc=*/NoLoc, 8996 /*RParenLoc=*/NoLoc, 8997 /*TypeQuals=*/0, 8998 /*RefQualifierIsLvalueRef=*/true, 8999 /*RefQualifierLoc=*/NoLoc, 9000 /*ConstQualifierLoc=*/NoLoc, 9001 /*VolatileQualifierLoc=*/NoLoc, 9002 /*MutableLoc=*/NoLoc, 9003 EST_None, 9004 /*ESpecLoc=*/NoLoc, 9005 /*Exceptions=*/0, 9006 /*ExceptionRanges=*/0, 9007 /*NumExceptions=*/0, 9008 /*NoexceptExpr=*/0, 9009 Loc, Loc, D), 9010 DS.getAttributes(), 9011 SourceLocation()); 9012 D.SetIdentifier(&II, Loc); 9013 9014 // Insert this function into translation-unit scope. 9015 9016 DeclContext *PrevDC = CurContext; 9017 CurContext = Context.getTranslationUnitDecl(); 9018 9019 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9020 FD->setImplicit(); 9021 9022 CurContext = PrevDC; 9023 9024 AddKnownFunctionAttributes(FD); 9025 9026 return FD; 9027} 9028 9029/// \brief Adds any function attributes that we know a priori based on 9030/// the declaration of this function. 9031/// 9032/// These attributes can apply both to implicitly-declared builtins 9033/// (like __builtin___printf_chk) or to library-declared functions 9034/// like NSLog or printf. 9035/// 9036/// We need to check for duplicate attributes both here and where user-written 9037/// attributes are applied to declarations. 9038void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 9039 if (FD->isInvalidDecl()) 9040 return; 9041 9042 // If this is a built-in function, map its builtin attributes to 9043 // actual attributes. 9044 if (unsigned BuiltinID = FD->getBuiltinID()) { 9045 // Handle printf-formatting attributes. 9046 unsigned FormatIdx; 9047 bool HasVAListArg; 9048 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 9049 if (!FD->getAttr<FormatAttr>()) { 9050 const char *fmt = "printf"; 9051 unsigned int NumParams = FD->getNumParams(); 9052 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 9053 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 9054 fmt = "NSString"; 9055 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9056 fmt, FormatIdx+1, 9057 HasVAListArg ? 0 : FormatIdx+2)); 9058 } 9059 } 9060 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 9061 HasVAListArg)) { 9062 if (!FD->getAttr<FormatAttr>()) 9063 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9064 "scanf", FormatIdx+1, 9065 HasVAListArg ? 0 : FormatIdx+2)); 9066 } 9067 9068 // Mark const if we don't care about errno and that is the only 9069 // thing preventing the function from being const. This allows 9070 // IRgen to use LLVM intrinsics for such functions. 9071 if (!getLangOpts().MathErrno && 9072 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 9073 if (!FD->getAttr<ConstAttr>()) 9074 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9075 } 9076 9077 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 9078 !FD->getAttr<ReturnsTwiceAttr>()) 9079 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 9080 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 9081 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 9082 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 9083 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9084 } 9085 9086 IdentifierInfo *Name = FD->getIdentifier(); 9087 if (!Name) 9088 return; 9089 if ((!getLangOpts().CPlusPlus && 9090 FD->getDeclContext()->isTranslationUnit()) || 9091 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 9092 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 9093 LinkageSpecDecl::lang_c)) { 9094 // Okay: this could be a libc/libm/Objective-C function we know 9095 // about. 9096 } else 9097 return; 9098 9099 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 9100 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 9101 // target-specific builtins, perhaps? 9102 if (!FD->getAttr<FormatAttr>()) 9103 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9104 "printf", 2, 9105 Name->isStr("vasprintf") ? 0 : 3)); 9106 } 9107 9108 if (Name->isStr("__CFStringMakeConstantString")) { 9109 // We already have a __builtin___CFStringMakeConstantString, 9110 // but builds that use -fno-constant-cfstrings don't go through that. 9111 if (!FD->getAttr<FormatArgAttr>()) 9112 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 9113 } 9114} 9115 9116TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 9117 TypeSourceInfo *TInfo) { 9118 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 9119 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 9120 9121 if (!TInfo) { 9122 assert(D.isInvalidType() && "no declarator info for valid type"); 9123 TInfo = Context.getTrivialTypeSourceInfo(T); 9124 } 9125 9126 // Scope manipulation handled by caller. 9127 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 9128 D.getLocStart(), 9129 D.getIdentifierLoc(), 9130 D.getIdentifier(), 9131 TInfo); 9132 9133 // Bail out immediately if we have an invalid declaration. 9134 if (D.isInvalidType()) { 9135 NewTD->setInvalidDecl(); 9136 return NewTD; 9137 } 9138 9139 if (D.getDeclSpec().isModulePrivateSpecified()) { 9140 if (CurContext->isFunctionOrMethod()) 9141 Diag(NewTD->getLocation(), diag::err_module_private_local) 9142 << 2 << NewTD->getDeclName() 9143 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9144 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9145 else 9146 NewTD->setModulePrivate(); 9147 } 9148 9149 // C++ [dcl.typedef]p8: 9150 // If the typedef declaration defines an unnamed class (or 9151 // enum), the first typedef-name declared by the declaration 9152 // to be that class type (or enum type) is used to denote the 9153 // class type (or enum type) for linkage purposes only. 9154 // We need to check whether the type was declared in the declaration. 9155 switch (D.getDeclSpec().getTypeSpecType()) { 9156 case TST_enum: 9157 case TST_struct: 9158 case TST_interface: 9159 case TST_union: 9160 case TST_class: { 9161 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 9162 9163 // Do nothing if the tag is not anonymous or already has an 9164 // associated typedef (from an earlier typedef in this decl group). 9165 if (tagFromDeclSpec->getIdentifier()) break; 9166 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 9167 9168 // A well-formed anonymous tag must always be a TUK_Definition. 9169 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 9170 9171 // The type must match the tag exactly; no qualifiers allowed. 9172 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 9173 break; 9174 9175 // Otherwise, set this is the anon-decl typedef for the tag. 9176 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 9177 break; 9178 } 9179 9180 default: 9181 break; 9182 } 9183 9184 return NewTD; 9185} 9186 9187 9188/// \brief Check that this is a valid underlying type for an enum declaration. 9189bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 9190 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 9191 QualType T = TI->getType(); 9192 9193 if (T->isDependentType()) 9194 return false; 9195 9196 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 9197 if (BT->isInteger()) 9198 return false; 9199 9200 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 9201 return true; 9202} 9203 9204/// Check whether this is a valid redeclaration of a previous enumeration. 9205/// \return true if the redeclaration was invalid. 9206bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 9207 QualType EnumUnderlyingTy, 9208 const EnumDecl *Prev) { 9209 bool IsFixed = !EnumUnderlyingTy.isNull(); 9210 9211 if (IsScoped != Prev->isScoped()) { 9212 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 9213 << Prev->isScoped(); 9214 Diag(Prev->getLocation(), diag::note_previous_use); 9215 return true; 9216 } 9217 9218 if (IsFixed && Prev->isFixed()) { 9219 if (!EnumUnderlyingTy->isDependentType() && 9220 !Prev->getIntegerType()->isDependentType() && 9221 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 9222 Prev->getIntegerType())) { 9223 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 9224 << EnumUnderlyingTy << Prev->getIntegerType(); 9225 Diag(Prev->getLocation(), diag::note_previous_use); 9226 return true; 9227 } 9228 } else if (IsFixed != Prev->isFixed()) { 9229 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 9230 << Prev->isFixed(); 9231 Diag(Prev->getLocation(), diag::note_previous_use); 9232 return true; 9233 } 9234 9235 return false; 9236} 9237 9238/// \brief Get diagnostic %select index for tag kind for 9239/// redeclaration diagnostic message. 9240/// WARNING: Indexes apply to particular diagnostics only! 9241/// 9242/// \returns diagnostic %select index. 9243static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 9244 switch (Tag) { 9245 case TTK_Struct: return 0; 9246 case TTK_Interface: return 1; 9247 case TTK_Class: return 2; 9248 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 9249 } 9250} 9251 9252/// \brief Determine if tag kind is a class-key compatible with 9253/// class for redeclaration (class, struct, or __interface). 9254/// 9255/// \returns true iff the tag kind is compatible. 9256static bool isClassCompatTagKind(TagTypeKind Tag) 9257{ 9258 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 9259} 9260 9261/// \brief Determine whether a tag with a given kind is acceptable 9262/// as a redeclaration of the given tag declaration. 9263/// 9264/// \returns true if the new tag kind is acceptable, false otherwise. 9265bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 9266 TagTypeKind NewTag, bool isDefinition, 9267 SourceLocation NewTagLoc, 9268 const IdentifierInfo &Name) { 9269 // C++ [dcl.type.elab]p3: 9270 // The class-key or enum keyword present in the 9271 // elaborated-type-specifier shall agree in kind with the 9272 // declaration to which the name in the elaborated-type-specifier 9273 // refers. This rule also applies to the form of 9274 // elaborated-type-specifier that declares a class-name or 9275 // friend class since it can be construed as referring to the 9276 // definition of the class. Thus, in any 9277 // elaborated-type-specifier, the enum keyword shall be used to 9278 // refer to an enumeration (7.2), the union class-key shall be 9279 // used to refer to a union (clause 9), and either the class or 9280 // struct class-key shall be used to refer to a class (clause 9) 9281 // declared using the class or struct class-key. 9282 TagTypeKind OldTag = Previous->getTagKind(); 9283 if (!isDefinition || !isClassCompatTagKind(NewTag)) 9284 if (OldTag == NewTag) 9285 return true; 9286 9287 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 9288 // Warn about the struct/class tag mismatch. 9289 bool isTemplate = false; 9290 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 9291 isTemplate = Record->getDescribedClassTemplate(); 9292 9293 if (!ActiveTemplateInstantiations.empty()) { 9294 // In a template instantiation, do not offer fix-its for tag mismatches 9295 // since they usually mess up the template instead of fixing the problem. 9296 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9297 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9298 << getRedeclDiagFromTagKind(OldTag); 9299 return true; 9300 } 9301 9302 if (isDefinition) { 9303 // On definitions, check previous tags and issue a fix-it for each 9304 // one that doesn't match the current tag. 9305 if (Previous->getDefinition()) { 9306 // Don't suggest fix-its for redefinitions. 9307 return true; 9308 } 9309 9310 bool previousMismatch = false; 9311 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 9312 E(Previous->redecls_end()); I != E; ++I) { 9313 if (I->getTagKind() != NewTag) { 9314 if (!previousMismatch) { 9315 previousMismatch = true; 9316 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 9317 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9318 << getRedeclDiagFromTagKind(I->getTagKind()); 9319 } 9320 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 9321 << getRedeclDiagFromTagKind(NewTag) 9322 << FixItHint::CreateReplacement(I->getInnerLocStart(), 9323 TypeWithKeyword::getTagTypeKindName(NewTag)); 9324 } 9325 } 9326 return true; 9327 } 9328 9329 // Check for a previous definition. If current tag and definition 9330 // are same type, do nothing. If no definition, but disagree with 9331 // with previous tag type, give a warning, but no fix-it. 9332 const TagDecl *Redecl = Previous->getDefinition() ? 9333 Previous->getDefinition() : Previous; 9334 if (Redecl->getTagKind() == NewTag) { 9335 return true; 9336 } 9337 9338 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9339 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9340 << getRedeclDiagFromTagKind(OldTag); 9341 Diag(Redecl->getLocation(), diag::note_previous_use); 9342 9343 // If there is a previous defintion, suggest a fix-it. 9344 if (Previous->getDefinition()) { 9345 Diag(NewTagLoc, diag::note_struct_class_suggestion) 9346 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 9347 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 9348 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 9349 } 9350 9351 return true; 9352 } 9353 return false; 9354} 9355 9356/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 9357/// former case, Name will be non-null. In the later case, Name will be null. 9358/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 9359/// reference/declaration/definition of a tag. 9360Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 9361 SourceLocation KWLoc, CXXScopeSpec &SS, 9362 IdentifierInfo *Name, SourceLocation NameLoc, 9363 AttributeList *Attr, AccessSpecifier AS, 9364 SourceLocation ModulePrivateLoc, 9365 MultiTemplateParamsArg TemplateParameterLists, 9366 bool &OwnedDecl, bool &IsDependent, 9367 SourceLocation ScopedEnumKWLoc, 9368 bool ScopedEnumUsesClassTag, 9369 TypeResult UnderlyingType) { 9370 // If this is not a definition, it must have a name. 9371 IdentifierInfo *OrigName = Name; 9372 assert((Name != 0 || TUK == TUK_Definition) && 9373 "Nameless record must be a definition!"); 9374 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 9375 9376 OwnedDecl = false; 9377 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9378 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 9379 9380 // FIXME: Check explicit specializations more carefully. 9381 bool isExplicitSpecialization = false; 9382 bool Invalid = false; 9383 9384 // We only need to do this matching if we have template parameters 9385 // or a scope specifier, which also conveniently avoids this work 9386 // for non-C++ cases. 9387 if (TemplateParameterLists.size() > 0 || 9388 (SS.isNotEmpty() && TUK != TUK_Reference)) { 9389 if (TemplateParameterList *TemplateParams 9390 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 9391 TemplateParameterLists.data(), 9392 TemplateParameterLists.size(), 9393 TUK == TUK_Friend, 9394 isExplicitSpecialization, 9395 Invalid)) { 9396 if (Kind == TTK_Enum) { 9397 Diag(KWLoc, diag::err_enum_template); 9398 return 0; 9399 } 9400 9401 if (TemplateParams->size() > 0) { 9402 // This is a declaration or definition of a class template (which may 9403 // be a member of another template). 9404 9405 if (Invalid) 9406 return 0; 9407 9408 OwnedDecl = false; 9409 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 9410 SS, Name, NameLoc, Attr, 9411 TemplateParams, AS, 9412 ModulePrivateLoc, 9413 TemplateParameterLists.size()-1, 9414 TemplateParameterLists.data()); 9415 return Result.get(); 9416 } else { 9417 // The "template<>" header is extraneous. 9418 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9419 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9420 isExplicitSpecialization = true; 9421 } 9422 } 9423 } 9424 9425 // Figure out the underlying type if this a enum declaration. We need to do 9426 // this early, because it's needed to detect if this is an incompatible 9427 // redeclaration. 9428 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 9429 9430 if (Kind == TTK_Enum) { 9431 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 9432 // No underlying type explicitly specified, or we failed to parse the 9433 // type, default to int. 9434 EnumUnderlying = Context.IntTy.getTypePtr(); 9435 else if (UnderlyingType.get()) { 9436 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 9437 // integral type; any cv-qualification is ignored. 9438 TypeSourceInfo *TI = 0; 9439 GetTypeFromParser(UnderlyingType.get(), &TI); 9440 EnumUnderlying = TI; 9441 9442 if (CheckEnumUnderlyingType(TI)) 9443 // Recover by falling back to int. 9444 EnumUnderlying = Context.IntTy.getTypePtr(); 9445 9446 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 9447 UPPC_FixedUnderlyingType)) 9448 EnumUnderlying = Context.IntTy.getTypePtr(); 9449 9450 } else if (getLangOpts().MicrosoftMode) 9451 // Microsoft enums are always of int type. 9452 EnumUnderlying = Context.IntTy.getTypePtr(); 9453 } 9454 9455 DeclContext *SearchDC = CurContext; 9456 DeclContext *DC = CurContext; 9457 bool isStdBadAlloc = false; 9458 9459 RedeclarationKind Redecl = ForRedeclaration; 9460 if (TUK == TUK_Friend || TUK == TUK_Reference) 9461 Redecl = NotForRedeclaration; 9462 9463 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 9464 9465 if (Name && SS.isNotEmpty()) { 9466 // We have a nested-name tag ('struct foo::bar'). 9467 9468 // Check for invalid 'foo::'. 9469 if (SS.isInvalid()) { 9470 Name = 0; 9471 goto CreateNewDecl; 9472 } 9473 9474 // If this is a friend or a reference to a class in a dependent 9475 // context, don't try to make a decl for it. 9476 if (TUK == TUK_Friend || TUK == TUK_Reference) { 9477 DC = computeDeclContext(SS, false); 9478 if (!DC) { 9479 IsDependent = true; 9480 return 0; 9481 } 9482 } else { 9483 DC = computeDeclContext(SS, true); 9484 if (!DC) { 9485 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 9486 << SS.getRange(); 9487 return 0; 9488 } 9489 } 9490 9491 if (RequireCompleteDeclContext(SS, DC)) 9492 return 0; 9493 9494 SearchDC = DC; 9495 // Look-up name inside 'foo::'. 9496 LookupQualifiedName(Previous, DC); 9497 9498 if (Previous.isAmbiguous()) 9499 return 0; 9500 9501 if (Previous.empty()) { 9502 // Name lookup did not find anything. However, if the 9503 // nested-name-specifier refers to the current instantiation, 9504 // and that current instantiation has any dependent base 9505 // classes, we might find something at instantiation time: treat 9506 // this as a dependent elaborated-type-specifier. 9507 // But this only makes any sense for reference-like lookups. 9508 if (Previous.wasNotFoundInCurrentInstantiation() && 9509 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9510 IsDependent = true; 9511 return 0; 9512 } 9513 9514 // A tag 'foo::bar' must already exist. 9515 Diag(NameLoc, diag::err_not_tag_in_scope) 9516 << Kind << Name << DC << SS.getRange(); 9517 Name = 0; 9518 Invalid = true; 9519 goto CreateNewDecl; 9520 } 9521 } else if (Name) { 9522 // If this is a named struct, check to see if there was a previous forward 9523 // declaration or definition. 9524 // FIXME: We're looking into outer scopes here, even when we 9525 // shouldn't be. Doing so can result in ambiguities that we 9526 // shouldn't be diagnosing. 9527 LookupName(Previous, S); 9528 9529 // When declaring or defining a tag, ignore ambiguities introduced 9530 // by types using'ed into this scope. 9531 if (Previous.isAmbiguous() && 9532 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 9533 LookupResult::Filter F = Previous.makeFilter(); 9534 while (F.hasNext()) { 9535 NamedDecl *ND = F.next(); 9536 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 9537 F.erase(); 9538 } 9539 F.done(); 9540 } 9541 9542 // C++11 [namespace.memdef]p3: 9543 // If the name in a friend declaration is neither qualified nor 9544 // a template-id and the declaration is a function or an 9545 // elaborated-type-specifier, the lookup to determine whether 9546 // the entity has been previously declared shall not consider 9547 // any scopes outside the innermost enclosing namespace. 9548 // 9549 // Does it matter that this should be by scope instead of by 9550 // semantic context? 9551 if (!Previous.empty() && TUK == TUK_Friend) { 9552 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 9553 LookupResult::Filter F = Previous.makeFilter(); 9554 while (F.hasNext()) { 9555 NamedDecl *ND = F.next(); 9556 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 9557 if (DC->isFileContext() && !EnclosingNS->Encloses(ND->getDeclContext())) 9558 F.erase(); 9559 } 9560 F.done(); 9561 } 9562 9563 // Note: there used to be some attempt at recovery here. 9564 if (Previous.isAmbiguous()) 9565 return 0; 9566 9567 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 9568 // FIXME: This makes sure that we ignore the contexts associated 9569 // with C structs, unions, and enums when looking for a matching 9570 // tag declaration or definition. See the similar lookup tweak 9571 // in Sema::LookupName; is there a better way to deal with this? 9572 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 9573 SearchDC = SearchDC->getParent(); 9574 } 9575 } else if (S->isFunctionPrototypeScope()) { 9576 // If this is an enum declaration in function prototype scope, set its 9577 // initial context to the translation unit. 9578 // FIXME: [citation needed] 9579 SearchDC = Context.getTranslationUnitDecl(); 9580 } 9581 9582 if (Previous.isSingleResult() && 9583 Previous.getFoundDecl()->isTemplateParameter()) { 9584 // Maybe we will complain about the shadowed template parameter. 9585 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 9586 // Just pretend that we didn't see the previous declaration. 9587 Previous.clear(); 9588 } 9589 9590 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 9591 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 9592 // This is a declaration of or a reference to "std::bad_alloc". 9593 isStdBadAlloc = true; 9594 9595 if (Previous.empty() && StdBadAlloc) { 9596 // std::bad_alloc has been implicitly declared (but made invisible to 9597 // name lookup). Fill in this implicit declaration as the previous 9598 // declaration, so that the declarations get chained appropriately. 9599 Previous.addDecl(getStdBadAlloc()); 9600 } 9601 } 9602 9603 // If we didn't find a previous declaration, and this is a reference 9604 // (or friend reference), move to the correct scope. In C++, we 9605 // also need to do a redeclaration lookup there, just in case 9606 // there's a shadow friend decl. 9607 if (Name && Previous.empty() && 9608 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9609 if (Invalid) goto CreateNewDecl; 9610 assert(SS.isEmpty()); 9611 9612 if (TUK == TUK_Reference) { 9613 // C++ [basic.scope.pdecl]p5: 9614 // -- for an elaborated-type-specifier of the form 9615 // 9616 // class-key identifier 9617 // 9618 // if the elaborated-type-specifier is used in the 9619 // decl-specifier-seq or parameter-declaration-clause of a 9620 // function defined in namespace scope, the identifier is 9621 // declared as a class-name in the namespace that contains 9622 // the declaration; otherwise, except as a friend 9623 // declaration, the identifier is declared in the smallest 9624 // non-class, non-function-prototype scope that contains the 9625 // declaration. 9626 // 9627 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 9628 // C structs and unions. 9629 // 9630 // It is an error in C++ to declare (rather than define) an enum 9631 // type, including via an elaborated type specifier. We'll 9632 // diagnose that later; for now, declare the enum in the same 9633 // scope as we would have picked for any other tag type. 9634 // 9635 // GNU C also supports this behavior as part of its incomplete 9636 // enum types extension, while GNU C++ does not. 9637 // 9638 // Find the context where we'll be declaring the tag. 9639 // FIXME: We would like to maintain the current DeclContext as the 9640 // lexical context, 9641 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 9642 SearchDC = SearchDC->getParent(); 9643 9644 // Find the scope where we'll be declaring the tag. 9645 while (S->isClassScope() || 9646 (getLangOpts().CPlusPlus && 9647 S->isFunctionPrototypeScope()) || 9648 ((S->getFlags() & Scope::DeclScope) == 0) || 9649 (S->getEntity() && 9650 ((DeclContext *)S->getEntity())->isTransparentContext())) 9651 S = S->getParent(); 9652 } else { 9653 assert(TUK == TUK_Friend); 9654 // C++ [namespace.memdef]p3: 9655 // If a friend declaration in a non-local class first declares a 9656 // class or function, the friend class or function is a member of 9657 // the innermost enclosing namespace. 9658 SearchDC = SearchDC->getEnclosingNamespaceContext(); 9659 } 9660 9661 // In C++, we need to do a redeclaration lookup to properly 9662 // diagnose some problems. 9663 if (getLangOpts().CPlusPlus) { 9664 Previous.setRedeclarationKind(ForRedeclaration); 9665 LookupQualifiedName(Previous, SearchDC); 9666 } 9667 } 9668 9669 if (!Previous.empty()) { 9670 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 9671 9672 // It's okay to have a tag decl in the same scope as a typedef 9673 // which hides a tag decl in the same scope. Finding this 9674 // insanity with a redeclaration lookup can only actually happen 9675 // in C++. 9676 // 9677 // This is also okay for elaborated-type-specifiers, which is 9678 // technically forbidden by the current standard but which is 9679 // okay according to the likely resolution of an open issue; 9680 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 9681 if (getLangOpts().CPlusPlus) { 9682 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9683 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 9684 TagDecl *Tag = TT->getDecl(); 9685 if (Tag->getDeclName() == Name && 9686 Tag->getDeclContext()->getRedeclContext() 9687 ->Equals(TD->getDeclContext()->getRedeclContext())) { 9688 PrevDecl = Tag; 9689 Previous.clear(); 9690 Previous.addDecl(Tag); 9691 Previous.resolveKind(); 9692 } 9693 } 9694 } 9695 } 9696 9697 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 9698 // If this is a use of a previous tag, or if the tag is already declared 9699 // in the same scope (so that the definition/declaration completes or 9700 // rementions the tag), reuse the decl. 9701 if (TUK == TUK_Reference || TUK == TUK_Friend || 9702 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 9703 // Make sure that this wasn't declared as an enum and now used as a 9704 // struct or something similar. 9705 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 9706 TUK == TUK_Definition, KWLoc, 9707 *Name)) { 9708 bool SafeToContinue 9709 = (PrevTagDecl->getTagKind() != TTK_Enum && 9710 Kind != TTK_Enum); 9711 if (SafeToContinue) 9712 Diag(KWLoc, diag::err_use_with_wrong_tag) 9713 << Name 9714 << FixItHint::CreateReplacement(SourceRange(KWLoc), 9715 PrevTagDecl->getKindName()); 9716 else 9717 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 9718 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 9719 9720 if (SafeToContinue) 9721 Kind = PrevTagDecl->getTagKind(); 9722 else { 9723 // Recover by making this an anonymous redefinition. 9724 Name = 0; 9725 Previous.clear(); 9726 Invalid = true; 9727 } 9728 } 9729 9730 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 9731 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 9732 9733 // If this is an elaborated-type-specifier for a scoped enumeration, 9734 // the 'class' keyword is not necessary and not permitted. 9735 if (TUK == TUK_Reference || TUK == TUK_Friend) { 9736 if (ScopedEnum) 9737 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 9738 << PrevEnum->isScoped() 9739 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 9740 return PrevTagDecl; 9741 } 9742 9743 QualType EnumUnderlyingTy; 9744 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9745 EnumUnderlyingTy = TI->getType(); 9746 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 9747 EnumUnderlyingTy = QualType(T, 0); 9748 9749 // All conflicts with previous declarations are recovered by 9750 // returning the previous declaration, unless this is a definition, 9751 // in which case we want the caller to bail out. 9752 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 9753 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 9754 return TUK == TUK_Declaration ? PrevTagDecl : 0; 9755 } 9756 9757 if (!Invalid) { 9758 // If this is a use, just return the declaration we found. 9759 9760 // FIXME: In the future, return a variant or some other clue 9761 // for the consumer of this Decl to know it doesn't own it. 9762 // For our current ASTs this shouldn't be a problem, but will 9763 // need to be changed with DeclGroups. 9764 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 9765 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 9766 return PrevTagDecl; 9767 9768 // Diagnose attempts to redefine a tag. 9769 if (TUK == TUK_Definition) { 9770 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 9771 // If we're defining a specialization and the previous definition 9772 // is from an implicit instantiation, don't emit an error 9773 // here; we'll catch this in the general case below. 9774 bool IsExplicitSpecializationAfterInstantiation = false; 9775 if (isExplicitSpecialization) { 9776 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 9777 IsExplicitSpecializationAfterInstantiation = 9778 RD->getTemplateSpecializationKind() != 9779 TSK_ExplicitSpecialization; 9780 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 9781 IsExplicitSpecializationAfterInstantiation = 9782 ED->getTemplateSpecializationKind() != 9783 TSK_ExplicitSpecialization; 9784 } 9785 9786 if (!IsExplicitSpecializationAfterInstantiation) { 9787 // A redeclaration in function prototype scope in C isn't 9788 // visible elsewhere, so merely issue a warning. 9789 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 9790 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 9791 else 9792 Diag(NameLoc, diag::err_redefinition) << Name; 9793 Diag(Def->getLocation(), diag::note_previous_definition); 9794 // If this is a redefinition, recover by making this 9795 // struct be anonymous, which will make any later 9796 // references get the previous definition. 9797 Name = 0; 9798 Previous.clear(); 9799 Invalid = true; 9800 } 9801 } else { 9802 // If the type is currently being defined, complain 9803 // about a nested redefinition. 9804 const TagType *Tag 9805 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 9806 if (Tag->isBeingDefined()) { 9807 Diag(NameLoc, diag::err_nested_redefinition) << Name; 9808 Diag(PrevTagDecl->getLocation(), 9809 diag::note_previous_definition); 9810 Name = 0; 9811 Previous.clear(); 9812 Invalid = true; 9813 } 9814 } 9815 9816 // Okay, this is definition of a previously declared or referenced 9817 // tag PrevDecl. We're going to create a new Decl for it. 9818 } 9819 } 9820 // If we get here we have (another) forward declaration or we 9821 // have a definition. Just create a new decl. 9822 9823 } else { 9824 // If we get here, this is a definition of a new tag type in a nested 9825 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 9826 // new decl/type. We set PrevDecl to NULL so that the entities 9827 // have distinct types. 9828 Previous.clear(); 9829 } 9830 // If we get here, we're going to create a new Decl. If PrevDecl 9831 // is non-NULL, it's a definition of the tag declared by 9832 // PrevDecl. If it's NULL, we have a new definition. 9833 9834 9835 // Otherwise, PrevDecl is not a tag, but was found with tag 9836 // lookup. This is only actually possible in C++, where a few 9837 // things like templates still live in the tag namespace. 9838 } else { 9839 // Use a better diagnostic if an elaborated-type-specifier 9840 // found the wrong kind of type on the first 9841 // (non-redeclaration) lookup. 9842 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 9843 !Previous.isForRedeclaration()) { 9844 unsigned Kind = 0; 9845 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9846 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9847 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9848 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 9849 Diag(PrevDecl->getLocation(), diag::note_declared_at); 9850 Invalid = true; 9851 9852 // Otherwise, only diagnose if the declaration is in scope. 9853 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 9854 isExplicitSpecialization)) { 9855 // do nothing 9856 9857 // Diagnose implicit declarations introduced by elaborated types. 9858 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 9859 unsigned Kind = 0; 9860 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9861 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9862 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9863 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 9864 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9865 Invalid = true; 9866 9867 // Otherwise it's a declaration. Call out a particularly common 9868 // case here. 9869 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9870 unsigned Kind = 0; 9871 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 9872 Diag(NameLoc, diag::err_tag_definition_of_typedef) 9873 << Name << Kind << TND->getUnderlyingType(); 9874 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9875 Invalid = true; 9876 9877 // Otherwise, diagnose. 9878 } else { 9879 // The tag name clashes with something else in the target scope, 9880 // issue an error and recover by making this tag be anonymous. 9881 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 9882 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9883 Name = 0; 9884 Invalid = true; 9885 } 9886 9887 // The existing declaration isn't relevant to us; we're in a 9888 // new scope, so clear out the previous declaration. 9889 Previous.clear(); 9890 } 9891 } 9892 9893CreateNewDecl: 9894 9895 TagDecl *PrevDecl = 0; 9896 if (Previous.isSingleResult()) 9897 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 9898 9899 // If there is an identifier, use the location of the identifier as the 9900 // location of the decl, otherwise use the location of the struct/union 9901 // keyword. 9902 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 9903 9904 // Otherwise, create a new declaration. If there is a previous 9905 // declaration of the same entity, the two will be linked via 9906 // PrevDecl. 9907 TagDecl *New; 9908 9909 bool IsForwardReference = false; 9910 if (Kind == TTK_Enum) { 9911 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9912 // enum X { A, B, C } D; D should chain to X. 9913 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 9914 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 9915 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 9916 // If this is an undefined enum, warn. 9917 if (TUK != TUK_Definition && !Invalid) { 9918 TagDecl *Def; 9919 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 9920 cast<EnumDecl>(New)->isFixed()) { 9921 // C++0x: 7.2p2: opaque-enum-declaration. 9922 // Conflicts are diagnosed above. Do nothing. 9923 } 9924 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 9925 Diag(Loc, diag::ext_forward_ref_enum_def) 9926 << New; 9927 Diag(Def->getLocation(), diag::note_previous_definition); 9928 } else { 9929 unsigned DiagID = diag::ext_forward_ref_enum; 9930 if (getLangOpts().MicrosoftMode) 9931 DiagID = diag::ext_ms_forward_ref_enum; 9932 else if (getLangOpts().CPlusPlus) 9933 DiagID = diag::err_forward_ref_enum; 9934 Diag(Loc, DiagID); 9935 9936 // If this is a forward-declared reference to an enumeration, make a 9937 // note of it; we won't actually be introducing the declaration into 9938 // the declaration context. 9939 if (TUK == TUK_Reference) 9940 IsForwardReference = true; 9941 } 9942 } 9943 9944 if (EnumUnderlying) { 9945 EnumDecl *ED = cast<EnumDecl>(New); 9946 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9947 ED->setIntegerTypeSourceInfo(TI); 9948 else 9949 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 9950 ED->setPromotionType(ED->getIntegerType()); 9951 } 9952 9953 } else { 9954 // struct/union/class 9955 9956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9957 // struct X { int A; } D; D should chain to X. 9958 if (getLangOpts().CPlusPlus) { 9959 // FIXME: Look for a way to use RecordDecl for simple structs. 9960 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9961 cast_or_null<CXXRecordDecl>(PrevDecl)); 9962 9963 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 9964 StdBadAlloc = cast<CXXRecordDecl>(New); 9965 } else 9966 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9967 cast_or_null<RecordDecl>(PrevDecl)); 9968 } 9969 9970 // Maybe add qualifier info. 9971 if (SS.isNotEmpty()) { 9972 if (SS.isSet()) { 9973 // If this is either a declaration or a definition, check the 9974 // nested-name-specifier against the current context. We don't do this 9975 // for explicit specializations, because they have similar checking 9976 // (with more specific diagnostics) in the call to 9977 // CheckMemberSpecialization, below. 9978 if (!isExplicitSpecialization && 9979 (TUK == TUK_Definition || TUK == TUK_Declaration) && 9980 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 9981 Invalid = true; 9982 9983 New->setQualifierInfo(SS.getWithLocInContext(Context)); 9984 if (TemplateParameterLists.size() > 0) { 9985 New->setTemplateParameterListsInfo(Context, 9986 TemplateParameterLists.size(), 9987 TemplateParameterLists.data()); 9988 } 9989 } 9990 else 9991 Invalid = true; 9992 } 9993 9994 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 9995 // Add alignment attributes if necessary; these attributes are checked when 9996 // the ASTContext lays out the structure. 9997 // 9998 // It is important for implementing the correct semantics that this 9999 // happen here (in act on tag decl). The #pragma pack stack is 10000 // maintained as a result of parser callbacks which can occur at 10001 // many points during the parsing of a struct declaration (because 10002 // the #pragma tokens are effectively skipped over during the 10003 // parsing of the struct). 10004 if (TUK == TUK_Definition) { 10005 AddAlignmentAttributesForRecord(RD); 10006 AddMsStructLayoutForRecord(RD); 10007 } 10008 } 10009 10010 if (ModulePrivateLoc.isValid()) { 10011 if (isExplicitSpecialization) 10012 Diag(New->getLocation(), diag::err_module_private_specialization) 10013 << 2 10014 << FixItHint::CreateRemoval(ModulePrivateLoc); 10015 // __module_private__ does not apply to local classes. However, we only 10016 // diagnose this as an error when the declaration specifiers are 10017 // freestanding. Here, we just ignore the __module_private__. 10018 else if (!SearchDC->isFunctionOrMethod()) 10019 New->setModulePrivate(); 10020 } 10021 10022 // If this is a specialization of a member class (of a class template), 10023 // check the specialization. 10024 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 10025 Invalid = true; 10026 10027 if (Invalid) 10028 New->setInvalidDecl(); 10029 10030 if (Attr) 10031 ProcessDeclAttributeList(S, New, Attr); 10032 10033 // If we're declaring or defining a tag in function prototype scope 10034 // in C, note that this type can only be used within the function. 10035 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 10036 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 10037 10038 // Set the lexical context. If the tag has a C++ scope specifier, the 10039 // lexical context will be different from the semantic context. 10040 New->setLexicalDeclContext(CurContext); 10041 10042 // Mark this as a friend decl if applicable. 10043 // In Microsoft mode, a friend declaration also acts as a forward 10044 // declaration so we always pass true to setObjectOfFriendDecl to make 10045 // the tag name visible. 10046 if (TUK == TUK_Friend) 10047 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 10048 getLangOpts().MicrosoftExt); 10049 10050 // Set the access specifier. 10051 if (!Invalid && SearchDC->isRecord()) 10052 SetMemberAccessSpecifier(New, PrevDecl, AS); 10053 10054 if (TUK == TUK_Definition) 10055 New->startDefinition(); 10056 10057 // If this has an identifier, add it to the scope stack. 10058 if (TUK == TUK_Friend) { 10059 // We might be replacing an existing declaration in the lookup tables; 10060 // if so, borrow its access specifier. 10061 if (PrevDecl) 10062 New->setAccess(PrevDecl->getAccess()); 10063 10064 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 10065 DC->makeDeclVisibleInContext(New); 10066 if (Name) // can be null along some error paths 10067 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10068 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 10069 } else if (Name) { 10070 S = getNonFieldDeclScope(S); 10071 PushOnScopeChains(New, S, !IsForwardReference); 10072 if (IsForwardReference) 10073 SearchDC->makeDeclVisibleInContext(New); 10074 10075 } else { 10076 CurContext->addDecl(New); 10077 } 10078 10079 // If this is the C FILE type, notify the AST context. 10080 if (IdentifierInfo *II = New->getIdentifier()) 10081 if (!New->isInvalidDecl() && 10082 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 10083 II->isStr("FILE")) 10084 Context.setFILEDecl(New); 10085 10086 // If we were in function prototype scope (and not in C++ mode), add this 10087 // tag to the list of decls to inject into the function definition scope. 10088 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 10089 InFunctionDeclarator && Name) 10090 DeclsInPrototypeScope.push_back(New); 10091 10092 if (PrevDecl) 10093 mergeDeclAttributes(New, PrevDecl); 10094 10095 // If there's a #pragma GCC visibility in scope, set the visibility of this 10096 // record. 10097 AddPushedVisibilityAttribute(New); 10098 10099 OwnedDecl = true; 10100 // In C++, don't return an invalid declaration. We can't recover well from 10101 // the cases where we make the type anonymous. 10102 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 10103} 10104 10105void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 10106 AdjustDeclIfTemplate(TagD); 10107 TagDecl *Tag = cast<TagDecl>(TagD); 10108 10109 // Enter the tag context. 10110 PushDeclContext(S, Tag); 10111 10112 ActOnDocumentableDecl(TagD); 10113 10114 // If there's a #pragma GCC visibility in scope, set the visibility of this 10115 // record. 10116 AddPushedVisibilityAttribute(Tag); 10117} 10118 10119Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 10120 assert(isa<ObjCContainerDecl>(IDecl) && 10121 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 10122 DeclContext *OCD = cast<DeclContext>(IDecl); 10123 assert(getContainingDC(OCD) == CurContext && 10124 "The next DeclContext should be lexically contained in the current one."); 10125 CurContext = OCD; 10126 return IDecl; 10127} 10128 10129void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 10130 SourceLocation FinalLoc, 10131 SourceLocation LBraceLoc) { 10132 AdjustDeclIfTemplate(TagD); 10133 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 10134 10135 FieldCollector->StartClass(); 10136 10137 if (!Record->getIdentifier()) 10138 return; 10139 10140 if (FinalLoc.isValid()) 10141 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 10142 10143 // C++ [class]p2: 10144 // [...] The class-name is also inserted into the scope of the 10145 // class itself; this is known as the injected-class-name. For 10146 // purposes of access checking, the injected-class-name is treated 10147 // as if it were a public member name. 10148 CXXRecordDecl *InjectedClassName 10149 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 10150 Record->getLocStart(), Record->getLocation(), 10151 Record->getIdentifier(), 10152 /*PrevDecl=*/0, 10153 /*DelayTypeCreation=*/true); 10154 Context.getTypeDeclType(InjectedClassName, Record); 10155 InjectedClassName->setImplicit(); 10156 InjectedClassName->setAccess(AS_public); 10157 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 10158 InjectedClassName->setDescribedClassTemplate(Template); 10159 PushOnScopeChains(InjectedClassName, S); 10160 assert(InjectedClassName->isInjectedClassName() && 10161 "Broken injected-class-name"); 10162} 10163 10164void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 10165 SourceLocation RBraceLoc) { 10166 AdjustDeclIfTemplate(TagD); 10167 TagDecl *Tag = cast<TagDecl>(TagD); 10168 Tag->setRBraceLoc(RBraceLoc); 10169 10170 // Make sure we "complete" the definition even it is invalid. 10171 if (Tag->isBeingDefined()) { 10172 assert(Tag->isInvalidDecl() && "We should already have completed it"); 10173 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10174 RD->completeDefinition(); 10175 } 10176 10177 if (isa<CXXRecordDecl>(Tag)) 10178 FieldCollector->FinishClass(); 10179 10180 // Exit this scope of this tag's definition. 10181 PopDeclContext(); 10182 10183 if (getCurLexicalContext()->isObjCContainer() && 10184 Tag->getDeclContext()->isFileContext()) 10185 Tag->setTopLevelDeclInObjCContainer(); 10186 10187 // Notify the consumer that we've defined a tag. 10188 Consumer.HandleTagDeclDefinition(Tag); 10189} 10190 10191void Sema::ActOnObjCContainerFinishDefinition() { 10192 // Exit this scope of this interface definition. 10193 PopDeclContext(); 10194} 10195 10196void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 10197 assert(DC == CurContext && "Mismatch of container contexts"); 10198 OriginalLexicalContext = DC; 10199 ActOnObjCContainerFinishDefinition(); 10200} 10201 10202void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 10203 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 10204 OriginalLexicalContext = 0; 10205} 10206 10207void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 10208 AdjustDeclIfTemplate(TagD); 10209 TagDecl *Tag = cast<TagDecl>(TagD); 10210 Tag->setInvalidDecl(); 10211 10212 // Make sure we "complete" the definition even it is invalid. 10213 if (Tag->isBeingDefined()) { 10214 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10215 RD->completeDefinition(); 10216 } 10217 10218 // We're undoing ActOnTagStartDefinition here, not 10219 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 10220 // the FieldCollector. 10221 10222 PopDeclContext(); 10223} 10224 10225// Note that FieldName may be null for anonymous bitfields. 10226ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 10227 IdentifierInfo *FieldName, 10228 QualType FieldTy, Expr *BitWidth, 10229 bool *ZeroWidth) { 10230 // Default to true; that shouldn't confuse checks for emptiness 10231 if (ZeroWidth) 10232 *ZeroWidth = true; 10233 10234 // C99 6.7.2.1p4 - verify the field type. 10235 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 10236 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 10237 // Handle incomplete types with specific error. 10238 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 10239 return ExprError(); 10240 if (FieldName) 10241 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 10242 << FieldName << FieldTy << BitWidth->getSourceRange(); 10243 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 10244 << FieldTy << BitWidth->getSourceRange(); 10245 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 10246 UPPC_BitFieldWidth)) 10247 return ExprError(); 10248 10249 // If the bit-width is type- or value-dependent, don't try to check 10250 // it now. 10251 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 10252 return Owned(BitWidth); 10253 10254 llvm::APSInt Value; 10255 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 10256 if (ICE.isInvalid()) 10257 return ICE; 10258 BitWidth = ICE.take(); 10259 10260 if (Value != 0 && ZeroWidth) 10261 *ZeroWidth = false; 10262 10263 // Zero-width bitfield is ok for anonymous field. 10264 if (Value == 0 && FieldName) 10265 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 10266 10267 if (Value.isSigned() && Value.isNegative()) { 10268 if (FieldName) 10269 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 10270 << FieldName << Value.toString(10); 10271 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 10272 << Value.toString(10); 10273 } 10274 10275 if (!FieldTy->isDependentType()) { 10276 uint64_t TypeSize = Context.getTypeSize(FieldTy); 10277 if (Value.getZExtValue() > TypeSize) { 10278 if (!getLangOpts().CPlusPlus) { 10279 if (FieldName) 10280 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 10281 << FieldName << (unsigned)Value.getZExtValue() 10282 << (unsigned)TypeSize; 10283 10284 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 10285 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10286 } 10287 10288 if (FieldName) 10289 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 10290 << FieldName << (unsigned)Value.getZExtValue() 10291 << (unsigned)TypeSize; 10292 else 10293 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 10294 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10295 } 10296 } 10297 10298 return Owned(BitWidth); 10299} 10300 10301/// ActOnField - Each field of a C struct/union is passed into this in order 10302/// to create a FieldDecl object for it. 10303Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 10304 Declarator &D, Expr *BitfieldWidth) { 10305 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 10306 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 10307 /*InitStyle=*/ICIS_NoInit, AS_public); 10308 return Res; 10309} 10310 10311/// HandleField - Analyze a field of a C struct or a C++ data member. 10312/// 10313FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 10314 SourceLocation DeclStart, 10315 Declarator &D, Expr *BitWidth, 10316 InClassInitStyle InitStyle, 10317 AccessSpecifier AS) { 10318 IdentifierInfo *II = D.getIdentifier(); 10319 SourceLocation Loc = DeclStart; 10320 if (II) Loc = D.getIdentifierLoc(); 10321 10322 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10323 QualType T = TInfo->getType(); 10324 if (getLangOpts().CPlusPlus) { 10325 CheckExtraCXXDefaultArguments(D); 10326 10327 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10328 UPPC_DataMemberType)) { 10329 D.setInvalidType(); 10330 T = Context.IntTy; 10331 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 10332 } 10333 } 10334 10335 // TR 18037 does not allow fields to be declared with address spaces. 10336 if (T.getQualifiers().hasAddressSpace()) { 10337 Diag(Loc, diag::err_field_with_address_space); 10338 D.setInvalidType(); 10339 } 10340 10341 // OpenCL 1.2 spec, s6.9 r: 10342 // The event type cannot be used to declare a structure or union field. 10343 if (LangOpts.OpenCL && T->isEventT()) { 10344 Diag(Loc, diag::err_event_t_struct_field); 10345 D.setInvalidType(); 10346 } 10347 10348 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 10349 10350 if (D.getDeclSpec().isThreadSpecified()) 10351 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 10352 10353 // Check to see if this name was declared as a member previously 10354 NamedDecl *PrevDecl = 0; 10355 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 10356 LookupName(Previous, S); 10357 switch (Previous.getResultKind()) { 10358 case LookupResult::Found: 10359 case LookupResult::FoundUnresolvedValue: 10360 PrevDecl = Previous.getAsSingle<NamedDecl>(); 10361 break; 10362 10363 case LookupResult::FoundOverloaded: 10364 PrevDecl = Previous.getRepresentativeDecl(); 10365 break; 10366 10367 case LookupResult::NotFound: 10368 case LookupResult::NotFoundInCurrentInstantiation: 10369 case LookupResult::Ambiguous: 10370 break; 10371 } 10372 Previous.suppressDiagnostics(); 10373 10374 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10375 // Maybe we will complain about the shadowed template parameter. 10376 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10377 // Just pretend that we didn't see the previous declaration. 10378 PrevDecl = 0; 10379 } 10380 10381 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 10382 PrevDecl = 0; 10383 10384 bool Mutable 10385 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 10386 SourceLocation TSSL = D.getLocStart(); 10387 FieldDecl *NewFD 10388 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 10389 TSSL, AS, PrevDecl, &D); 10390 10391 if (NewFD->isInvalidDecl()) 10392 Record->setInvalidDecl(); 10393 10394 if (D.getDeclSpec().isModulePrivateSpecified()) 10395 NewFD->setModulePrivate(); 10396 10397 if (NewFD->isInvalidDecl() && PrevDecl) { 10398 // Don't introduce NewFD into scope; there's already something 10399 // with the same name in the same scope. 10400 } else if (II) { 10401 PushOnScopeChains(NewFD, S); 10402 } else 10403 Record->addDecl(NewFD); 10404 10405 return NewFD; 10406} 10407 10408/// \brief Build a new FieldDecl and check its well-formedness. 10409/// 10410/// This routine builds a new FieldDecl given the fields name, type, 10411/// record, etc. \p PrevDecl should refer to any previous declaration 10412/// with the same name and in the same scope as the field to be 10413/// created. 10414/// 10415/// \returns a new FieldDecl. 10416/// 10417/// \todo The Declarator argument is a hack. It will be removed once 10418FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 10419 TypeSourceInfo *TInfo, 10420 RecordDecl *Record, SourceLocation Loc, 10421 bool Mutable, Expr *BitWidth, 10422 InClassInitStyle InitStyle, 10423 SourceLocation TSSL, 10424 AccessSpecifier AS, NamedDecl *PrevDecl, 10425 Declarator *D) { 10426 IdentifierInfo *II = Name.getAsIdentifierInfo(); 10427 bool InvalidDecl = false; 10428 if (D) InvalidDecl = D->isInvalidType(); 10429 10430 // If we receive a broken type, recover by assuming 'int' and 10431 // marking this declaration as invalid. 10432 if (T.isNull()) { 10433 InvalidDecl = true; 10434 T = Context.IntTy; 10435 } 10436 10437 QualType EltTy = Context.getBaseElementType(T); 10438 if (!EltTy->isDependentType()) { 10439 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 10440 // Fields of incomplete type force their record to be invalid. 10441 Record->setInvalidDecl(); 10442 InvalidDecl = true; 10443 } else { 10444 NamedDecl *Def; 10445 EltTy->isIncompleteType(&Def); 10446 if (Def && Def->isInvalidDecl()) { 10447 Record->setInvalidDecl(); 10448 InvalidDecl = true; 10449 } 10450 } 10451 } 10452 10453 // OpenCL v1.2 s6.9.c: bitfields are not supported. 10454 if (BitWidth && getLangOpts().OpenCL) { 10455 Diag(Loc, diag::err_opencl_bitfields); 10456 InvalidDecl = true; 10457 } 10458 10459 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10460 // than a variably modified type. 10461 if (!InvalidDecl && T->isVariablyModifiedType()) { 10462 bool SizeIsNegative; 10463 llvm::APSInt Oversized; 10464 10465 TypeSourceInfo *FixedTInfo = 10466 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 10467 SizeIsNegative, 10468 Oversized); 10469 if (FixedTInfo) { 10470 Diag(Loc, diag::warn_illegal_constant_array_size); 10471 TInfo = FixedTInfo; 10472 T = FixedTInfo->getType(); 10473 } else { 10474 if (SizeIsNegative) 10475 Diag(Loc, diag::err_typecheck_negative_array_size); 10476 else if (Oversized.getBoolValue()) 10477 Diag(Loc, diag::err_array_too_large) 10478 << Oversized.toString(10); 10479 else 10480 Diag(Loc, diag::err_typecheck_field_variable_size); 10481 InvalidDecl = true; 10482 } 10483 } 10484 10485 // Fields can not have abstract class types 10486 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 10487 diag::err_abstract_type_in_decl, 10488 AbstractFieldType)) 10489 InvalidDecl = true; 10490 10491 bool ZeroWidth = false; 10492 // If this is declared as a bit-field, check the bit-field. 10493 if (!InvalidDecl && BitWidth) { 10494 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 10495 if (!BitWidth) { 10496 InvalidDecl = true; 10497 BitWidth = 0; 10498 ZeroWidth = false; 10499 } 10500 } 10501 10502 // Check that 'mutable' is consistent with the type of the declaration. 10503 if (!InvalidDecl && Mutable) { 10504 unsigned DiagID = 0; 10505 if (T->isReferenceType()) 10506 DiagID = diag::err_mutable_reference; 10507 else if (T.isConstQualified()) 10508 DiagID = diag::err_mutable_const; 10509 10510 if (DiagID) { 10511 SourceLocation ErrLoc = Loc; 10512 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 10513 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 10514 Diag(ErrLoc, DiagID); 10515 Mutable = false; 10516 InvalidDecl = true; 10517 } 10518 } 10519 10520 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 10521 BitWidth, Mutable, InitStyle); 10522 if (InvalidDecl) 10523 NewFD->setInvalidDecl(); 10524 10525 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 10526 Diag(Loc, diag::err_duplicate_member) << II; 10527 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10528 NewFD->setInvalidDecl(); 10529 } 10530 10531 if (!InvalidDecl && getLangOpts().CPlusPlus) { 10532 if (Record->isUnion()) { 10533 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10534 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10535 if (RDecl->getDefinition()) { 10536 // C++ [class.union]p1: An object of a class with a non-trivial 10537 // constructor, a non-trivial copy constructor, a non-trivial 10538 // destructor, or a non-trivial copy assignment operator 10539 // cannot be a member of a union, nor can an array of such 10540 // objects. 10541 if (CheckNontrivialField(NewFD)) 10542 NewFD->setInvalidDecl(); 10543 } 10544 } 10545 10546 // C++ [class.union]p1: If a union contains a member of reference type, 10547 // the program is ill-formed. 10548 if (EltTy->isReferenceType()) { 10549 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 10550 << NewFD->getDeclName() << EltTy; 10551 NewFD->setInvalidDecl(); 10552 } 10553 } 10554 } 10555 10556 // FIXME: We need to pass in the attributes given an AST 10557 // representation, not a parser representation. 10558 if (D) { 10559 // FIXME: What to pass instead of TUScope? 10560 ProcessDeclAttributes(TUScope, NewFD, *D); 10561 10562 if (NewFD->hasAttrs()) 10563 CheckAlignasUnderalignment(NewFD); 10564 } 10565 10566 // In auto-retain/release, infer strong retension for fields of 10567 // retainable type. 10568 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 10569 NewFD->setInvalidDecl(); 10570 10571 if (T.isObjCGCWeak()) 10572 Diag(Loc, diag::warn_attribute_weak_on_field); 10573 10574 NewFD->setAccess(AS); 10575 return NewFD; 10576} 10577 10578bool Sema::CheckNontrivialField(FieldDecl *FD) { 10579 assert(FD); 10580 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 10581 10582 if (FD->isInvalidDecl()) 10583 return true; 10584 10585 QualType EltTy = Context.getBaseElementType(FD->getType()); 10586 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10587 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10588 if (RDecl->getDefinition()) { 10589 // We check for copy constructors before constructors 10590 // because otherwise we'll never get complaints about 10591 // copy constructors. 10592 10593 CXXSpecialMember member = CXXInvalid; 10594 // We're required to check for any non-trivial constructors. Since the 10595 // implicit default constructor is suppressed if there are any 10596 // user-declared constructors, we just need to check that there is a 10597 // trivial default constructor and a trivial copy constructor. (We don't 10598 // worry about move constructors here, since this is a C++98 check.) 10599 if (RDecl->hasNonTrivialCopyConstructor()) 10600 member = CXXCopyConstructor; 10601 else if (!RDecl->hasTrivialDefaultConstructor()) 10602 member = CXXDefaultConstructor; 10603 else if (RDecl->hasNonTrivialCopyAssignment()) 10604 member = CXXCopyAssignment; 10605 else if (RDecl->hasNonTrivialDestructor()) 10606 member = CXXDestructor; 10607 10608 if (member != CXXInvalid) { 10609 if (!getLangOpts().CPlusPlus11 && 10610 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 10611 // Objective-C++ ARC: it is an error to have a non-trivial field of 10612 // a union. However, system headers in Objective-C programs 10613 // occasionally have Objective-C lifetime objects within unions, 10614 // and rather than cause the program to fail, we make those 10615 // members unavailable. 10616 SourceLocation Loc = FD->getLocation(); 10617 if (getSourceManager().isInSystemHeader(Loc)) { 10618 if (!FD->hasAttr<UnavailableAttr>()) 10619 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 10620 "this system field has retaining ownership")); 10621 return false; 10622 } 10623 } 10624 10625 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 10626 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 10627 diag::err_illegal_union_or_anon_struct_member) 10628 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 10629 DiagnoseNontrivial(RDecl, member); 10630 return !getLangOpts().CPlusPlus11; 10631 } 10632 } 10633 } 10634 10635 return false; 10636} 10637 10638/// TranslateIvarVisibility - Translate visibility from a token ID to an 10639/// AST enum value. 10640static ObjCIvarDecl::AccessControl 10641TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 10642 switch (ivarVisibility) { 10643 default: llvm_unreachable("Unknown visitibility kind"); 10644 case tok::objc_private: return ObjCIvarDecl::Private; 10645 case tok::objc_public: return ObjCIvarDecl::Public; 10646 case tok::objc_protected: return ObjCIvarDecl::Protected; 10647 case tok::objc_package: return ObjCIvarDecl::Package; 10648 } 10649} 10650 10651/// ActOnIvar - Each ivar field of an objective-c class is passed into this 10652/// in order to create an IvarDecl object for it. 10653Decl *Sema::ActOnIvar(Scope *S, 10654 SourceLocation DeclStart, 10655 Declarator &D, Expr *BitfieldWidth, 10656 tok::ObjCKeywordKind Visibility) { 10657 10658 IdentifierInfo *II = D.getIdentifier(); 10659 Expr *BitWidth = (Expr*)BitfieldWidth; 10660 SourceLocation Loc = DeclStart; 10661 if (II) Loc = D.getIdentifierLoc(); 10662 10663 // FIXME: Unnamed fields can be handled in various different ways, for 10664 // example, unnamed unions inject all members into the struct namespace! 10665 10666 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10667 QualType T = TInfo->getType(); 10668 10669 if (BitWidth) { 10670 // 6.7.2.1p3, 6.7.2.1p4 10671 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 10672 if (!BitWidth) 10673 D.setInvalidType(); 10674 } else { 10675 // Not a bitfield. 10676 10677 // validate II. 10678 10679 } 10680 if (T->isReferenceType()) { 10681 Diag(Loc, diag::err_ivar_reference_type); 10682 D.setInvalidType(); 10683 } 10684 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10685 // than a variably modified type. 10686 else if (T->isVariablyModifiedType()) { 10687 Diag(Loc, diag::err_typecheck_ivar_variable_size); 10688 D.setInvalidType(); 10689 } 10690 10691 // Get the visibility (access control) for this ivar. 10692 ObjCIvarDecl::AccessControl ac = 10693 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 10694 : ObjCIvarDecl::None; 10695 // Must set ivar's DeclContext to its enclosing interface. 10696 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 10697 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 10698 return 0; 10699 ObjCContainerDecl *EnclosingContext; 10700 if (ObjCImplementationDecl *IMPDecl = 10701 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10702 if (LangOpts.ObjCRuntime.isFragile()) { 10703 // Case of ivar declared in an implementation. Context is that of its class. 10704 EnclosingContext = IMPDecl->getClassInterface(); 10705 assert(EnclosingContext && "Implementation has no class interface!"); 10706 } 10707 else 10708 EnclosingContext = EnclosingDecl; 10709 } else { 10710 if (ObjCCategoryDecl *CDecl = 10711 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10712 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 10713 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 10714 return 0; 10715 } 10716 } 10717 EnclosingContext = EnclosingDecl; 10718 } 10719 10720 // Construct the decl. 10721 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 10722 DeclStart, Loc, II, T, 10723 TInfo, ac, (Expr *)BitfieldWidth); 10724 10725 if (II) { 10726 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 10727 ForRedeclaration); 10728 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 10729 && !isa<TagDecl>(PrevDecl)) { 10730 Diag(Loc, diag::err_duplicate_member) << II; 10731 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10732 NewID->setInvalidDecl(); 10733 } 10734 } 10735 10736 // Process attributes attached to the ivar. 10737 ProcessDeclAttributes(S, NewID, D); 10738 10739 if (D.isInvalidType()) 10740 NewID->setInvalidDecl(); 10741 10742 // In ARC, infer 'retaining' for ivars of retainable type. 10743 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 10744 NewID->setInvalidDecl(); 10745 10746 if (D.getDeclSpec().isModulePrivateSpecified()) 10747 NewID->setModulePrivate(); 10748 10749 if (II) { 10750 // FIXME: When interfaces are DeclContexts, we'll need to add 10751 // these to the interface. 10752 S->AddDecl(NewID); 10753 IdResolver.AddDecl(NewID); 10754 } 10755 10756 if (LangOpts.ObjCRuntime.isNonFragile() && 10757 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 10758 Diag(Loc, diag::warn_ivars_in_interface); 10759 10760 return NewID; 10761} 10762 10763/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 10764/// class and class extensions. For every class \@interface and class 10765/// extension \@interface, if the last ivar is a bitfield of any type, 10766/// then add an implicit `char :0` ivar to the end of that interface. 10767void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 10768 SmallVectorImpl<Decl *> &AllIvarDecls) { 10769 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 10770 return; 10771 10772 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 10773 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 10774 10775 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 10776 return; 10777 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 10778 if (!ID) { 10779 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 10780 if (!CD->IsClassExtension()) 10781 return; 10782 } 10783 // No need to add this to end of @implementation. 10784 else 10785 return; 10786 } 10787 // All conditions are met. Add a new bitfield to the tail end of ivars. 10788 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 10789 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 10790 10791 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 10792 DeclLoc, DeclLoc, 0, 10793 Context.CharTy, 10794 Context.getTrivialTypeSourceInfo(Context.CharTy, 10795 DeclLoc), 10796 ObjCIvarDecl::Private, BW, 10797 true); 10798 AllIvarDecls.push_back(Ivar); 10799} 10800 10801void Sema::ActOnFields(Scope* S, 10802 SourceLocation RecLoc, Decl *EnclosingDecl, 10803 llvm::ArrayRef<Decl *> Fields, 10804 SourceLocation LBrac, SourceLocation RBrac, 10805 AttributeList *Attr) { 10806 assert(EnclosingDecl && "missing record or interface decl"); 10807 10808 // If this is an Objective-C @implementation or category and we have 10809 // new fields here we should reset the layout of the interface since 10810 // it will now change. 10811 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 10812 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 10813 switch (DC->getKind()) { 10814 default: break; 10815 case Decl::ObjCCategory: 10816 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 10817 break; 10818 case Decl::ObjCImplementation: 10819 Context. 10820 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 10821 break; 10822 } 10823 } 10824 10825 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 10826 10827 // Start counting up the number of named members; make sure to include 10828 // members of anonymous structs and unions in the total. 10829 unsigned NumNamedMembers = 0; 10830 if (Record) { 10831 for (RecordDecl::decl_iterator i = Record->decls_begin(), 10832 e = Record->decls_end(); i != e; i++) { 10833 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 10834 if (IFD->getDeclName()) 10835 ++NumNamedMembers; 10836 } 10837 } 10838 10839 // Verify that all the fields are okay. 10840 SmallVector<FieldDecl*, 32> RecFields; 10841 10842 bool ARCErrReported = false; 10843 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 10844 i != end; ++i) { 10845 FieldDecl *FD = cast<FieldDecl>(*i); 10846 10847 // Get the type for the field. 10848 const Type *FDTy = FD->getType().getTypePtr(); 10849 10850 if (!FD->isAnonymousStructOrUnion()) { 10851 // Remember all fields written by the user. 10852 RecFields.push_back(FD); 10853 } 10854 10855 // If the field is already invalid for some reason, don't emit more 10856 // diagnostics about it. 10857 if (FD->isInvalidDecl()) { 10858 EnclosingDecl->setInvalidDecl(); 10859 continue; 10860 } 10861 10862 // C99 6.7.2.1p2: 10863 // A structure or union shall not contain a member with 10864 // incomplete or function type (hence, a structure shall not 10865 // contain an instance of itself, but may contain a pointer to 10866 // an instance of itself), except that the last member of a 10867 // structure with more than one named member may have incomplete 10868 // array type; such a structure (and any union containing, 10869 // possibly recursively, a member that is such a structure) 10870 // shall not be a member of a structure or an element of an 10871 // array. 10872 if (FDTy->isFunctionType()) { 10873 // Field declared as a function. 10874 Diag(FD->getLocation(), diag::err_field_declared_as_function) 10875 << FD->getDeclName(); 10876 FD->setInvalidDecl(); 10877 EnclosingDecl->setInvalidDecl(); 10878 continue; 10879 } else if (FDTy->isIncompleteArrayType() && Record && 10880 ((i + 1 == Fields.end() && !Record->isUnion()) || 10881 ((getLangOpts().MicrosoftExt || 10882 getLangOpts().CPlusPlus) && 10883 (i + 1 == Fields.end() || Record->isUnion())))) { 10884 // Flexible array member. 10885 // Microsoft and g++ is more permissive regarding flexible array. 10886 // It will accept flexible array in union and also 10887 // as the sole element of a struct/class. 10888 if (getLangOpts().MicrosoftExt) { 10889 if (Record->isUnion()) 10890 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 10891 << FD->getDeclName(); 10892 else if (Fields.size() == 1) 10893 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 10894 << FD->getDeclName() << Record->getTagKind(); 10895 } else if (getLangOpts().CPlusPlus) { 10896 if (Record->isUnion()) 10897 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10898 << FD->getDeclName(); 10899 else if (Fields.size() == 1) 10900 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 10901 << FD->getDeclName() << Record->getTagKind(); 10902 } else if (!getLangOpts().C99) { 10903 if (Record->isUnion()) 10904 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10905 << FD->getDeclName(); 10906 else 10907 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 10908 << FD->getDeclName() << Record->getTagKind(); 10909 } else if (NumNamedMembers < 1) { 10910 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 10911 << FD->getDeclName(); 10912 FD->setInvalidDecl(); 10913 EnclosingDecl->setInvalidDecl(); 10914 continue; 10915 } 10916 if (!FD->getType()->isDependentType() && 10917 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 10918 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 10919 << FD->getDeclName() << FD->getType(); 10920 FD->setInvalidDecl(); 10921 EnclosingDecl->setInvalidDecl(); 10922 continue; 10923 } 10924 // Okay, we have a legal flexible array member at the end of the struct. 10925 if (Record) 10926 Record->setHasFlexibleArrayMember(true); 10927 } else if (!FDTy->isDependentType() && 10928 RequireCompleteType(FD->getLocation(), FD->getType(), 10929 diag::err_field_incomplete)) { 10930 // Incomplete type 10931 FD->setInvalidDecl(); 10932 EnclosingDecl->setInvalidDecl(); 10933 continue; 10934 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 10935 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 10936 // If this is a member of a union, then entire union becomes "flexible". 10937 if (Record && Record->isUnion()) { 10938 Record->setHasFlexibleArrayMember(true); 10939 } else { 10940 // If this is a struct/class and this is not the last element, reject 10941 // it. Note that GCC supports variable sized arrays in the middle of 10942 // structures. 10943 if (i + 1 != Fields.end()) 10944 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 10945 << FD->getDeclName() << FD->getType(); 10946 else { 10947 // We support flexible arrays at the end of structs in 10948 // other structs as an extension. 10949 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 10950 << FD->getDeclName(); 10951 if (Record) 10952 Record->setHasFlexibleArrayMember(true); 10953 } 10954 } 10955 } 10956 if (isa<ObjCContainerDecl>(EnclosingDecl) && 10957 RequireNonAbstractType(FD->getLocation(), FD->getType(), 10958 diag::err_abstract_type_in_decl, 10959 AbstractIvarType)) { 10960 // Ivars can not have abstract class types 10961 FD->setInvalidDecl(); 10962 } 10963 if (Record && FDTTy->getDecl()->hasObjectMember()) 10964 Record->setHasObjectMember(true); 10965 if (Record && FDTTy->getDecl()->hasVolatileMember()) 10966 Record->setHasVolatileMember(true); 10967 } else if (FDTy->isObjCObjectType()) { 10968 /// A field cannot be an Objective-c object 10969 Diag(FD->getLocation(), diag::err_statically_allocated_object) 10970 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 10971 QualType T = Context.getObjCObjectPointerType(FD->getType()); 10972 FD->setType(T); 10973 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 10974 (!getLangOpts().CPlusPlus || Record->isUnion())) { 10975 // It's an error in ARC if a field has lifetime. 10976 // We don't want to report this in a system header, though, 10977 // so we just make the field unavailable. 10978 // FIXME: that's really not sufficient; we need to make the type 10979 // itself invalid to, say, initialize or copy. 10980 QualType T = FD->getType(); 10981 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 10982 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 10983 SourceLocation loc = FD->getLocation(); 10984 if (getSourceManager().isInSystemHeader(loc)) { 10985 if (!FD->hasAttr<UnavailableAttr>()) { 10986 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10987 "this system field has retaining ownership")); 10988 } 10989 } else { 10990 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 10991 << T->isBlockPointerType() << Record->getTagKind(); 10992 } 10993 ARCErrReported = true; 10994 } 10995 } else if (getLangOpts().ObjC1 && 10996 getLangOpts().getGC() != LangOptions::NonGC && 10997 Record && !Record->hasObjectMember()) { 10998 if (FD->getType()->isObjCObjectPointerType() || 10999 FD->getType().isObjCGCStrong()) 11000 Record->setHasObjectMember(true); 11001 else if (Context.getAsArrayType(FD->getType())) { 11002 QualType BaseType = Context.getBaseElementType(FD->getType()); 11003 if (BaseType->isRecordType() && 11004 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 11005 Record->setHasObjectMember(true); 11006 else if (BaseType->isObjCObjectPointerType() || 11007 BaseType.isObjCGCStrong()) 11008 Record->setHasObjectMember(true); 11009 } 11010 } 11011 if (Record && FD->getType().isVolatileQualified()) 11012 Record->setHasVolatileMember(true); 11013 // Keep track of the number of named members. 11014 if (FD->getIdentifier()) 11015 ++NumNamedMembers; 11016 } 11017 11018 // Okay, we successfully defined 'Record'. 11019 if (Record) { 11020 bool Completed = false; 11021 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 11022 if (!CXXRecord->isInvalidDecl()) { 11023 // Set access bits correctly on the directly-declared conversions. 11024 for (CXXRecordDecl::conversion_iterator 11025 I = CXXRecord->conversion_begin(), 11026 E = CXXRecord->conversion_end(); I != E; ++I) 11027 I.setAccess((*I)->getAccess()); 11028 11029 if (!CXXRecord->isDependentType()) { 11030 // Adjust user-defined destructor exception spec. 11031 if (getLangOpts().CPlusPlus11 && 11032 CXXRecord->hasUserDeclaredDestructor()) 11033 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 11034 11035 // Add any implicitly-declared members to this class. 11036 AddImplicitlyDeclaredMembersToClass(CXXRecord); 11037 11038 // If we have virtual base classes, we may end up finding multiple 11039 // final overriders for a given virtual function. Check for this 11040 // problem now. 11041 if (CXXRecord->getNumVBases()) { 11042 CXXFinalOverriderMap FinalOverriders; 11043 CXXRecord->getFinalOverriders(FinalOverriders); 11044 11045 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 11046 MEnd = FinalOverriders.end(); 11047 M != MEnd; ++M) { 11048 for (OverridingMethods::iterator SO = M->second.begin(), 11049 SOEnd = M->second.end(); 11050 SO != SOEnd; ++SO) { 11051 assert(SO->second.size() > 0 && 11052 "Virtual function without overridding functions?"); 11053 if (SO->second.size() == 1) 11054 continue; 11055 11056 // C++ [class.virtual]p2: 11057 // In a derived class, if a virtual member function of a base 11058 // class subobject has more than one final overrider the 11059 // program is ill-formed. 11060 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 11061 << (const NamedDecl *)M->first << Record; 11062 Diag(M->first->getLocation(), 11063 diag::note_overridden_virtual_function); 11064 for (OverridingMethods::overriding_iterator 11065 OM = SO->second.begin(), 11066 OMEnd = SO->second.end(); 11067 OM != OMEnd; ++OM) 11068 Diag(OM->Method->getLocation(), diag::note_final_overrider) 11069 << (const NamedDecl *)M->first << OM->Method->getParent(); 11070 11071 Record->setInvalidDecl(); 11072 } 11073 } 11074 CXXRecord->completeDefinition(&FinalOverriders); 11075 Completed = true; 11076 } 11077 } 11078 } 11079 } 11080 11081 if (!Completed) 11082 Record->completeDefinition(); 11083 11084 if (Record->hasAttrs()) 11085 CheckAlignasUnderalignment(Record); 11086 } else { 11087 ObjCIvarDecl **ClsFields = 11088 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 11089 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 11090 ID->setEndOfDefinitionLoc(RBrac); 11091 // Add ivar's to class's DeclContext. 11092 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 11093 ClsFields[i]->setLexicalDeclContext(ID); 11094 ID->addDecl(ClsFields[i]); 11095 } 11096 // Must enforce the rule that ivars in the base classes may not be 11097 // duplicates. 11098 if (ID->getSuperClass()) 11099 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 11100 } else if (ObjCImplementationDecl *IMPDecl = 11101 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11102 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 11103 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 11104 // Ivar declared in @implementation never belongs to the implementation. 11105 // Only it is in implementation's lexical context. 11106 ClsFields[I]->setLexicalDeclContext(IMPDecl); 11107 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 11108 IMPDecl->setIvarLBraceLoc(LBrac); 11109 IMPDecl->setIvarRBraceLoc(RBrac); 11110 } else if (ObjCCategoryDecl *CDecl = 11111 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11112 // case of ivars in class extension; all other cases have been 11113 // reported as errors elsewhere. 11114 // FIXME. Class extension does not have a LocEnd field. 11115 // CDecl->setLocEnd(RBrac); 11116 // Add ivar's to class extension's DeclContext. 11117 // Diagnose redeclaration of private ivars. 11118 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 11119 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 11120 if (IDecl) { 11121 if (const ObjCIvarDecl *ClsIvar = 11122 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 11123 Diag(ClsFields[i]->getLocation(), 11124 diag::err_duplicate_ivar_declaration); 11125 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 11126 continue; 11127 } 11128 for (ObjCInterfaceDecl::known_extensions_iterator 11129 Ext = IDecl->known_extensions_begin(), 11130 ExtEnd = IDecl->known_extensions_end(); 11131 Ext != ExtEnd; ++Ext) { 11132 if (const ObjCIvarDecl *ClsExtIvar 11133 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 11134 Diag(ClsFields[i]->getLocation(), 11135 diag::err_duplicate_ivar_declaration); 11136 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 11137 continue; 11138 } 11139 } 11140 } 11141 ClsFields[i]->setLexicalDeclContext(CDecl); 11142 CDecl->addDecl(ClsFields[i]); 11143 } 11144 CDecl->setIvarLBraceLoc(LBrac); 11145 CDecl->setIvarRBraceLoc(RBrac); 11146 } 11147 } 11148 11149 if (Attr) 11150 ProcessDeclAttributeList(S, Record, Attr); 11151} 11152 11153/// \brief Determine whether the given integral value is representable within 11154/// the given type T. 11155static bool isRepresentableIntegerValue(ASTContext &Context, 11156 llvm::APSInt &Value, 11157 QualType T) { 11158 assert(T->isIntegralType(Context) && "Integral type required!"); 11159 unsigned BitWidth = Context.getIntWidth(T); 11160 11161 if (Value.isUnsigned() || Value.isNonNegative()) { 11162 if (T->isSignedIntegerOrEnumerationType()) 11163 --BitWidth; 11164 return Value.getActiveBits() <= BitWidth; 11165 } 11166 return Value.getMinSignedBits() <= BitWidth; 11167} 11168 11169// \brief Given an integral type, return the next larger integral type 11170// (or a NULL type of no such type exists). 11171static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 11172 // FIXME: Int128/UInt128 support, which also needs to be introduced into 11173 // enum checking below. 11174 assert(T->isIntegralType(Context) && "Integral type required!"); 11175 const unsigned NumTypes = 4; 11176 QualType SignedIntegralTypes[NumTypes] = { 11177 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 11178 }; 11179 QualType UnsignedIntegralTypes[NumTypes] = { 11180 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 11181 Context.UnsignedLongLongTy 11182 }; 11183 11184 unsigned BitWidth = Context.getTypeSize(T); 11185 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 11186 : UnsignedIntegralTypes; 11187 for (unsigned I = 0; I != NumTypes; ++I) 11188 if (Context.getTypeSize(Types[I]) > BitWidth) 11189 return Types[I]; 11190 11191 return QualType(); 11192} 11193 11194EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 11195 EnumConstantDecl *LastEnumConst, 11196 SourceLocation IdLoc, 11197 IdentifierInfo *Id, 11198 Expr *Val) { 11199 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11200 llvm::APSInt EnumVal(IntWidth); 11201 QualType EltTy; 11202 11203 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 11204 Val = 0; 11205 11206 if (Val) 11207 Val = DefaultLvalueConversion(Val).take(); 11208 11209 if (Val) { 11210 if (Enum->isDependentType() || Val->isTypeDependent()) 11211 EltTy = Context.DependentTy; 11212 else { 11213 SourceLocation ExpLoc; 11214 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 11215 !getLangOpts().MicrosoftMode) { 11216 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 11217 // constant-expression in the enumerator-definition shall be a converted 11218 // constant expression of the underlying type. 11219 EltTy = Enum->getIntegerType(); 11220 ExprResult Converted = 11221 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 11222 CCEK_Enumerator); 11223 if (Converted.isInvalid()) 11224 Val = 0; 11225 else 11226 Val = Converted.take(); 11227 } else if (!Val->isValueDependent() && 11228 !(Val = VerifyIntegerConstantExpression(Val, 11229 &EnumVal).take())) { 11230 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 11231 } else { 11232 if (Enum->isFixed()) { 11233 EltTy = Enum->getIntegerType(); 11234 11235 // In Obj-C and Microsoft mode, require the enumeration value to be 11236 // representable in the underlying type of the enumeration. In C++11, 11237 // we perform a non-narrowing conversion as part of converted constant 11238 // expression checking. 11239 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11240 if (getLangOpts().MicrosoftMode) { 11241 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 11242 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11243 } else 11244 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 11245 } else 11246 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11247 } else if (getLangOpts().CPlusPlus) { 11248 // C++11 [dcl.enum]p5: 11249 // If the underlying type is not fixed, the type of each enumerator 11250 // is the type of its initializing value: 11251 // - If an initializer is specified for an enumerator, the 11252 // initializing value has the same type as the expression. 11253 EltTy = Val->getType(); 11254 } else { 11255 // C99 6.7.2.2p2: 11256 // The expression that defines the value of an enumeration constant 11257 // shall be an integer constant expression that has a value 11258 // representable as an int. 11259 11260 // Complain if the value is not representable in an int. 11261 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 11262 Diag(IdLoc, diag::ext_enum_value_not_int) 11263 << EnumVal.toString(10) << Val->getSourceRange() 11264 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 11265 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 11266 // Force the type of the expression to 'int'. 11267 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 11268 } 11269 EltTy = Val->getType(); 11270 } 11271 } 11272 } 11273 } 11274 11275 if (!Val) { 11276 if (Enum->isDependentType()) 11277 EltTy = Context.DependentTy; 11278 else if (!LastEnumConst) { 11279 // C++0x [dcl.enum]p5: 11280 // If the underlying type is not fixed, the type of each enumerator 11281 // is the type of its initializing value: 11282 // - If no initializer is specified for the first enumerator, the 11283 // initializing value has an unspecified integral type. 11284 // 11285 // GCC uses 'int' for its unspecified integral type, as does 11286 // C99 6.7.2.2p3. 11287 if (Enum->isFixed()) { 11288 EltTy = Enum->getIntegerType(); 11289 } 11290 else { 11291 EltTy = Context.IntTy; 11292 } 11293 } else { 11294 // Assign the last value + 1. 11295 EnumVal = LastEnumConst->getInitVal(); 11296 ++EnumVal; 11297 EltTy = LastEnumConst->getType(); 11298 11299 // Check for overflow on increment. 11300 if (EnumVal < LastEnumConst->getInitVal()) { 11301 // C++0x [dcl.enum]p5: 11302 // If the underlying type is not fixed, the type of each enumerator 11303 // is the type of its initializing value: 11304 // 11305 // - Otherwise the type of the initializing value is the same as 11306 // the type of the initializing value of the preceding enumerator 11307 // unless the incremented value is not representable in that type, 11308 // in which case the type is an unspecified integral type 11309 // sufficient to contain the incremented value. If no such type 11310 // exists, the program is ill-formed. 11311 QualType T = getNextLargerIntegralType(Context, EltTy); 11312 if (T.isNull() || Enum->isFixed()) { 11313 // There is no integral type larger enough to represent this 11314 // value. Complain, then allow the value to wrap around. 11315 EnumVal = LastEnumConst->getInitVal(); 11316 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 11317 ++EnumVal; 11318 if (Enum->isFixed()) 11319 // When the underlying type is fixed, this is ill-formed. 11320 Diag(IdLoc, diag::err_enumerator_wrapped) 11321 << EnumVal.toString(10) 11322 << EltTy; 11323 else 11324 Diag(IdLoc, diag::warn_enumerator_too_large) 11325 << EnumVal.toString(10); 11326 } else { 11327 EltTy = T; 11328 } 11329 11330 // Retrieve the last enumerator's value, extent that type to the 11331 // type that is supposed to be large enough to represent the incremented 11332 // value, then increment. 11333 EnumVal = LastEnumConst->getInitVal(); 11334 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11335 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 11336 ++EnumVal; 11337 11338 // If we're not in C++, diagnose the overflow of enumerator values, 11339 // which in C99 means that the enumerator value is not representable in 11340 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 11341 // permits enumerator values that are representable in some larger 11342 // integral type. 11343 if (!getLangOpts().CPlusPlus && !T.isNull()) 11344 Diag(IdLoc, diag::warn_enum_value_overflow); 11345 } else if (!getLangOpts().CPlusPlus && 11346 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11347 // Enforce C99 6.7.2.2p2 even when we compute the next value. 11348 Diag(IdLoc, diag::ext_enum_value_not_int) 11349 << EnumVal.toString(10) << 1; 11350 } 11351 } 11352 } 11353 11354 if (!EltTy->isDependentType()) { 11355 // Make the enumerator value match the signedness and size of the 11356 // enumerator's type. 11357 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 11358 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11359 } 11360 11361 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 11362 Val, EnumVal); 11363} 11364 11365 11366Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 11367 SourceLocation IdLoc, IdentifierInfo *Id, 11368 AttributeList *Attr, 11369 SourceLocation EqualLoc, Expr *Val) { 11370 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 11371 EnumConstantDecl *LastEnumConst = 11372 cast_or_null<EnumConstantDecl>(lastEnumConst); 11373 11374 // The scope passed in may not be a decl scope. Zip up the scope tree until 11375 // we find one that is. 11376 S = getNonFieldDeclScope(S); 11377 11378 // Verify that there isn't already something declared with this name in this 11379 // scope. 11380 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 11381 ForRedeclaration); 11382 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11383 // Maybe we will complain about the shadowed template parameter. 11384 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 11385 // Just pretend that we didn't see the previous declaration. 11386 PrevDecl = 0; 11387 } 11388 11389 if (PrevDecl) { 11390 // When in C++, we may get a TagDecl with the same name; in this case the 11391 // enum constant will 'hide' the tag. 11392 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 11393 "Received TagDecl when not in C++!"); 11394 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 11395 if (isa<EnumConstantDecl>(PrevDecl)) 11396 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 11397 else 11398 Diag(IdLoc, diag::err_redefinition) << Id; 11399 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11400 return 0; 11401 } 11402 } 11403 11404 // C++ [class.mem]p15: 11405 // If T is the name of a class, then each of the following shall have a name 11406 // different from T: 11407 // - every enumerator of every member of class T that is an unscoped 11408 // enumerated type 11409 if (CXXRecordDecl *Record 11410 = dyn_cast<CXXRecordDecl>( 11411 TheEnumDecl->getDeclContext()->getRedeclContext())) 11412 if (!TheEnumDecl->isScoped() && 11413 Record->getIdentifier() && Record->getIdentifier() == Id) 11414 Diag(IdLoc, diag::err_member_name_of_class) << Id; 11415 11416 EnumConstantDecl *New = 11417 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 11418 11419 if (New) { 11420 // Process attributes. 11421 if (Attr) ProcessDeclAttributeList(S, New, Attr); 11422 11423 // Register this decl in the current scope stack. 11424 New->setAccess(TheEnumDecl->getAccess()); 11425 PushOnScopeChains(New, S); 11426 } 11427 11428 ActOnDocumentableDecl(New); 11429 11430 return New; 11431} 11432 11433// Returns true when the enum initial expression does not trigger the 11434// duplicate enum warning. A few common cases are exempted as follows: 11435// Element2 = Element1 11436// Element2 = Element1 + 1 11437// Element2 = Element1 - 1 11438// Where Element2 and Element1 are from the same enum. 11439static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 11440 Expr *InitExpr = ECD->getInitExpr(); 11441 if (!InitExpr) 11442 return true; 11443 InitExpr = InitExpr->IgnoreImpCasts(); 11444 11445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 11446 if (!BO->isAdditiveOp()) 11447 return true; 11448 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 11449 if (!IL) 11450 return true; 11451 if (IL->getValue() != 1) 11452 return true; 11453 11454 InitExpr = BO->getLHS(); 11455 } 11456 11457 // This checks if the elements are from the same enum. 11458 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 11459 if (!DRE) 11460 return true; 11461 11462 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 11463 if (!EnumConstant) 11464 return true; 11465 11466 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 11467 Enum) 11468 return true; 11469 11470 return false; 11471} 11472 11473struct DupKey { 11474 int64_t val; 11475 bool isTombstoneOrEmptyKey; 11476 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 11477 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 11478}; 11479 11480static DupKey GetDupKey(const llvm::APSInt& Val) { 11481 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 11482 false); 11483} 11484 11485struct DenseMapInfoDupKey { 11486 static DupKey getEmptyKey() { return DupKey(0, true); } 11487 static DupKey getTombstoneKey() { return DupKey(1, true); } 11488 static unsigned getHashValue(const DupKey Key) { 11489 return (unsigned)(Key.val * 37); 11490 } 11491 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 11492 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 11493 LHS.val == RHS.val; 11494 } 11495}; 11496 11497// Emits a warning when an element is implicitly set a value that 11498// a previous element has already been set to. 11499static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements, 11500 unsigned NumElements, EnumDecl *Enum, 11501 QualType EnumType) { 11502 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 11503 Enum->getLocation()) == 11504 DiagnosticsEngine::Ignored) 11505 return; 11506 // Avoid anonymous enums 11507 if (!Enum->getIdentifier()) 11508 return; 11509 11510 // Only check for small enums. 11511 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 11512 return; 11513 11514 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 11515 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 11516 11517 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 11518 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 11519 ValueToVectorMap; 11520 11521 DuplicatesVector DupVector; 11522 ValueToVectorMap EnumMap; 11523 11524 // Populate the EnumMap with all values represented by enum constants without 11525 // an initialier. 11526 for (unsigned i = 0; i < NumElements; ++i) { 11527 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11528 11529 // Null EnumConstantDecl means a previous diagnostic has been emitted for 11530 // this constant. Skip this enum since it may be ill-formed. 11531 if (!ECD) { 11532 return; 11533 } 11534 11535 if (ECD->getInitExpr()) 11536 continue; 11537 11538 DupKey Key = GetDupKey(ECD->getInitVal()); 11539 DeclOrVector &Entry = EnumMap[Key]; 11540 11541 // First time encountering this value. 11542 if (Entry.isNull()) 11543 Entry = ECD; 11544 } 11545 11546 // Create vectors for any values that has duplicates. 11547 for (unsigned i = 0; i < NumElements; ++i) { 11548 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11549 if (!ValidDuplicateEnum(ECD, Enum)) 11550 continue; 11551 11552 DupKey Key = GetDupKey(ECD->getInitVal()); 11553 11554 DeclOrVector& Entry = EnumMap[Key]; 11555 if (Entry.isNull()) 11556 continue; 11557 11558 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 11559 // Ensure constants are different. 11560 if (D == ECD) 11561 continue; 11562 11563 // Create new vector and push values onto it. 11564 ECDVector *Vec = new ECDVector(); 11565 Vec->push_back(D); 11566 Vec->push_back(ECD); 11567 11568 // Update entry to point to the duplicates vector. 11569 Entry = Vec; 11570 11571 // Store the vector somewhere we can consult later for quick emission of 11572 // diagnostics. 11573 DupVector.push_back(Vec); 11574 continue; 11575 } 11576 11577 ECDVector *Vec = Entry.get<ECDVector*>(); 11578 // Make sure constants are not added more than once. 11579 if (*Vec->begin() == ECD) 11580 continue; 11581 11582 Vec->push_back(ECD); 11583 } 11584 11585 // Emit diagnostics. 11586 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 11587 DupVectorEnd = DupVector.end(); 11588 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 11589 ECDVector *Vec = *DupVectorIter; 11590 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 11591 11592 // Emit warning for one enum constant. 11593 ECDVector::iterator I = Vec->begin(); 11594 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 11595 << (*I)->getName() << (*I)->getInitVal().toString(10) 11596 << (*I)->getSourceRange(); 11597 ++I; 11598 11599 // Emit one note for each of the remaining enum constants with 11600 // the same value. 11601 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 11602 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 11603 << (*I)->getName() << (*I)->getInitVal().toString(10) 11604 << (*I)->getSourceRange(); 11605 delete Vec; 11606 } 11607} 11608 11609void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 11610 SourceLocation RBraceLoc, Decl *EnumDeclX, 11611 Decl **Elements, unsigned NumElements, 11612 Scope *S, AttributeList *Attr) { 11613 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 11614 QualType EnumType = Context.getTypeDeclType(Enum); 11615 11616 if (Attr) 11617 ProcessDeclAttributeList(S, Enum, Attr); 11618 11619 if (Enum->isDependentType()) { 11620 for (unsigned i = 0; i != NumElements; ++i) { 11621 EnumConstantDecl *ECD = 11622 cast_or_null<EnumConstantDecl>(Elements[i]); 11623 if (!ECD) continue; 11624 11625 ECD->setType(EnumType); 11626 } 11627 11628 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 11629 return; 11630 } 11631 11632 // TODO: If the result value doesn't fit in an int, it must be a long or long 11633 // long value. ISO C does not support this, but GCC does as an extension, 11634 // emit a warning. 11635 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11636 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 11637 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 11638 11639 // Verify that all the values are okay, compute the size of the values, and 11640 // reverse the list. 11641 unsigned NumNegativeBits = 0; 11642 unsigned NumPositiveBits = 0; 11643 11644 // Keep track of whether all elements have type int. 11645 bool AllElementsInt = true; 11646 11647 for (unsigned i = 0; i != NumElements; ++i) { 11648 EnumConstantDecl *ECD = 11649 cast_or_null<EnumConstantDecl>(Elements[i]); 11650 if (!ECD) continue; // Already issued a diagnostic. 11651 11652 const llvm::APSInt &InitVal = ECD->getInitVal(); 11653 11654 // Keep track of the size of positive and negative values. 11655 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 11656 NumPositiveBits = std::max(NumPositiveBits, 11657 (unsigned)InitVal.getActiveBits()); 11658 else 11659 NumNegativeBits = std::max(NumNegativeBits, 11660 (unsigned)InitVal.getMinSignedBits()); 11661 11662 // Keep track of whether every enum element has type int (very commmon). 11663 if (AllElementsInt) 11664 AllElementsInt = ECD->getType() == Context.IntTy; 11665 } 11666 11667 // Figure out the type that should be used for this enum. 11668 QualType BestType; 11669 unsigned BestWidth; 11670 11671 // C++0x N3000 [conv.prom]p3: 11672 // An rvalue of an unscoped enumeration type whose underlying 11673 // type is not fixed can be converted to an rvalue of the first 11674 // of the following types that can represent all the values of 11675 // the enumeration: int, unsigned int, long int, unsigned long 11676 // int, long long int, or unsigned long long int. 11677 // C99 6.4.4.3p2: 11678 // An identifier declared as an enumeration constant has type int. 11679 // The C99 rule is modified by a gcc extension 11680 QualType BestPromotionType; 11681 11682 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 11683 // -fshort-enums is the equivalent to specifying the packed attribute on all 11684 // enum definitions. 11685 if (LangOpts.ShortEnums) 11686 Packed = true; 11687 11688 if (Enum->isFixed()) { 11689 BestType = Enum->getIntegerType(); 11690 if (BestType->isPromotableIntegerType()) 11691 BestPromotionType = Context.getPromotedIntegerType(BestType); 11692 else 11693 BestPromotionType = BestType; 11694 // We don't need to set BestWidth, because BestType is going to be the type 11695 // of the enumerators, but we do anyway because otherwise some compilers 11696 // warn that it might be used uninitialized. 11697 BestWidth = CharWidth; 11698 } 11699 else if (NumNegativeBits) { 11700 // If there is a negative value, figure out the smallest integer type (of 11701 // int/long/longlong) that fits. 11702 // If it's packed, check also if it fits a char or a short. 11703 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 11704 BestType = Context.SignedCharTy; 11705 BestWidth = CharWidth; 11706 } else if (Packed && NumNegativeBits <= ShortWidth && 11707 NumPositiveBits < ShortWidth) { 11708 BestType = Context.ShortTy; 11709 BestWidth = ShortWidth; 11710 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 11711 BestType = Context.IntTy; 11712 BestWidth = IntWidth; 11713 } else { 11714 BestWidth = Context.getTargetInfo().getLongWidth(); 11715 11716 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 11717 BestType = Context.LongTy; 11718 } else { 11719 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11720 11721 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 11722 Diag(Enum->getLocation(), diag::warn_enum_too_large); 11723 BestType = Context.LongLongTy; 11724 } 11725 } 11726 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 11727 } else { 11728 // If there is no negative value, figure out the smallest type that fits 11729 // all of the enumerator values. 11730 // If it's packed, check also if it fits a char or a short. 11731 if (Packed && NumPositiveBits <= CharWidth) { 11732 BestType = Context.UnsignedCharTy; 11733 BestPromotionType = Context.IntTy; 11734 BestWidth = CharWidth; 11735 } else if (Packed && NumPositiveBits <= ShortWidth) { 11736 BestType = Context.UnsignedShortTy; 11737 BestPromotionType = Context.IntTy; 11738 BestWidth = ShortWidth; 11739 } else if (NumPositiveBits <= IntWidth) { 11740 BestType = Context.UnsignedIntTy; 11741 BestWidth = IntWidth; 11742 BestPromotionType 11743 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11744 ? Context.UnsignedIntTy : Context.IntTy; 11745 } else if (NumPositiveBits <= 11746 (BestWidth = Context.getTargetInfo().getLongWidth())) { 11747 BestType = Context.UnsignedLongTy; 11748 BestPromotionType 11749 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11750 ? Context.UnsignedLongTy : Context.LongTy; 11751 } else { 11752 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11753 assert(NumPositiveBits <= BestWidth && 11754 "How could an initializer get larger than ULL?"); 11755 BestType = Context.UnsignedLongLongTy; 11756 BestPromotionType 11757 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11758 ? Context.UnsignedLongLongTy : Context.LongLongTy; 11759 } 11760 } 11761 11762 // Loop over all of the enumerator constants, changing their types to match 11763 // the type of the enum if needed. 11764 for (unsigned i = 0; i != NumElements; ++i) { 11765 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 11766 if (!ECD) continue; // Already issued a diagnostic. 11767 11768 // Standard C says the enumerators have int type, but we allow, as an 11769 // extension, the enumerators to be larger than int size. If each 11770 // enumerator value fits in an int, type it as an int, otherwise type it the 11771 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 11772 // that X has type 'int', not 'unsigned'. 11773 11774 // Determine whether the value fits into an int. 11775 llvm::APSInt InitVal = ECD->getInitVal(); 11776 11777 // If it fits into an integer type, force it. Otherwise force it to match 11778 // the enum decl type. 11779 QualType NewTy; 11780 unsigned NewWidth; 11781 bool NewSign; 11782 if (!getLangOpts().CPlusPlus && 11783 !Enum->isFixed() && 11784 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 11785 NewTy = Context.IntTy; 11786 NewWidth = IntWidth; 11787 NewSign = true; 11788 } else if (ECD->getType() == BestType) { 11789 // Already the right type! 11790 if (getLangOpts().CPlusPlus) 11791 // C++ [dcl.enum]p4: Following the closing brace of an 11792 // enum-specifier, each enumerator has the type of its 11793 // enumeration. 11794 ECD->setType(EnumType); 11795 continue; 11796 } else { 11797 NewTy = BestType; 11798 NewWidth = BestWidth; 11799 NewSign = BestType->isSignedIntegerOrEnumerationType(); 11800 } 11801 11802 // Adjust the APSInt value. 11803 InitVal = InitVal.extOrTrunc(NewWidth); 11804 InitVal.setIsSigned(NewSign); 11805 ECD->setInitVal(InitVal); 11806 11807 // Adjust the Expr initializer and type. 11808 if (ECD->getInitExpr() && 11809 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 11810 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 11811 CK_IntegralCast, 11812 ECD->getInitExpr(), 11813 /*base paths*/ 0, 11814 VK_RValue)); 11815 if (getLangOpts().CPlusPlus) 11816 // C++ [dcl.enum]p4: Following the closing brace of an 11817 // enum-specifier, each enumerator has the type of its 11818 // enumeration. 11819 ECD->setType(EnumType); 11820 else 11821 ECD->setType(NewTy); 11822 } 11823 11824 Enum->completeDefinition(BestType, BestPromotionType, 11825 NumPositiveBits, NumNegativeBits); 11826 11827 // If we're declaring a function, ensure this decl isn't forgotten about - 11828 // it needs to go into the function scope. 11829 if (InFunctionDeclarator) 11830 DeclsInPrototypeScope.push_back(Enum); 11831 11832 CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType); 11833 11834 // Now that the enum type is defined, ensure it's not been underaligned. 11835 if (Enum->hasAttrs()) 11836 CheckAlignasUnderalignment(Enum); 11837} 11838 11839Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 11840 SourceLocation StartLoc, 11841 SourceLocation EndLoc) { 11842 StringLiteral *AsmString = cast<StringLiteral>(expr); 11843 11844 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 11845 AsmString, StartLoc, 11846 EndLoc); 11847 CurContext->addDecl(New); 11848 return New; 11849} 11850 11851DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 11852 SourceLocation ImportLoc, 11853 ModuleIdPath Path) { 11854 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 11855 Module::AllVisible, 11856 /*IsIncludeDirective=*/false); 11857 if (!Mod) 11858 return true; 11859 11860 SmallVector<SourceLocation, 2> IdentifierLocs; 11861 Module *ModCheck = Mod; 11862 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 11863 // If we've run out of module parents, just drop the remaining identifiers. 11864 // We need the length to be consistent. 11865 if (!ModCheck) 11866 break; 11867 ModCheck = ModCheck->Parent; 11868 11869 IdentifierLocs.push_back(Path[I].second); 11870 } 11871 11872 ImportDecl *Import = ImportDecl::Create(Context, 11873 Context.getTranslationUnitDecl(), 11874 AtLoc.isValid()? AtLoc : ImportLoc, 11875 Mod, IdentifierLocs); 11876 Context.getTranslationUnitDecl()->addDecl(Import); 11877 return Import; 11878} 11879 11880void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 11881 // Create the implicit import declaration. 11882 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 11883 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 11884 Loc, Mod, Loc); 11885 TU->addDecl(ImportD); 11886 Consumer.HandleImplicitImportDecl(ImportD); 11887 11888 // Make the module visible. 11889 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 11890 /*Complain=*/false); 11891} 11892 11893void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 11894 IdentifierInfo* AliasName, 11895 SourceLocation PragmaLoc, 11896 SourceLocation NameLoc, 11897 SourceLocation AliasNameLoc) { 11898 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 11899 LookupOrdinaryName); 11900 AsmLabelAttr *Attr = 11901 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 11902 11903 if (PrevDecl) 11904 PrevDecl->addAttr(Attr); 11905 else 11906 (void)ExtnameUndeclaredIdentifiers.insert( 11907 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 11908} 11909 11910void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 11911 SourceLocation PragmaLoc, 11912 SourceLocation NameLoc) { 11913 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 11914 11915 if (PrevDecl) { 11916 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 11917 } else { 11918 (void)WeakUndeclaredIdentifiers.insert( 11919 std::pair<IdentifierInfo*,WeakInfo> 11920 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 11921 } 11922} 11923 11924void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 11925 IdentifierInfo* AliasName, 11926 SourceLocation PragmaLoc, 11927 SourceLocation NameLoc, 11928 SourceLocation AliasNameLoc) { 11929 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 11930 LookupOrdinaryName); 11931 WeakInfo W = WeakInfo(Name, NameLoc); 11932 11933 if (PrevDecl) { 11934 if (!PrevDecl->hasAttr<AliasAttr>()) 11935 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 11936 DeclApplyPragmaWeak(TUScope, ND, W); 11937 } else { 11938 (void)WeakUndeclaredIdentifiers.insert( 11939 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 11940 } 11941} 11942 11943Decl *Sema::getObjCDeclContext() const { 11944 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 11945} 11946 11947AvailabilityResult Sema::getCurContextAvailability() const { 11948 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 11949 return D->getAvailability(); 11950} 11951