SemaDecl.cpp revision 8af742a499bf13f0a3d53b03aa44ae748fadd61e
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->hasErrorOccurred()) 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 SC_None, 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, 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 // If this declaration has external 1609 bool hasExternalLinkage = decl->hasExternalLinkage(); 1610 1611 LookupResult::Filter filter = previous.makeFilter(); 1612 while (filter.hasNext()) { 1613 NamedDecl *old = filter.next(); 1614 1615 // Non-hidden declarations are never ignored. 1616 if (!old->isHidden()) 1617 continue; 1618 1619 // If either has no-external linkage, ignore the old declaration. 1620 if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage) 1621 filter.erase(); 1622 } 1623 1624 filter.done(); 1625} 1626 1627bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1628 QualType OldType; 1629 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1630 OldType = OldTypedef->getUnderlyingType(); 1631 else 1632 OldType = Context.getTypeDeclType(Old); 1633 QualType NewType = New->getUnderlyingType(); 1634 1635 if (NewType->isVariablyModifiedType()) { 1636 // Must not redefine a typedef with a variably-modified type. 1637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1638 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1639 << Kind << NewType; 1640 if (Old->getLocation().isValid()) 1641 Diag(Old->getLocation(), diag::note_previous_definition); 1642 New->setInvalidDecl(); 1643 return true; 1644 } 1645 1646 if (OldType != NewType && 1647 !OldType->isDependentType() && 1648 !NewType->isDependentType() && 1649 !Context.hasSameType(OldType, NewType)) { 1650 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1651 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1652 << Kind << NewType << OldType; 1653 if (Old->getLocation().isValid()) 1654 Diag(Old->getLocation(), diag::note_previous_definition); 1655 New->setInvalidDecl(); 1656 return true; 1657 } 1658 return false; 1659} 1660 1661/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1662/// same name and scope as a previous declaration 'Old'. Figure out 1663/// how to resolve this situation, merging decls or emitting 1664/// diagnostics as appropriate. If there was an error, set New to be invalid. 1665/// 1666void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1667 // If the new decl is known invalid already, don't bother doing any 1668 // merging checks. 1669 if (New->isInvalidDecl()) return; 1670 1671 // Allow multiple definitions for ObjC built-in typedefs. 1672 // FIXME: Verify the underlying types are equivalent! 1673 if (getLangOpts().ObjC1) { 1674 const IdentifierInfo *TypeID = New->getIdentifier(); 1675 switch (TypeID->getLength()) { 1676 default: break; 1677 case 2: 1678 { 1679 if (!TypeID->isStr("id")) 1680 break; 1681 QualType T = New->getUnderlyingType(); 1682 if (!T->isPointerType()) 1683 break; 1684 if (!T->isVoidPointerType()) { 1685 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1686 if (!PT->isStructureType()) 1687 break; 1688 } 1689 Context.setObjCIdRedefinitionType(T); 1690 // Install the built-in type for 'id', ignoring the current definition. 1691 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1692 return; 1693 } 1694 case 5: 1695 if (!TypeID->isStr("Class")) 1696 break; 1697 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1698 // Install the built-in type for 'Class', ignoring the current definition. 1699 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1700 return; 1701 case 3: 1702 if (!TypeID->isStr("SEL")) 1703 break; 1704 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1705 // Install the built-in type for 'SEL', ignoring the current definition. 1706 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1707 return; 1708 } 1709 // Fall through - the typedef name was not a builtin type. 1710 } 1711 1712 // Verify the old decl was also a type. 1713 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1714 if (!Old) { 1715 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1716 << New->getDeclName(); 1717 1718 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1719 if (OldD->getLocation().isValid()) 1720 Diag(OldD->getLocation(), diag::note_previous_definition); 1721 1722 return New->setInvalidDecl(); 1723 } 1724 1725 // If the old declaration is invalid, just give up here. 1726 if (Old->isInvalidDecl()) 1727 return New->setInvalidDecl(); 1728 1729 // If the typedef types are not identical, reject them in all languages and 1730 // with any extensions enabled. 1731 if (isIncompatibleTypedef(Old, New)) 1732 return; 1733 1734 // The types match. Link up the redeclaration chain if the old 1735 // declaration was a typedef. 1736 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1737 New->setPreviousDeclaration(Typedef); 1738 1739 if (getLangOpts().MicrosoftExt) 1740 return; 1741 1742 if (getLangOpts().CPlusPlus) { 1743 // C++ [dcl.typedef]p2: 1744 // In a given non-class scope, a typedef specifier can be used to 1745 // redefine the name of any type declared in that scope to refer 1746 // to the type to which it already refers. 1747 if (!isa<CXXRecordDecl>(CurContext)) 1748 return; 1749 1750 // C++0x [dcl.typedef]p4: 1751 // In a given class scope, a typedef specifier can be used to redefine 1752 // any class-name declared in that scope that is not also a typedef-name 1753 // to refer to the type to which it already refers. 1754 // 1755 // This wording came in via DR424, which was a correction to the 1756 // wording in DR56, which accidentally banned code like: 1757 // 1758 // struct S { 1759 // typedef struct A { } A; 1760 // }; 1761 // 1762 // in the C++03 standard. We implement the C++0x semantics, which 1763 // allow the above but disallow 1764 // 1765 // struct S { 1766 // typedef int I; 1767 // typedef int I; 1768 // }; 1769 // 1770 // since that was the intent of DR56. 1771 if (!isa<TypedefNameDecl>(Old)) 1772 return; 1773 1774 Diag(New->getLocation(), diag::err_redefinition) 1775 << New->getDeclName(); 1776 Diag(Old->getLocation(), diag::note_previous_definition); 1777 return New->setInvalidDecl(); 1778 } 1779 1780 // Modules always permit redefinition of typedefs, as does C11. 1781 if (getLangOpts().Modules || getLangOpts().C11) 1782 return; 1783 1784 // If we have a redefinition of a typedef in C, emit a warning. This warning 1785 // is normally mapped to an error, but can be controlled with 1786 // -Wtypedef-redefinition. If either the original or the redefinition is 1787 // in a system header, don't emit this for compatibility with GCC. 1788 if (getDiagnostics().getSuppressSystemWarnings() && 1789 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1790 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1791 return; 1792 1793 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1794 << New->getDeclName(); 1795 Diag(Old->getLocation(), diag::note_previous_definition); 1796 return; 1797} 1798 1799/// DeclhasAttr - returns true if decl Declaration already has the target 1800/// attribute. 1801static bool 1802DeclHasAttr(const Decl *D, const Attr *A) { 1803 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1804 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1805 // responsible for making sure they are consistent. 1806 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1807 if (AA) 1808 return false; 1809 1810 // The following thread safety attributes can also be duplicated. 1811 switch (A->getKind()) { 1812 case attr::ExclusiveLocksRequired: 1813 case attr::SharedLocksRequired: 1814 case attr::LocksExcluded: 1815 case attr::ExclusiveLockFunction: 1816 case attr::SharedLockFunction: 1817 case attr::UnlockFunction: 1818 case attr::ExclusiveTrylockFunction: 1819 case attr::SharedTrylockFunction: 1820 case attr::GuardedBy: 1821 case attr::PtGuardedBy: 1822 case attr::AcquiredBefore: 1823 case attr::AcquiredAfter: 1824 return false; 1825 default: 1826 ; 1827 } 1828 1829 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1830 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1831 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1832 if ((*i)->getKind() == A->getKind()) { 1833 if (Ann) { 1834 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1835 return true; 1836 continue; 1837 } 1838 // FIXME: Don't hardcode this check 1839 if (OA && isa<OwnershipAttr>(*i)) 1840 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1841 return true; 1842 } 1843 1844 return false; 1845} 1846 1847static bool isAttributeTargetADefinition(Decl *D) { 1848 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1849 return VD->isThisDeclarationADefinition(); 1850 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1851 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1852 return true; 1853} 1854 1855/// Merge alignment attributes from \p Old to \p New, taking into account the 1856/// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1857/// 1858/// \return \c true if any attributes were added to \p New. 1859static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1860 // Look for alignas attributes on Old, and pick out whichever attribute 1861 // specifies the strictest alignment requirement. 1862 AlignedAttr *OldAlignasAttr = 0; 1863 AlignedAttr *OldStrictestAlignAttr = 0; 1864 unsigned OldAlign = 0; 1865 for (specific_attr_iterator<AlignedAttr> 1866 I = Old->specific_attr_begin<AlignedAttr>(), 1867 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1868 // FIXME: We have no way of representing inherited dependent alignments 1869 // in a case like: 1870 // template<int A, int B> struct alignas(A) X; 1871 // template<int A, int B> struct alignas(B) X {}; 1872 // For now, we just ignore any alignas attributes which are not on the 1873 // definition in such a case. 1874 if (I->isAlignmentDependent()) 1875 return false; 1876 1877 if (I->isAlignas()) 1878 OldAlignasAttr = *I; 1879 1880 unsigned Align = I->getAlignment(S.Context); 1881 if (Align > OldAlign) { 1882 OldAlign = Align; 1883 OldStrictestAlignAttr = *I; 1884 } 1885 } 1886 1887 // Look for alignas attributes on New. 1888 AlignedAttr *NewAlignasAttr = 0; 1889 unsigned NewAlign = 0; 1890 for (specific_attr_iterator<AlignedAttr> 1891 I = New->specific_attr_begin<AlignedAttr>(), 1892 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1893 if (I->isAlignmentDependent()) 1894 return false; 1895 1896 if (I->isAlignas()) 1897 NewAlignasAttr = *I; 1898 1899 unsigned Align = I->getAlignment(S.Context); 1900 if (Align > NewAlign) 1901 NewAlign = Align; 1902 } 1903 1904 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1905 // Both declarations have 'alignas' attributes. We require them to match. 1906 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1907 // fall short. (If two declarations both have alignas, they must both match 1908 // every definition, and so must match each other if there is a definition.) 1909 1910 // If either declaration only contains 'alignas(0)' specifiers, then it 1911 // specifies the natural alignment for the type. 1912 if (OldAlign == 0 || NewAlign == 0) { 1913 QualType Ty; 1914 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1915 Ty = VD->getType(); 1916 else 1917 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1918 1919 if (OldAlign == 0) 1920 OldAlign = S.Context.getTypeAlign(Ty); 1921 if (NewAlign == 0) 1922 NewAlign = S.Context.getTypeAlign(Ty); 1923 } 1924 1925 if (OldAlign != NewAlign) { 1926 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1927 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1928 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1929 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1930 } 1931 } 1932 1933 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1934 // C++11 [dcl.align]p6: 1935 // if any declaration of an entity has an alignment-specifier, 1936 // every defining declaration of that entity shall specify an 1937 // equivalent alignment. 1938 // C11 6.7.5/7: 1939 // If the definition of an object does not have an alignment 1940 // specifier, any other declaration of that object shall also 1941 // have no alignment specifier. 1942 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1943 << OldAlignasAttr->isC11(); 1944 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1945 << OldAlignasAttr->isC11(); 1946 } 1947 1948 bool AnyAdded = false; 1949 1950 // Ensure we have an attribute representing the strictest alignment. 1951 if (OldAlign > NewAlign) { 1952 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1953 Clone->setInherited(true); 1954 New->addAttr(Clone); 1955 AnyAdded = true; 1956 } 1957 1958 // Ensure we have an alignas attribute if the old declaration had one. 1959 if (OldAlignasAttr && !NewAlignasAttr && 1960 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1961 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1962 Clone->setInherited(true); 1963 New->addAttr(Clone); 1964 AnyAdded = true; 1965 } 1966 1967 return AnyAdded; 1968} 1969 1970static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1971 bool Override) { 1972 InheritableAttr *NewAttr = NULL; 1973 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1974 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1975 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1976 AA->getIntroduced(), AA->getDeprecated(), 1977 AA->getObsoleted(), AA->getUnavailable(), 1978 AA->getMessage(), Override, 1979 AttrSpellingListIndex); 1980 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1981 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1982 AttrSpellingListIndex); 1983 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1984 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1985 AttrSpellingListIndex); 1986 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1987 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1988 AttrSpellingListIndex); 1989 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1990 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1991 AttrSpellingListIndex); 1992 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1993 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1994 FA->getFormatIdx(), FA->getFirstArg(), 1995 AttrSpellingListIndex); 1996 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1997 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1998 AttrSpellingListIndex); 1999 else if (isa<AlignedAttr>(Attr)) 2000 // AlignedAttrs are handled separately, because we need to handle all 2001 // such attributes on a declaration at the same time. 2002 NewAttr = 0; 2003 else if (!DeclHasAttr(D, Attr)) 2004 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2005 2006 if (NewAttr) { 2007 NewAttr->setInherited(true); 2008 D->addAttr(NewAttr); 2009 return true; 2010 } 2011 2012 return false; 2013} 2014 2015static const Decl *getDefinition(const Decl *D) { 2016 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2017 return TD->getDefinition(); 2018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2019 return VD->getDefinition(); 2020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2021 const FunctionDecl* Def; 2022 if (FD->hasBody(Def)) 2023 return Def; 2024 } 2025 return NULL; 2026} 2027 2028static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2029 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2030 I != E; ++I) { 2031 Attr *Attribute = *I; 2032 if (Attribute->getKind() == Kind) 2033 return true; 2034 } 2035 return false; 2036} 2037 2038/// checkNewAttributesAfterDef - If we already have a definition, check that 2039/// there are no new attributes in this declaration. 2040static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2041 if (!New->hasAttrs()) 2042 return; 2043 2044 const Decl *Def = getDefinition(Old); 2045 if (!Def || Def == New) 2046 return; 2047 2048 AttrVec &NewAttributes = New->getAttrs(); 2049 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2050 const Attr *NewAttribute = NewAttributes[I]; 2051 if (hasAttribute(Def, NewAttribute->getKind())) { 2052 ++I; 2053 continue; // regular attr merging will take care of validating this. 2054 } 2055 2056 if (isa<C11NoReturnAttr>(NewAttribute)) { 2057 // C's _Noreturn is allowed to be added to a function after it is defined. 2058 ++I; 2059 continue; 2060 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2061 if (AA->isAlignas()) { 2062 // C++11 [dcl.align]p6: 2063 // if any declaration of an entity has an alignment-specifier, 2064 // every defining declaration of that entity shall specify an 2065 // equivalent alignment. 2066 // C11 6.7.5/7: 2067 // If the definition of an object does not have an alignment 2068 // specifier, any other declaration of that object shall also 2069 // have no alignment specifier. 2070 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2071 << AA->isC11(); 2072 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2073 << AA->isC11(); 2074 NewAttributes.erase(NewAttributes.begin() + I); 2075 --E; 2076 continue; 2077 } 2078 } 2079 2080 S.Diag(NewAttribute->getLocation(), 2081 diag::warn_attribute_precede_definition); 2082 S.Diag(Def->getLocation(), diag::note_previous_definition); 2083 NewAttributes.erase(NewAttributes.begin() + I); 2084 --E; 2085 } 2086} 2087 2088/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2089void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2090 AvailabilityMergeKind AMK) { 2091 if (!Old->hasAttrs() && !New->hasAttrs()) 2092 return; 2093 2094 // attributes declared post-definition are currently ignored 2095 checkNewAttributesAfterDef(*this, New, Old); 2096 2097 if (!Old->hasAttrs()) 2098 return; 2099 2100 bool foundAny = New->hasAttrs(); 2101 2102 // Ensure that any moving of objects within the allocated map is done before 2103 // we process them. 2104 if (!foundAny) New->setAttrs(AttrVec()); 2105 2106 for (specific_attr_iterator<InheritableAttr> 2107 i = Old->specific_attr_begin<InheritableAttr>(), 2108 e = Old->specific_attr_end<InheritableAttr>(); 2109 i != e; ++i) { 2110 bool Override = false; 2111 // Ignore deprecated/unavailable/availability attributes if requested. 2112 if (isa<DeprecatedAttr>(*i) || 2113 isa<UnavailableAttr>(*i) || 2114 isa<AvailabilityAttr>(*i)) { 2115 switch (AMK) { 2116 case AMK_None: 2117 continue; 2118 2119 case AMK_Redeclaration: 2120 break; 2121 2122 case AMK_Override: 2123 Override = true; 2124 break; 2125 } 2126 } 2127 2128 if (mergeDeclAttribute(*this, New, *i, Override)) 2129 foundAny = true; 2130 } 2131 2132 if (mergeAlignedAttrs(*this, New, Old)) 2133 foundAny = true; 2134 2135 if (!foundAny) New->dropAttrs(); 2136} 2137 2138/// mergeParamDeclAttributes - Copy attributes from the old parameter 2139/// to the new one. 2140static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2141 const ParmVarDecl *oldDecl, 2142 Sema &S) { 2143 // C++11 [dcl.attr.depend]p2: 2144 // The first declaration of a function shall specify the 2145 // carries_dependency attribute for its declarator-id if any declaration 2146 // of the function specifies the carries_dependency attribute. 2147 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2148 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2149 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2150 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2151 // Find the first declaration of the parameter. 2152 // FIXME: Should we build redeclaration chains for function parameters? 2153 const FunctionDecl *FirstFD = 2154 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration(); 2155 const ParmVarDecl *FirstVD = 2156 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2157 S.Diag(FirstVD->getLocation(), 2158 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2159 } 2160 2161 if (!oldDecl->hasAttrs()) 2162 return; 2163 2164 bool foundAny = newDecl->hasAttrs(); 2165 2166 // Ensure that any moving of objects within the allocated map is 2167 // done before we process them. 2168 if (!foundAny) newDecl->setAttrs(AttrVec()); 2169 2170 for (specific_attr_iterator<InheritableParamAttr> 2171 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2172 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2173 if (!DeclHasAttr(newDecl, *i)) { 2174 InheritableAttr *newAttr = 2175 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2176 newAttr->setInherited(true); 2177 newDecl->addAttr(newAttr); 2178 foundAny = true; 2179 } 2180 } 2181 2182 if (!foundAny) newDecl->dropAttrs(); 2183} 2184 2185namespace { 2186 2187/// Used in MergeFunctionDecl to keep track of function parameters in 2188/// C. 2189struct GNUCompatibleParamWarning { 2190 ParmVarDecl *OldParm; 2191 ParmVarDecl *NewParm; 2192 QualType PromotedType; 2193}; 2194 2195} 2196 2197/// getSpecialMember - get the special member enum for a method. 2198Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2199 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2200 if (Ctor->isDefaultConstructor()) 2201 return Sema::CXXDefaultConstructor; 2202 2203 if (Ctor->isCopyConstructor()) 2204 return Sema::CXXCopyConstructor; 2205 2206 if (Ctor->isMoveConstructor()) 2207 return Sema::CXXMoveConstructor; 2208 } else if (isa<CXXDestructorDecl>(MD)) { 2209 return Sema::CXXDestructor; 2210 } else if (MD->isCopyAssignmentOperator()) { 2211 return Sema::CXXCopyAssignment; 2212 } else if (MD->isMoveAssignmentOperator()) { 2213 return Sema::CXXMoveAssignment; 2214 } 2215 2216 return Sema::CXXInvalid; 2217} 2218 2219/// canRedefineFunction - checks if a function can be redefined. Currently, 2220/// only extern inline functions can be redefined, and even then only in 2221/// GNU89 mode. 2222static bool canRedefineFunction(const FunctionDecl *FD, 2223 const LangOptions& LangOpts) { 2224 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2225 !LangOpts.CPlusPlus && 2226 FD->isInlineSpecified() && 2227 FD->getStorageClass() == SC_Extern); 2228} 2229 2230/// Is the given calling convention the ABI default for the given 2231/// declaration? 2232static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) { 2233 CallingConv ABIDefaultCC; 2234 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 2235 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic()); 2236 } else { 2237 // Free C function or a static method. 2238 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C); 2239 } 2240 return ABIDefaultCC == CC; 2241} 2242 2243template <typename T> 2244static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2245 const DeclContext *DC = Old->getDeclContext(); 2246 if (DC->isRecord()) 2247 return false; 2248 2249 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2250 if (OldLinkage == CXXLanguageLinkage && 2251 New->getDeclContext()->isExternCContext()) 2252 return true; 2253 if (OldLinkage == CLanguageLinkage && 2254 New->getDeclContext()->isExternCXXContext()) 2255 return true; 2256 return false; 2257} 2258 2259/// MergeFunctionDecl - We just parsed a function 'New' from 2260/// declarator D which has the same name and scope as a previous 2261/// declaration 'Old'. Figure out how to resolve this situation, 2262/// merging decls or emitting diagnostics as appropriate. 2263/// 2264/// In C++, New and Old must be declarations that are not 2265/// overloaded. Use IsOverload to determine whether New and Old are 2266/// overloaded, and to select the Old declaration that New should be 2267/// merged with. 2268/// 2269/// Returns true if there was an error, false otherwise. 2270bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 2271 // Verify the old decl was also a function. 2272 FunctionDecl *Old = 0; 2273 if (FunctionTemplateDecl *OldFunctionTemplate 2274 = dyn_cast<FunctionTemplateDecl>(OldD)) 2275 Old = OldFunctionTemplate->getTemplatedDecl(); 2276 else 2277 Old = dyn_cast<FunctionDecl>(OldD); 2278 if (!Old) { 2279 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2280 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2281 Diag(Shadow->getTargetDecl()->getLocation(), 2282 diag::note_using_decl_target); 2283 Diag(Shadow->getUsingDecl()->getLocation(), 2284 diag::note_using_decl) << 0; 2285 return true; 2286 } 2287 2288 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2289 << New->getDeclName(); 2290 Diag(OldD->getLocation(), diag::note_previous_definition); 2291 return true; 2292 } 2293 2294 // Determine whether the previous declaration was a definition, 2295 // implicit declaration, or a declaration. 2296 diag::kind PrevDiag; 2297 if (Old->isThisDeclarationADefinition()) 2298 PrevDiag = diag::note_previous_definition; 2299 else if (Old->isImplicit()) 2300 PrevDiag = diag::note_previous_implicit_declaration; 2301 else 2302 PrevDiag = diag::note_previous_declaration; 2303 2304 QualType OldQType = Context.getCanonicalType(Old->getType()); 2305 QualType NewQType = Context.getCanonicalType(New->getType()); 2306 2307 // Don't complain about this if we're in GNU89 mode and the old function 2308 // is an extern inline function. 2309 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2310 New->getStorageClass() == SC_Static && 2311 Old->getStorageClass() != SC_Static && 2312 !canRedefineFunction(Old, getLangOpts())) { 2313 if (getLangOpts().MicrosoftExt) { 2314 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2315 Diag(Old->getLocation(), PrevDiag); 2316 } else { 2317 Diag(New->getLocation(), diag::err_static_non_static) << New; 2318 Diag(Old->getLocation(), PrevDiag); 2319 return true; 2320 } 2321 } 2322 2323 // If a function is first declared with a calling convention, but is 2324 // later declared or defined without one, the second decl assumes the 2325 // calling convention of the first. 2326 // 2327 // It's OK if a function is first declared without a calling convention, 2328 // but is later declared or defined with the default calling convention. 2329 // 2330 // For the new decl, we have to look at the NON-canonical type to tell the 2331 // difference between a function that really doesn't have a calling 2332 // convention and one that is declared cdecl. That's because in 2333 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 2334 // because it is the default calling convention. 2335 // 2336 // Note also that we DO NOT return at this point, because we still have 2337 // other tests to run. 2338 const FunctionType *OldType = cast<FunctionType>(OldQType); 2339 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2340 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2341 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2342 bool RequiresAdjustment = false; 2343 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) { 2344 // Fast path: nothing to do. 2345 2346 // Inherit the CC from the previous declaration if it was specified 2347 // there but not here. 2348 } else if (NewTypeInfo.getCC() == CC_Default) { 2349 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2350 RequiresAdjustment = true; 2351 2352 // Don't complain about mismatches when the default CC is 2353 // effectively the same as the explict one. Only Old decl contains correct 2354 // information about storage class of CXXMethod. 2355 } else if (OldTypeInfo.getCC() == CC_Default && 2356 isABIDefaultCC(*this, NewTypeInfo.getCC(), Old)) { 2357 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2358 RequiresAdjustment = true; 2359 2360 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2361 NewTypeInfo.getCC())) { 2362 // Calling conventions really aren't compatible, so complain. 2363 Diag(New->getLocation(), diag::err_cconv_change) 2364 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2365 << (OldTypeInfo.getCC() == CC_Default) 2366 << (OldTypeInfo.getCC() == CC_Default ? "" : 2367 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2368 Diag(Old->getLocation(), diag::note_previous_declaration); 2369 return true; 2370 } 2371 2372 // FIXME: diagnose the other way around? 2373 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2374 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2375 RequiresAdjustment = true; 2376 } 2377 2378 // Merge regparm attribute. 2379 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2380 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2381 if (NewTypeInfo.getHasRegParm()) { 2382 Diag(New->getLocation(), diag::err_regparm_mismatch) 2383 << NewType->getRegParmType() 2384 << OldType->getRegParmType(); 2385 Diag(Old->getLocation(), diag::note_previous_declaration); 2386 return true; 2387 } 2388 2389 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2390 RequiresAdjustment = true; 2391 } 2392 2393 // Merge ns_returns_retained attribute. 2394 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2395 if (NewTypeInfo.getProducesResult()) { 2396 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2397 Diag(Old->getLocation(), diag::note_previous_declaration); 2398 return true; 2399 } 2400 2401 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2402 RequiresAdjustment = true; 2403 } 2404 2405 if (RequiresAdjustment) { 2406 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2407 New->setType(QualType(NewType, 0)); 2408 NewQType = Context.getCanonicalType(New->getType()); 2409 } 2410 2411 // If this redeclaration makes the function inline, we may need to add it to 2412 // UndefinedButUsed. 2413 if (!Old->isInlined() && New->isInlined() && 2414 !New->hasAttr<GNUInlineAttr>() && 2415 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2416 Old->isUsed(false) && 2417 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2418 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2419 SourceLocation())); 2420 2421 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2422 // about it. 2423 if (New->hasAttr<GNUInlineAttr>() && 2424 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2425 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2426 } 2427 2428 if (getLangOpts().CPlusPlus) { 2429 // (C++98 13.1p2): 2430 // Certain function declarations cannot be overloaded: 2431 // -- Function declarations that differ only in the return type 2432 // cannot be overloaded. 2433 QualType OldReturnType = OldType->getResultType(); 2434 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2435 QualType ResQT; 2436 if (OldReturnType != NewReturnType) { 2437 if (NewReturnType->isObjCObjectPointerType() 2438 && OldReturnType->isObjCObjectPointerType()) 2439 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2440 if (ResQT.isNull()) { 2441 if (New->isCXXClassMember() && New->isOutOfLine()) 2442 Diag(New->getLocation(), 2443 diag::err_member_def_does_not_match_ret_type) << New; 2444 else 2445 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2446 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2447 return true; 2448 } 2449 else 2450 NewQType = ResQT; 2451 } 2452 2453 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2454 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2455 if (OldMethod && NewMethod) { 2456 // Preserve triviality. 2457 NewMethod->setTrivial(OldMethod->isTrivial()); 2458 2459 // MSVC allows explicit template specialization at class scope: 2460 // 2 CXMethodDecls referring to the same function will be injected. 2461 // We don't want a redeclartion error. 2462 bool IsClassScopeExplicitSpecialization = 2463 OldMethod->isFunctionTemplateSpecialization() && 2464 NewMethod->isFunctionTemplateSpecialization(); 2465 bool isFriend = NewMethod->getFriendObjectKind(); 2466 2467 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2468 !IsClassScopeExplicitSpecialization) { 2469 // -- Member function declarations with the same name and the 2470 // same parameter types cannot be overloaded if any of them 2471 // is a static member function declaration. 2472 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2473 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2474 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2475 return true; 2476 } 2477 2478 // C++ [class.mem]p1: 2479 // [...] A member shall not be declared twice in the 2480 // member-specification, except that a nested class or member 2481 // class template can be declared and then later defined. 2482 if (ActiveTemplateInstantiations.empty()) { 2483 unsigned NewDiag; 2484 if (isa<CXXConstructorDecl>(OldMethod)) 2485 NewDiag = diag::err_constructor_redeclared; 2486 else if (isa<CXXDestructorDecl>(NewMethod)) 2487 NewDiag = diag::err_destructor_redeclared; 2488 else if (isa<CXXConversionDecl>(NewMethod)) 2489 NewDiag = diag::err_conv_function_redeclared; 2490 else 2491 NewDiag = diag::err_member_redeclared; 2492 2493 Diag(New->getLocation(), NewDiag); 2494 } else { 2495 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2496 << New << New->getType(); 2497 } 2498 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2499 2500 // Complain if this is an explicit declaration of a special 2501 // member that was initially declared implicitly. 2502 // 2503 // As an exception, it's okay to befriend such methods in order 2504 // to permit the implicit constructor/destructor/operator calls. 2505 } else if (OldMethod->isImplicit()) { 2506 if (isFriend) { 2507 NewMethod->setImplicit(); 2508 } else { 2509 Diag(NewMethod->getLocation(), 2510 diag::err_definition_of_implicitly_declared_member) 2511 << New << getSpecialMember(OldMethod); 2512 return true; 2513 } 2514 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2515 Diag(NewMethod->getLocation(), 2516 diag::err_definition_of_explicitly_defaulted_member) 2517 << getSpecialMember(OldMethod); 2518 return true; 2519 } 2520 } 2521 2522 // C++11 [dcl.attr.noreturn]p1: 2523 // The first declaration of a function shall specify the noreturn 2524 // attribute if any declaration of that function specifies the noreturn 2525 // attribute. 2526 if (New->hasAttr<CXX11NoReturnAttr>() && 2527 !Old->hasAttr<CXX11NoReturnAttr>()) { 2528 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2529 diag::err_noreturn_missing_on_first_decl); 2530 Diag(Old->getFirstDeclaration()->getLocation(), 2531 diag::note_noreturn_missing_first_decl); 2532 } 2533 2534 // C++11 [dcl.attr.depend]p2: 2535 // The first declaration of a function shall specify the 2536 // carries_dependency attribute for its declarator-id if any declaration 2537 // of the function specifies the carries_dependency attribute. 2538 if (New->hasAttr<CarriesDependencyAttr>() && 2539 !Old->hasAttr<CarriesDependencyAttr>()) { 2540 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2541 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2542 Diag(Old->getFirstDeclaration()->getLocation(), 2543 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2544 } 2545 2546 // (C++98 8.3.5p3): 2547 // All declarations for a function shall agree exactly in both the 2548 // return type and the parameter-type-list. 2549 // We also want to respect all the extended bits except noreturn. 2550 2551 // noreturn should now match unless the old type info didn't have it. 2552 QualType OldQTypeForComparison = OldQType; 2553 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2554 assert(OldQType == QualType(OldType, 0)); 2555 const FunctionType *OldTypeForComparison 2556 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2557 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2558 assert(OldQTypeForComparison.isCanonical()); 2559 } 2560 2561 if (haveIncompatibleLanguageLinkages(Old, New)) { 2562 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2563 Diag(Old->getLocation(), PrevDiag); 2564 return true; 2565 } 2566 2567 if (OldQTypeForComparison == NewQType) 2568 return MergeCompatibleFunctionDecls(New, Old, S); 2569 2570 // Fall through for conflicting redeclarations and redefinitions. 2571 } 2572 2573 // C: Function types need to be compatible, not identical. This handles 2574 // duplicate function decls like "void f(int); void f(enum X);" properly. 2575 if (!getLangOpts().CPlusPlus && 2576 Context.typesAreCompatible(OldQType, NewQType)) { 2577 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2578 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2579 const FunctionProtoType *OldProto = 0; 2580 if (isa<FunctionNoProtoType>(NewFuncType) && 2581 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2582 // The old declaration provided a function prototype, but the 2583 // new declaration does not. Merge in the prototype. 2584 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2585 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2586 OldProto->arg_type_end()); 2587 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2588 ParamTypes, 2589 OldProto->getExtProtoInfo()); 2590 New->setType(NewQType); 2591 New->setHasInheritedPrototype(); 2592 2593 // Synthesize a parameter for each argument type. 2594 SmallVector<ParmVarDecl*, 16> Params; 2595 for (FunctionProtoType::arg_type_iterator 2596 ParamType = OldProto->arg_type_begin(), 2597 ParamEnd = OldProto->arg_type_end(); 2598 ParamType != ParamEnd; ++ParamType) { 2599 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2600 SourceLocation(), 2601 SourceLocation(), 0, 2602 *ParamType, /*TInfo=*/0, 2603 SC_None, SC_None, 2604 0); 2605 Param->setScopeInfo(0, Params.size()); 2606 Param->setImplicit(); 2607 Params.push_back(Param); 2608 } 2609 2610 New->setParams(Params); 2611 } 2612 2613 return MergeCompatibleFunctionDecls(New, Old, S); 2614 } 2615 2616 // GNU C permits a K&R definition to follow a prototype declaration 2617 // if the declared types of the parameters in the K&R definition 2618 // match the types in the prototype declaration, even when the 2619 // promoted types of the parameters from the K&R definition differ 2620 // from the types in the prototype. GCC then keeps the types from 2621 // the prototype. 2622 // 2623 // If a variadic prototype is followed by a non-variadic K&R definition, 2624 // the K&R definition becomes variadic. This is sort of an edge case, but 2625 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2626 // C99 6.9.1p8. 2627 if (!getLangOpts().CPlusPlus && 2628 Old->hasPrototype() && !New->hasPrototype() && 2629 New->getType()->getAs<FunctionProtoType>() && 2630 Old->getNumParams() == New->getNumParams()) { 2631 SmallVector<QualType, 16> ArgTypes; 2632 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2633 const FunctionProtoType *OldProto 2634 = Old->getType()->getAs<FunctionProtoType>(); 2635 const FunctionProtoType *NewProto 2636 = New->getType()->getAs<FunctionProtoType>(); 2637 2638 // Determine whether this is the GNU C extension. 2639 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2640 NewProto->getResultType()); 2641 bool LooseCompatible = !MergedReturn.isNull(); 2642 for (unsigned Idx = 0, End = Old->getNumParams(); 2643 LooseCompatible && Idx != End; ++Idx) { 2644 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2645 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2646 if (Context.typesAreCompatible(OldParm->getType(), 2647 NewProto->getArgType(Idx))) { 2648 ArgTypes.push_back(NewParm->getType()); 2649 } else if (Context.typesAreCompatible(OldParm->getType(), 2650 NewParm->getType(), 2651 /*CompareUnqualified=*/true)) { 2652 GNUCompatibleParamWarning Warn 2653 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2654 Warnings.push_back(Warn); 2655 ArgTypes.push_back(NewParm->getType()); 2656 } else 2657 LooseCompatible = false; 2658 } 2659 2660 if (LooseCompatible) { 2661 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2662 Diag(Warnings[Warn].NewParm->getLocation(), 2663 diag::ext_param_promoted_not_compatible_with_prototype) 2664 << Warnings[Warn].PromotedType 2665 << Warnings[Warn].OldParm->getType(); 2666 if (Warnings[Warn].OldParm->getLocation().isValid()) 2667 Diag(Warnings[Warn].OldParm->getLocation(), 2668 diag::note_previous_declaration); 2669 } 2670 2671 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2672 OldProto->getExtProtoInfo())); 2673 return MergeCompatibleFunctionDecls(New, Old, S); 2674 } 2675 2676 // Fall through to diagnose conflicting types. 2677 } 2678 2679 // A function that has already been declared has been redeclared or defined 2680 // with a different type- show appropriate diagnostic 2681 if (unsigned BuiltinID = Old->getBuiltinID()) { 2682 // The user has declared a builtin function with an incompatible 2683 // signature. 2684 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2685 // The function the user is redeclaring is a library-defined 2686 // function like 'malloc' or 'printf'. Warn about the 2687 // redeclaration, then pretend that we don't know about this 2688 // library built-in. 2689 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2690 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2691 << Old << Old->getType(); 2692 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2693 Old->setInvalidDecl(); 2694 return false; 2695 } 2696 2697 PrevDiag = diag::note_previous_builtin_declaration; 2698 } 2699 2700 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2701 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2702 return true; 2703} 2704 2705/// \brief Completes the merge of two function declarations that are 2706/// known to be compatible. 2707/// 2708/// This routine handles the merging of attributes and other 2709/// properties of function declarations form the old declaration to 2710/// the new declaration, once we know that New is in fact a 2711/// redeclaration of Old. 2712/// 2713/// \returns false 2714bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2715 Scope *S) { 2716 // Merge the attributes 2717 mergeDeclAttributes(New, Old); 2718 2719 // Merge the storage class. 2720 if (Old->getStorageClass() != SC_Extern && 2721 Old->getStorageClass() != SC_None) 2722 New->setStorageClass(Old->getStorageClass()); 2723 2724 // Merge "pure" flag. 2725 if (Old->isPure()) 2726 New->setPure(); 2727 2728 // Merge "used" flag. 2729 if (Old->isUsed(false)) 2730 New->setUsed(); 2731 2732 // Merge attributes from the parameters. These can mismatch with K&R 2733 // declarations. 2734 if (New->getNumParams() == Old->getNumParams()) 2735 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2736 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2737 *this); 2738 2739 if (getLangOpts().CPlusPlus) 2740 return MergeCXXFunctionDecl(New, Old, S); 2741 2742 // Merge the function types so the we get the composite types for the return 2743 // and argument types. 2744 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2745 if (!Merged.isNull()) 2746 New->setType(Merged); 2747 2748 return false; 2749} 2750 2751 2752void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2753 ObjCMethodDecl *oldMethod) { 2754 2755 // Merge the attributes, including deprecated/unavailable 2756 mergeDeclAttributes(newMethod, oldMethod, AMK_Override); 2757 2758 // Merge attributes from the parameters. 2759 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2760 oe = oldMethod->param_end(); 2761 for (ObjCMethodDecl::param_iterator 2762 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2763 ni != ne && oi != oe; ++ni, ++oi) 2764 mergeParamDeclAttributes(*ni, *oi, *this); 2765 2766 CheckObjCMethodOverride(newMethod, oldMethod); 2767} 2768 2769/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2770/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2771/// emitting diagnostics as appropriate. 2772/// 2773/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2774/// to here in AddInitializerToDecl. We can't check them before the initializer 2775/// is attached. 2776void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2777 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2778 return; 2779 2780 QualType MergedT; 2781 if (getLangOpts().CPlusPlus) { 2782 AutoType *AT = New->getType()->getContainedAutoType(); 2783 if (AT && !AT->isDeduced()) { 2784 // We don't know what the new type is until the initializer is attached. 2785 return; 2786 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2787 // These could still be something that needs exception specs checked. 2788 return MergeVarDeclExceptionSpecs(New, Old); 2789 } 2790 // C++ [basic.link]p10: 2791 // [...] the types specified by all declarations referring to a given 2792 // object or function shall be identical, except that declarations for an 2793 // array object can specify array types that differ by the presence or 2794 // absence of a major array bound (8.3.4). 2795 else if (Old->getType()->isIncompleteArrayType() && 2796 New->getType()->isArrayType()) { 2797 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2798 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2799 if (Context.hasSameType(OldArray->getElementType(), 2800 NewArray->getElementType())) 2801 MergedT = New->getType(); 2802 } else if (Old->getType()->isArrayType() && 2803 New->getType()->isIncompleteArrayType()) { 2804 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2805 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2806 if (Context.hasSameType(OldArray->getElementType(), 2807 NewArray->getElementType())) 2808 MergedT = Old->getType(); 2809 } else if (New->getType()->isObjCObjectPointerType() 2810 && Old->getType()->isObjCObjectPointerType()) { 2811 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2812 Old->getType()); 2813 } 2814 } else { 2815 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2816 } 2817 if (MergedT.isNull()) { 2818 Diag(New->getLocation(), diag::err_redefinition_different_type) 2819 << New->getDeclName() << New->getType() << Old->getType(); 2820 Diag(Old->getLocation(), diag::note_previous_definition); 2821 return New->setInvalidDecl(); 2822 } 2823 New->setType(MergedT); 2824} 2825 2826/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2827/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2828/// situation, merging decls or emitting diagnostics as appropriate. 2829/// 2830/// Tentative definition rules (C99 6.9.2p2) are checked by 2831/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2832/// definitions here, since the initializer hasn't been attached. 2833/// 2834void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2835 // If the new decl is already invalid, don't do any other checking. 2836 if (New->isInvalidDecl()) 2837 return; 2838 2839 // Verify the old decl was also a variable. 2840 VarDecl *Old = 0; 2841 if (!Previous.isSingleResult() || 2842 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2843 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2844 << New->getDeclName(); 2845 Diag(Previous.getRepresentativeDecl()->getLocation(), 2846 diag::note_previous_definition); 2847 return New->setInvalidDecl(); 2848 } 2849 2850 // C++ [class.mem]p1: 2851 // A member shall not be declared twice in the member-specification [...] 2852 // 2853 // Here, we need only consider static data members. 2854 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2855 Diag(New->getLocation(), diag::err_duplicate_member) 2856 << New->getIdentifier(); 2857 Diag(Old->getLocation(), diag::note_previous_declaration); 2858 New->setInvalidDecl(); 2859 } 2860 2861 mergeDeclAttributes(New, Old); 2862 // Warn if an already-declared variable is made a weak_import in a subsequent 2863 // declaration 2864 if (New->getAttr<WeakImportAttr>() && 2865 Old->getStorageClass() == SC_None && 2866 !Old->getAttr<WeakImportAttr>()) { 2867 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2868 Diag(Old->getLocation(), diag::note_previous_definition); 2869 // Remove weak_import attribute on new declaration. 2870 New->dropAttr<WeakImportAttr>(); 2871 } 2872 2873 // Merge the types. 2874 MergeVarDeclTypes(New, Old); 2875 if (New->isInvalidDecl()) 2876 return; 2877 2878 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2879 if (New->getStorageClass() == SC_Static && 2880 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2881 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2882 Diag(Old->getLocation(), diag::note_previous_definition); 2883 return New->setInvalidDecl(); 2884 } 2885 // C99 6.2.2p4: 2886 // For an identifier declared with the storage-class specifier 2887 // extern in a scope in which a prior declaration of that 2888 // identifier is visible,23) if the prior declaration specifies 2889 // internal or external linkage, the linkage of the identifier at 2890 // the later declaration is the same as the linkage specified at 2891 // the prior declaration. If no prior declaration is visible, or 2892 // if the prior declaration specifies no linkage, then the 2893 // identifier has external linkage. 2894 if (New->hasExternalStorage() && Old->hasLinkage()) 2895 /* Okay */; 2896 else if (New->getStorageClass() != SC_Static && 2897 Old->getStorageClass() == SC_Static) { 2898 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2899 Diag(Old->getLocation(), diag::note_previous_definition); 2900 return New->setInvalidDecl(); 2901 } 2902 2903 // Check if extern is followed by non-extern and vice-versa. 2904 if (New->hasExternalStorage() && 2905 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2906 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2907 Diag(Old->getLocation(), diag::note_previous_definition); 2908 return New->setInvalidDecl(); 2909 } 2910 if (Old->hasExternalStorage() && 2911 New->isLocalVarDecl() && !New->hasLinkage()) { 2912 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2913 Diag(Old->getLocation(), diag::note_previous_definition); 2914 return New->setInvalidDecl(); 2915 } 2916 2917 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2918 2919 // FIXME: The test for external storage here seems wrong? We still 2920 // need to check for mismatches. 2921 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2922 // Don't complain about out-of-line definitions of static members. 2923 !(Old->getLexicalDeclContext()->isRecord() && 2924 !New->getLexicalDeclContext()->isRecord())) { 2925 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2926 Diag(Old->getLocation(), diag::note_previous_definition); 2927 return New->setInvalidDecl(); 2928 } 2929 2930 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2931 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2932 Diag(Old->getLocation(), diag::note_previous_definition); 2933 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2934 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2935 Diag(Old->getLocation(), diag::note_previous_definition); 2936 } 2937 2938 // C++ doesn't have tentative definitions, so go right ahead and check here. 2939 const VarDecl *Def; 2940 if (getLangOpts().CPlusPlus && 2941 New->isThisDeclarationADefinition() == VarDecl::Definition && 2942 (Def = Old->getDefinition())) { 2943 Diag(New->getLocation(), diag::err_redefinition) 2944 << New->getDeclName(); 2945 Diag(Def->getLocation(), diag::note_previous_definition); 2946 New->setInvalidDecl(); 2947 return; 2948 } 2949 2950 if (haveIncompatibleLanguageLinkages(Old, New)) { 2951 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2952 Diag(Old->getLocation(), diag::note_previous_definition); 2953 New->setInvalidDecl(); 2954 return; 2955 } 2956 2957 // c99 6.2.2 P4. 2958 // For an identifier declared with the storage-class specifier extern in a 2959 // scope in which a prior declaration of that identifier is visible, if 2960 // the prior declaration specifies internal or external linkage, the linkage 2961 // of the identifier at the later declaration is the same as the linkage 2962 // specified at the prior declaration. 2963 // FIXME. revisit this code. 2964 if (New->hasExternalStorage() && 2965 Old->getLinkage() == InternalLinkage) 2966 New->setStorageClass(Old->getStorageClass()); 2967 2968 // Merge "used" flag. 2969 if (Old->isUsed(false)) 2970 New->setUsed(); 2971 2972 // Keep a chain of previous declarations. 2973 New->setPreviousDeclaration(Old); 2974 2975 // Inherit access appropriately. 2976 New->setAccess(Old->getAccess()); 2977} 2978 2979/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2980/// no declarator (e.g. "struct foo;") is parsed. 2981Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2982 DeclSpec &DS) { 2983 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 2984} 2985 2986/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2987/// no declarator (e.g. "struct foo;") is parsed. It also accepts template 2988/// parameters to cope with template friend declarations. 2989Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2990 DeclSpec &DS, 2991 MultiTemplateParamsArg TemplateParams, 2992 bool IsExplicitInstantiation) { 2993 Decl *TagD = 0; 2994 TagDecl *Tag = 0; 2995 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2996 DS.getTypeSpecType() == DeclSpec::TST_struct || 2997 DS.getTypeSpecType() == DeclSpec::TST_interface || 2998 DS.getTypeSpecType() == DeclSpec::TST_union || 2999 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3000 TagD = DS.getRepAsDecl(); 3001 3002 if (!TagD) // We probably had an error 3003 return 0; 3004 3005 // Note that the above type specs guarantee that the 3006 // type rep is a Decl, whereas in many of the others 3007 // it's a Type. 3008 if (isa<TagDecl>(TagD)) 3009 Tag = cast<TagDecl>(TagD); 3010 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3011 Tag = CTD->getTemplatedDecl(); 3012 } 3013 3014 if (Tag) { 3015 getASTContext().addUnnamedTag(Tag); 3016 Tag->setFreeStanding(); 3017 if (Tag->isInvalidDecl()) 3018 return Tag; 3019 } 3020 3021 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3022 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3023 // or incomplete types shall not be restrict-qualified." 3024 if (TypeQuals & DeclSpec::TQ_restrict) 3025 Diag(DS.getRestrictSpecLoc(), 3026 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3027 << DS.getSourceRange(); 3028 } 3029 3030 if (DS.isConstexprSpecified()) { 3031 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3032 // and definitions of functions and variables. 3033 if (Tag) 3034 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3035 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3036 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3037 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3038 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3039 else 3040 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3041 // Don't emit warnings after this error. 3042 return TagD; 3043 } 3044 3045 DiagnoseFunctionSpecifiers(DS); 3046 3047 if (DS.isFriendSpecified()) { 3048 // If we're dealing with a decl but not a TagDecl, assume that 3049 // whatever routines created it handled the friendship aspect. 3050 if (TagD && !Tag) 3051 return 0; 3052 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3053 } 3054 3055 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3056 bool IsExplicitSpecialization = 3057 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3058 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3059 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3060 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3061 // nested-name-specifier unless it is an explicit instantiation 3062 // or an explicit specialization. 3063 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3064 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3065 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3066 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3067 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3068 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3069 << SS.getRange(); 3070 return 0; 3071 } 3072 3073 // Track whether this decl-specifier declares anything. 3074 bool DeclaresAnything = true; 3075 3076 // Handle anonymous struct definitions. 3077 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3078 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3079 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3080 if (getLangOpts().CPlusPlus || 3081 Record->getDeclContext()->isRecord()) 3082 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3083 3084 DeclaresAnything = false; 3085 } 3086 } 3087 3088 // Check for Microsoft C extension: anonymous struct member. 3089 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3090 CurContext->isRecord() && 3091 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3092 // Handle 2 kinds of anonymous struct: 3093 // struct STRUCT; 3094 // and 3095 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3096 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3097 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3098 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3099 DS.getRepAsType().get()->isStructureType())) { 3100 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3101 << DS.getSourceRange(); 3102 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3103 } 3104 } 3105 3106 // Skip all the checks below if we have a type error. 3107 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3108 (TagD && TagD->isInvalidDecl())) 3109 return TagD; 3110 3111 if (getLangOpts().CPlusPlus && 3112 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3113 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3114 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3115 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3116 DeclaresAnything = false; 3117 3118 if (!DS.isMissingDeclaratorOk()) { 3119 // Customize diagnostic for a typedef missing a name. 3120 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3121 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3122 << DS.getSourceRange(); 3123 else 3124 DeclaresAnything = false; 3125 } 3126 3127 if (DS.isModulePrivateSpecified() && 3128 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3129 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3130 << Tag->getTagKind() 3131 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3132 3133 ActOnDocumentableDecl(TagD); 3134 3135 // C 6.7/2: 3136 // A declaration [...] shall declare at least a declarator [...], a tag, 3137 // or the members of an enumeration. 3138 // C++ [dcl.dcl]p3: 3139 // [If there are no declarators], and except for the declaration of an 3140 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3141 // names into the program, or shall redeclare a name introduced by a 3142 // previous declaration. 3143 if (!DeclaresAnything) { 3144 // In C, we allow this as a (popular) extension / bug. Don't bother 3145 // producing further diagnostics for redundant qualifiers after this. 3146 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3147 return TagD; 3148 } 3149 3150 // C++ [dcl.stc]p1: 3151 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3152 // init-declarator-list of the declaration shall not be empty. 3153 // C++ [dcl.fct.spec]p1: 3154 // If a cv-qualifier appears in a decl-specifier-seq, the 3155 // init-declarator-list of the declaration shall not be empty. 3156 // 3157 // Spurious qualifiers here appear to be valid in C. 3158 unsigned DiagID = diag::warn_standalone_specifier; 3159 if (getLangOpts().CPlusPlus) 3160 DiagID = diag::ext_standalone_specifier; 3161 3162 // Note that a linkage-specification sets a storage class, but 3163 // 'extern "C" struct foo;' is actually valid and not theoretically 3164 // useless. 3165 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3166 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3167 Diag(DS.getStorageClassSpecLoc(), DiagID) 3168 << DeclSpec::getSpecifierName(SCS); 3169 3170 if (DS.isThreadSpecified()) 3171 Diag(DS.getThreadSpecLoc(), DiagID) << "__thread"; 3172 if (DS.getTypeQualifiers()) { 3173 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3174 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3175 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3176 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3177 // Restrict is covered above. 3178 } 3179 3180 // Warn about ignored type attributes, for example: 3181 // __attribute__((aligned)) struct A; 3182 // Attributes should be placed after tag to apply to type declaration. 3183 if (!DS.getAttributes().empty()) { 3184 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3185 if (TypeSpecType == DeclSpec::TST_class || 3186 TypeSpecType == DeclSpec::TST_struct || 3187 TypeSpecType == DeclSpec::TST_interface || 3188 TypeSpecType == DeclSpec::TST_union || 3189 TypeSpecType == DeclSpec::TST_enum) { 3190 AttributeList* attrs = DS.getAttributes().getList(); 3191 while (attrs) { 3192 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3193 << attrs->getName() 3194 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3195 TypeSpecType == DeclSpec::TST_struct ? 1 : 3196 TypeSpecType == DeclSpec::TST_union ? 2 : 3197 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3198 attrs = attrs->getNext(); 3199 } 3200 } 3201 } 3202 3203 return TagD; 3204} 3205 3206/// We are trying to inject an anonymous member into the given scope; 3207/// check if there's an existing declaration that can't be overloaded. 3208/// 3209/// \return true if this is a forbidden redeclaration 3210static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3211 Scope *S, 3212 DeclContext *Owner, 3213 DeclarationName Name, 3214 SourceLocation NameLoc, 3215 unsigned diagnostic) { 3216 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3217 Sema::ForRedeclaration); 3218 if (!SemaRef.LookupName(R, S)) return false; 3219 3220 if (R.getAsSingle<TagDecl>()) 3221 return false; 3222 3223 // Pick a representative declaration. 3224 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3225 assert(PrevDecl && "Expected a non-null Decl"); 3226 3227 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3228 return false; 3229 3230 SemaRef.Diag(NameLoc, diagnostic) << Name; 3231 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3232 3233 return true; 3234} 3235 3236/// InjectAnonymousStructOrUnionMembers - Inject the members of the 3237/// anonymous struct or union AnonRecord into the owning context Owner 3238/// and scope S. This routine will be invoked just after we realize 3239/// that an unnamed union or struct is actually an anonymous union or 3240/// struct, e.g., 3241/// 3242/// @code 3243/// union { 3244/// int i; 3245/// float f; 3246/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3247/// // f into the surrounding scope.x 3248/// @endcode 3249/// 3250/// This routine is recursive, injecting the names of nested anonymous 3251/// structs/unions into the owning context and scope as well. 3252static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3253 DeclContext *Owner, 3254 RecordDecl *AnonRecord, 3255 AccessSpecifier AS, 3256 SmallVector<NamedDecl*, 2> &Chaining, 3257 bool MSAnonStruct) { 3258 unsigned diagKind 3259 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3260 : diag::err_anonymous_struct_member_redecl; 3261 3262 bool Invalid = false; 3263 3264 // Look every FieldDecl and IndirectFieldDecl with a name. 3265 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3266 DEnd = AnonRecord->decls_end(); 3267 D != DEnd; ++D) { 3268 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3269 cast<NamedDecl>(*D)->getDeclName()) { 3270 ValueDecl *VD = cast<ValueDecl>(*D); 3271 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3272 VD->getLocation(), diagKind)) { 3273 // C++ [class.union]p2: 3274 // The names of the members of an anonymous union shall be 3275 // distinct from the names of any other entity in the 3276 // scope in which the anonymous union is declared. 3277 Invalid = true; 3278 } else { 3279 // C++ [class.union]p2: 3280 // For the purpose of name lookup, after the anonymous union 3281 // definition, the members of the anonymous union are 3282 // considered to have been defined in the scope in which the 3283 // anonymous union is declared. 3284 unsigned OldChainingSize = Chaining.size(); 3285 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3286 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3287 PE = IF->chain_end(); PI != PE; ++PI) 3288 Chaining.push_back(*PI); 3289 else 3290 Chaining.push_back(VD); 3291 3292 assert(Chaining.size() >= 2); 3293 NamedDecl **NamedChain = 3294 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3295 for (unsigned i = 0; i < Chaining.size(); i++) 3296 NamedChain[i] = Chaining[i]; 3297 3298 IndirectFieldDecl* IndirectField = 3299 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3300 VD->getIdentifier(), VD->getType(), 3301 NamedChain, Chaining.size()); 3302 3303 IndirectField->setAccess(AS); 3304 IndirectField->setImplicit(); 3305 SemaRef.PushOnScopeChains(IndirectField, S); 3306 3307 // That includes picking up the appropriate access specifier. 3308 if (AS != AS_none) IndirectField->setAccess(AS); 3309 3310 Chaining.resize(OldChainingSize); 3311 } 3312 } 3313 } 3314 3315 return Invalid; 3316} 3317 3318/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3319/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3320/// illegal input values are mapped to SC_None. 3321static StorageClass 3322StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3323 switch (StorageClassSpec) { 3324 case DeclSpec::SCS_unspecified: return SC_None; 3325 case DeclSpec::SCS_extern: return SC_Extern; 3326 case DeclSpec::SCS_static: return SC_Static; 3327 case DeclSpec::SCS_auto: return SC_Auto; 3328 case DeclSpec::SCS_register: return SC_Register; 3329 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3330 // Illegal SCSs map to None: error reporting is up to the caller. 3331 case DeclSpec::SCS_mutable: // Fall through. 3332 case DeclSpec::SCS_typedef: return SC_None; 3333 } 3334 llvm_unreachable("unknown storage class specifier"); 3335} 3336 3337/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 3338/// a StorageClass. Any error reporting is up to the caller: 3339/// illegal input values are mapped to SC_None. 3340static StorageClass 3341StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3342 switch (StorageClassSpec) { 3343 case DeclSpec::SCS_unspecified: return SC_None; 3344 case DeclSpec::SCS_extern: return SC_Extern; 3345 case DeclSpec::SCS_static: return SC_Static; 3346 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3347 // Illegal SCSs map to None: error reporting is up to the caller. 3348 case DeclSpec::SCS_auto: // Fall through. 3349 case DeclSpec::SCS_mutable: // Fall through. 3350 case DeclSpec::SCS_register: // Fall through. 3351 case DeclSpec::SCS_typedef: return SC_None; 3352 } 3353 llvm_unreachable("unknown storage class specifier"); 3354} 3355 3356/// BuildAnonymousStructOrUnion - Handle the declaration of an 3357/// anonymous structure or union. Anonymous unions are a C++ feature 3358/// (C++ [class.union]) and a C11 feature; anonymous structures 3359/// are a C11 feature and GNU C++ extension. 3360Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3361 AccessSpecifier AS, 3362 RecordDecl *Record) { 3363 DeclContext *Owner = Record->getDeclContext(); 3364 3365 // Diagnose whether this anonymous struct/union is an extension. 3366 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3367 Diag(Record->getLocation(), diag::ext_anonymous_union); 3368 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3369 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3370 else if (!Record->isUnion() && !getLangOpts().C11) 3371 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3372 3373 // C and C++ require different kinds of checks for anonymous 3374 // structs/unions. 3375 bool Invalid = false; 3376 if (getLangOpts().CPlusPlus) { 3377 const char* PrevSpec = 0; 3378 unsigned DiagID; 3379 if (Record->isUnion()) { 3380 // C++ [class.union]p6: 3381 // Anonymous unions declared in a named namespace or in the 3382 // global namespace shall be declared static. 3383 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3384 (isa<TranslationUnitDecl>(Owner) || 3385 (isa<NamespaceDecl>(Owner) && 3386 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3387 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3388 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3389 3390 // Recover by adding 'static'. 3391 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3392 PrevSpec, DiagID); 3393 } 3394 // C++ [class.union]p6: 3395 // A storage class is not allowed in a declaration of an 3396 // anonymous union in a class scope. 3397 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3398 isa<RecordDecl>(Owner)) { 3399 Diag(DS.getStorageClassSpecLoc(), 3400 diag::err_anonymous_union_with_storage_spec) 3401 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3402 3403 // Recover by removing the storage specifier. 3404 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3405 SourceLocation(), 3406 PrevSpec, DiagID); 3407 } 3408 } 3409 3410 // Ignore const/volatile/restrict qualifiers. 3411 if (DS.getTypeQualifiers()) { 3412 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3413 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3414 << Record->isUnion() << 0 3415 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3416 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3417 Diag(DS.getVolatileSpecLoc(), 3418 diag::ext_anonymous_struct_union_qualified) 3419 << Record->isUnion() << 1 3420 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3421 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3422 Diag(DS.getRestrictSpecLoc(), 3423 diag::ext_anonymous_struct_union_qualified) 3424 << Record->isUnion() << 2 3425 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3426 3427 DS.ClearTypeQualifiers(); 3428 } 3429 3430 // C++ [class.union]p2: 3431 // The member-specification of an anonymous union shall only 3432 // define non-static data members. [Note: nested types and 3433 // functions cannot be declared within an anonymous union. ] 3434 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3435 MemEnd = Record->decls_end(); 3436 Mem != MemEnd; ++Mem) { 3437 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3438 // C++ [class.union]p3: 3439 // An anonymous union shall not have private or protected 3440 // members (clause 11). 3441 assert(FD->getAccess() != AS_none); 3442 if (FD->getAccess() != AS_public) { 3443 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3444 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3445 Invalid = true; 3446 } 3447 3448 // C++ [class.union]p1 3449 // An object of a class with a non-trivial constructor, a non-trivial 3450 // copy constructor, a non-trivial destructor, or a non-trivial copy 3451 // assignment operator cannot be a member of a union, nor can an 3452 // array of such objects. 3453 if (CheckNontrivialField(FD)) 3454 Invalid = true; 3455 } else if ((*Mem)->isImplicit()) { 3456 // Any implicit members are fine. 3457 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3458 // This is a type that showed up in an 3459 // elaborated-type-specifier inside the anonymous struct or 3460 // union, but which actually declares a type outside of the 3461 // anonymous struct or union. It's okay. 3462 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3463 if (!MemRecord->isAnonymousStructOrUnion() && 3464 MemRecord->getDeclName()) { 3465 // Visual C++ allows type definition in anonymous struct or union. 3466 if (getLangOpts().MicrosoftExt) 3467 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3468 << (int)Record->isUnion(); 3469 else { 3470 // This is a nested type declaration. 3471 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3472 << (int)Record->isUnion(); 3473 Invalid = true; 3474 } 3475 } else { 3476 // This is an anonymous type definition within another anonymous type. 3477 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3478 // not part of standard C++. 3479 Diag(MemRecord->getLocation(), 3480 diag::ext_anonymous_record_with_anonymous_type) 3481 << (int)Record->isUnion(); 3482 } 3483 } else if (isa<AccessSpecDecl>(*Mem)) { 3484 // Any access specifier is fine. 3485 } else { 3486 // We have something that isn't a non-static data 3487 // member. Complain about it. 3488 unsigned DK = diag::err_anonymous_record_bad_member; 3489 if (isa<TypeDecl>(*Mem)) 3490 DK = diag::err_anonymous_record_with_type; 3491 else if (isa<FunctionDecl>(*Mem)) 3492 DK = diag::err_anonymous_record_with_function; 3493 else if (isa<VarDecl>(*Mem)) 3494 DK = diag::err_anonymous_record_with_static; 3495 3496 // Visual C++ allows type definition in anonymous struct or union. 3497 if (getLangOpts().MicrosoftExt && 3498 DK == diag::err_anonymous_record_with_type) 3499 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3500 << (int)Record->isUnion(); 3501 else { 3502 Diag((*Mem)->getLocation(), DK) 3503 << (int)Record->isUnion(); 3504 Invalid = true; 3505 } 3506 } 3507 } 3508 } 3509 3510 if (!Record->isUnion() && !Owner->isRecord()) { 3511 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3512 << (int)getLangOpts().CPlusPlus; 3513 Invalid = true; 3514 } 3515 3516 // Mock up a declarator. 3517 Declarator Dc(DS, Declarator::MemberContext); 3518 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3519 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3520 3521 // Create a declaration for this anonymous struct/union. 3522 NamedDecl *Anon = 0; 3523 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3524 Anon = FieldDecl::Create(Context, OwningClass, 3525 DS.getLocStart(), 3526 Record->getLocation(), 3527 /*IdentifierInfo=*/0, 3528 Context.getTypeDeclType(Record), 3529 TInfo, 3530 /*BitWidth=*/0, /*Mutable=*/false, 3531 /*InitStyle=*/ICIS_NoInit); 3532 Anon->setAccess(AS); 3533 if (getLangOpts().CPlusPlus) 3534 FieldCollector->Add(cast<FieldDecl>(Anon)); 3535 } else { 3536 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3537 assert(SCSpec != DeclSpec::SCS_typedef && 3538 "Parser allowed 'typedef' as storage class VarDecl."); 3539 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3540 if (SCSpec == DeclSpec::SCS_mutable) { 3541 // mutable can only appear on non-static class members, so it's always 3542 // an error here 3543 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3544 Invalid = true; 3545 SC = SC_None; 3546 } 3547 SCSpec = DS.getStorageClassSpecAsWritten(); 3548 VarDecl::StorageClass SCAsWritten 3549 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3550 3551 Anon = VarDecl::Create(Context, Owner, 3552 DS.getLocStart(), 3553 Record->getLocation(), /*IdentifierInfo=*/0, 3554 Context.getTypeDeclType(Record), 3555 TInfo, SC, SCAsWritten); 3556 3557 // Default-initialize the implicit variable. This initialization will be 3558 // trivial in almost all cases, except if a union member has an in-class 3559 // initializer: 3560 // union { int n = 0; }; 3561 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3562 } 3563 Anon->setImplicit(); 3564 3565 // Add the anonymous struct/union object to the current 3566 // context. We'll be referencing this object when we refer to one of 3567 // its members. 3568 Owner->addDecl(Anon); 3569 3570 // Inject the members of the anonymous struct/union into the owning 3571 // context and into the identifier resolver chain for name lookup 3572 // purposes. 3573 SmallVector<NamedDecl*, 2> Chain; 3574 Chain.push_back(Anon); 3575 3576 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3577 Chain, false)) 3578 Invalid = true; 3579 3580 // Mark this as an anonymous struct/union type. Note that we do not 3581 // do this until after we have already checked and injected the 3582 // members of this anonymous struct/union type, because otherwise 3583 // the members could be injected twice: once by DeclContext when it 3584 // builds its lookup table, and once by 3585 // InjectAnonymousStructOrUnionMembers. 3586 Record->setAnonymousStructOrUnion(true); 3587 3588 if (Invalid) 3589 Anon->setInvalidDecl(); 3590 3591 return Anon; 3592} 3593 3594/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3595/// Microsoft C anonymous structure. 3596/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3597/// Example: 3598/// 3599/// struct A { int a; }; 3600/// struct B { struct A; int b; }; 3601/// 3602/// void foo() { 3603/// B var; 3604/// var.a = 3; 3605/// } 3606/// 3607Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3608 RecordDecl *Record) { 3609 3610 // If there is no Record, get the record via the typedef. 3611 if (!Record) 3612 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3613 3614 // Mock up a declarator. 3615 Declarator Dc(DS, Declarator::TypeNameContext); 3616 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3617 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3618 3619 // Create a declaration for this anonymous struct. 3620 NamedDecl* Anon = FieldDecl::Create(Context, 3621 cast<RecordDecl>(CurContext), 3622 DS.getLocStart(), 3623 DS.getLocStart(), 3624 /*IdentifierInfo=*/0, 3625 Context.getTypeDeclType(Record), 3626 TInfo, 3627 /*BitWidth=*/0, /*Mutable=*/false, 3628 /*InitStyle=*/ICIS_NoInit); 3629 Anon->setImplicit(); 3630 3631 // Add the anonymous struct object to the current context. 3632 CurContext->addDecl(Anon); 3633 3634 // Inject the members of the anonymous struct into the current 3635 // context and into the identifier resolver chain for name lookup 3636 // purposes. 3637 SmallVector<NamedDecl*, 2> Chain; 3638 Chain.push_back(Anon); 3639 3640 RecordDecl *RecordDef = Record->getDefinition(); 3641 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3642 RecordDef, AS_none, 3643 Chain, true)) 3644 Anon->setInvalidDecl(); 3645 3646 return Anon; 3647} 3648 3649/// GetNameForDeclarator - Determine the full declaration name for the 3650/// given Declarator. 3651DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3652 return GetNameFromUnqualifiedId(D.getName()); 3653} 3654 3655/// \brief Retrieves the declaration name from a parsed unqualified-id. 3656DeclarationNameInfo 3657Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3658 DeclarationNameInfo NameInfo; 3659 NameInfo.setLoc(Name.StartLocation); 3660 3661 switch (Name.getKind()) { 3662 3663 case UnqualifiedId::IK_ImplicitSelfParam: 3664 case UnqualifiedId::IK_Identifier: 3665 NameInfo.setName(Name.Identifier); 3666 NameInfo.setLoc(Name.StartLocation); 3667 return NameInfo; 3668 3669 case UnqualifiedId::IK_OperatorFunctionId: 3670 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3671 Name.OperatorFunctionId.Operator)); 3672 NameInfo.setLoc(Name.StartLocation); 3673 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3674 = Name.OperatorFunctionId.SymbolLocations[0]; 3675 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3676 = Name.EndLocation.getRawEncoding(); 3677 return NameInfo; 3678 3679 case UnqualifiedId::IK_LiteralOperatorId: 3680 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3681 Name.Identifier)); 3682 NameInfo.setLoc(Name.StartLocation); 3683 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3684 return NameInfo; 3685 3686 case UnqualifiedId::IK_ConversionFunctionId: { 3687 TypeSourceInfo *TInfo; 3688 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3689 if (Ty.isNull()) 3690 return DeclarationNameInfo(); 3691 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3692 Context.getCanonicalType(Ty))); 3693 NameInfo.setLoc(Name.StartLocation); 3694 NameInfo.setNamedTypeInfo(TInfo); 3695 return NameInfo; 3696 } 3697 3698 case UnqualifiedId::IK_ConstructorName: { 3699 TypeSourceInfo *TInfo; 3700 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3701 if (Ty.isNull()) 3702 return DeclarationNameInfo(); 3703 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3704 Context.getCanonicalType(Ty))); 3705 NameInfo.setLoc(Name.StartLocation); 3706 NameInfo.setNamedTypeInfo(TInfo); 3707 return NameInfo; 3708 } 3709 3710 case UnqualifiedId::IK_ConstructorTemplateId: { 3711 // In well-formed code, we can only have a constructor 3712 // template-id that refers to the current context, so go there 3713 // to find the actual type being constructed. 3714 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3715 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3716 return DeclarationNameInfo(); 3717 3718 // Determine the type of the class being constructed. 3719 QualType CurClassType = Context.getTypeDeclType(CurClass); 3720 3721 // FIXME: Check two things: that the template-id names the same type as 3722 // CurClassType, and that the template-id does not occur when the name 3723 // was qualified. 3724 3725 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3726 Context.getCanonicalType(CurClassType))); 3727 NameInfo.setLoc(Name.StartLocation); 3728 // FIXME: should we retrieve TypeSourceInfo? 3729 NameInfo.setNamedTypeInfo(0); 3730 return NameInfo; 3731 } 3732 3733 case UnqualifiedId::IK_DestructorName: { 3734 TypeSourceInfo *TInfo; 3735 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3736 if (Ty.isNull()) 3737 return DeclarationNameInfo(); 3738 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3739 Context.getCanonicalType(Ty))); 3740 NameInfo.setLoc(Name.StartLocation); 3741 NameInfo.setNamedTypeInfo(TInfo); 3742 return NameInfo; 3743 } 3744 3745 case UnqualifiedId::IK_TemplateId: { 3746 TemplateName TName = Name.TemplateId->Template.get(); 3747 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3748 return Context.getNameForTemplate(TName, TNameLoc); 3749 } 3750 3751 } // switch (Name.getKind()) 3752 3753 llvm_unreachable("Unknown name kind"); 3754} 3755 3756static QualType getCoreType(QualType Ty) { 3757 do { 3758 if (Ty->isPointerType() || Ty->isReferenceType()) 3759 Ty = Ty->getPointeeType(); 3760 else if (Ty->isArrayType()) 3761 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3762 else 3763 return Ty.withoutLocalFastQualifiers(); 3764 } while (true); 3765} 3766 3767/// hasSimilarParameters - Determine whether the C++ functions Declaration 3768/// and Definition have "nearly" matching parameters. This heuristic is 3769/// used to improve diagnostics in the case where an out-of-line function 3770/// definition doesn't match any declaration within the class or namespace. 3771/// Also sets Params to the list of indices to the parameters that differ 3772/// between the declaration and the definition. If hasSimilarParameters 3773/// returns true and Params is empty, then all of the parameters match. 3774static bool hasSimilarParameters(ASTContext &Context, 3775 FunctionDecl *Declaration, 3776 FunctionDecl *Definition, 3777 SmallVectorImpl<unsigned> &Params) { 3778 Params.clear(); 3779 if (Declaration->param_size() != Definition->param_size()) 3780 return false; 3781 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3782 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3783 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3784 3785 // The parameter types are identical 3786 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3787 continue; 3788 3789 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3790 QualType DefParamBaseTy = getCoreType(DefParamTy); 3791 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3792 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3793 3794 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3795 (DeclTyName && DeclTyName == DefTyName)) 3796 Params.push_back(Idx); 3797 else // The two parameters aren't even close 3798 return false; 3799 } 3800 3801 return true; 3802} 3803 3804/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3805/// declarator needs to be rebuilt in the current instantiation. 3806/// Any bits of declarator which appear before the name are valid for 3807/// consideration here. That's specifically the type in the decl spec 3808/// and the base type in any member-pointer chunks. 3809static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3810 DeclarationName Name) { 3811 // The types we specifically need to rebuild are: 3812 // - typenames, typeofs, and decltypes 3813 // - types which will become injected class names 3814 // Of course, we also need to rebuild any type referencing such a 3815 // type. It's safest to just say "dependent", but we call out a 3816 // few cases here. 3817 3818 DeclSpec &DS = D.getMutableDeclSpec(); 3819 switch (DS.getTypeSpecType()) { 3820 case DeclSpec::TST_typename: 3821 case DeclSpec::TST_typeofType: 3822 case DeclSpec::TST_underlyingType: 3823 case DeclSpec::TST_atomic: { 3824 // Grab the type from the parser. 3825 TypeSourceInfo *TSI = 0; 3826 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3827 if (T.isNull() || !T->isDependentType()) break; 3828 3829 // Make sure there's a type source info. This isn't really much 3830 // of a waste; most dependent types should have type source info 3831 // attached already. 3832 if (!TSI) 3833 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3834 3835 // Rebuild the type in the current instantiation. 3836 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3837 if (!TSI) return true; 3838 3839 // Store the new type back in the decl spec. 3840 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3841 DS.UpdateTypeRep(LocType); 3842 break; 3843 } 3844 3845 case DeclSpec::TST_decltype: 3846 case DeclSpec::TST_typeofExpr: { 3847 Expr *E = DS.getRepAsExpr(); 3848 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3849 if (Result.isInvalid()) return true; 3850 DS.UpdateExprRep(Result.get()); 3851 break; 3852 } 3853 3854 default: 3855 // Nothing to do for these decl specs. 3856 break; 3857 } 3858 3859 // It doesn't matter what order we do this in. 3860 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3861 DeclaratorChunk &Chunk = D.getTypeObject(I); 3862 3863 // The only type information in the declarator which can come 3864 // before the declaration name is the base type of a member 3865 // pointer. 3866 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3867 continue; 3868 3869 // Rebuild the scope specifier in-place. 3870 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3871 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3872 return true; 3873 } 3874 3875 return false; 3876} 3877 3878Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3879 D.setFunctionDefinitionKind(FDK_Declaration); 3880 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3881 3882 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3883 Dcl && Dcl->getDeclContext()->isFileContext()) 3884 Dcl->setTopLevelDeclInObjCContainer(); 3885 3886 return Dcl; 3887} 3888 3889/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3890/// If T is the name of a class, then each of the following shall have a 3891/// name different from T: 3892/// - every static data member of class T; 3893/// - every member function of class T 3894/// - every member of class T that is itself a type; 3895/// \returns true if the declaration name violates these rules. 3896bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3897 DeclarationNameInfo NameInfo) { 3898 DeclarationName Name = NameInfo.getName(); 3899 3900 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3901 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3902 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3903 return true; 3904 } 3905 3906 return false; 3907} 3908 3909/// \brief Diagnose a declaration whose declarator-id has the given 3910/// nested-name-specifier. 3911/// 3912/// \param SS The nested-name-specifier of the declarator-id. 3913/// 3914/// \param DC The declaration context to which the nested-name-specifier 3915/// resolves. 3916/// 3917/// \param Name The name of the entity being declared. 3918/// 3919/// \param Loc The location of the name of the entity being declared. 3920/// 3921/// \returns true if we cannot safely recover from this error, false otherwise. 3922bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3923 DeclarationName Name, 3924 SourceLocation Loc) { 3925 DeclContext *Cur = CurContext; 3926 while (isa<LinkageSpecDecl>(Cur)) 3927 Cur = Cur->getParent(); 3928 3929 // C++ [dcl.meaning]p1: 3930 // A declarator-id shall not be qualified except for the definition 3931 // of a member function (9.3) or static data member (9.4) outside of 3932 // its class, the definition or explicit instantiation of a function 3933 // or variable member of a namespace outside of its namespace, or the 3934 // definition of an explicit specialization outside of its namespace, 3935 // or the declaration of a friend function that is a member of 3936 // another class or namespace (11.3). [...] 3937 3938 // The user provided a superfluous scope specifier that refers back to the 3939 // class or namespaces in which the entity is already declared. 3940 // 3941 // class X { 3942 // void X::f(); 3943 // }; 3944 if (Cur->Equals(DC)) { 3945 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3946 : diag::err_member_extra_qualification) 3947 << Name << FixItHint::CreateRemoval(SS.getRange()); 3948 SS.clear(); 3949 return false; 3950 } 3951 3952 // Check whether the qualifying scope encloses the scope of the original 3953 // declaration. 3954 if (!Cur->Encloses(DC)) { 3955 if (Cur->isRecord()) 3956 Diag(Loc, diag::err_member_qualification) 3957 << Name << SS.getRange(); 3958 else if (isa<TranslationUnitDecl>(DC)) 3959 Diag(Loc, diag::err_invalid_declarator_global_scope) 3960 << Name << SS.getRange(); 3961 else if (isa<FunctionDecl>(Cur)) 3962 Diag(Loc, diag::err_invalid_declarator_in_function) 3963 << Name << SS.getRange(); 3964 else 3965 Diag(Loc, diag::err_invalid_declarator_scope) 3966 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3967 3968 return true; 3969 } 3970 3971 if (Cur->isRecord()) { 3972 // Cannot qualify members within a class. 3973 Diag(Loc, diag::err_member_qualification) 3974 << Name << SS.getRange(); 3975 SS.clear(); 3976 3977 // C++ constructors and destructors with incorrect scopes can break 3978 // our AST invariants by having the wrong underlying types. If 3979 // that's the case, then drop this declaration entirely. 3980 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3981 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3982 !Context.hasSameType(Name.getCXXNameType(), 3983 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3984 return true; 3985 3986 return false; 3987 } 3988 3989 // C++11 [dcl.meaning]p1: 3990 // [...] "The nested-name-specifier of the qualified declarator-id shall 3991 // not begin with a decltype-specifer" 3992 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3993 while (SpecLoc.getPrefix()) 3994 SpecLoc = SpecLoc.getPrefix(); 3995 if (dyn_cast_or_null<DecltypeType>( 3996 SpecLoc.getNestedNameSpecifier()->getAsType())) 3997 Diag(Loc, diag::err_decltype_in_declarator) 3998 << SpecLoc.getTypeLoc().getSourceRange(); 3999 4000 return false; 4001} 4002 4003NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4004 MultiTemplateParamsArg TemplateParamLists) { 4005 // TODO: consider using NameInfo for diagnostic. 4006 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4007 DeclarationName Name = NameInfo.getName(); 4008 4009 // All of these full declarators require an identifier. If it doesn't have 4010 // one, the ParsedFreeStandingDeclSpec action should be used. 4011 if (!Name) { 4012 if (!D.isInvalidType()) // Reject this if we think it is valid. 4013 Diag(D.getDeclSpec().getLocStart(), 4014 diag::err_declarator_need_ident) 4015 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4016 return 0; 4017 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4018 return 0; 4019 4020 // The scope passed in may not be a decl scope. Zip up the scope tree until 4021 // we find one that is. 4022 while ((S->getFlags() & Scope::DeclScope) == 0 || 4023 (S->getFlags() & Scope::TemplateParamScope) != 0) 4024 S = S->getParent(); 4025 4026 DeclContext *DC = CurContext; 4027 if (D.getCXXScopeSpec().isInvalid()) 4028 D.setInvalidType(); 4029 else if (D.getCXXScopeSpec().isSet()) { 4030 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4031 UPPC_DeclarationQualifier)) 4032 return 0; 4033 4034 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4035 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4036 if (!DC) { 4037 // If we could not compute the declaration context, it's because the 4038 // declaration context is dependent but does not refer to a class, 4039 // class template, or class template partial specialization. Complain 4040 // and return early, to avoid the coming semantic disaster. 4041 Diag(D.getIdentifierLoc(), 4042 diag::err_template_qualified_declarator_no_match) 4043 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4044 << D.getCXXScopeSpec().getRange(); 4045 return 0; 4046 } 4047 bool IsDependentContext = DC->isDependentContext(); 4048 4049 if (!IsDependentContext && 4050 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4051 return 0; 4052 4053 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4054 Diag(D.getIdentifierLoc(), 4055 diag::err_member_def_undefined_record) 4056 << Name << DC << D.getCXXScopeSpec().getRange(); 4057 D.setInvalidType(); 4058 } else if (!D.getDeclSpec().isFriendSpecified()) { 4059 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4060 Name, D.getIdentifierLoc())) { 4061 if (DC->isRecord()) 4062 return 0; 4063 4064 D.setInvalidType(); 4065 } 4066 } 4067 4068 // Check whether we need to rebuild the type of the given 4069 // declaration in the current instantiation. 4070 if (EnteringContext && IsDependentContext && 4071 TemplateParamLists.size() != 0) { 4072 ContextRAII SavedContext(*this, DC); 4073 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4074 D.setInvalidType(); 4075 } 4076 } 4077 4078 if (DiagnoseClassNameShadow(DC, NameInfo)) 4079 // If this is a typedef, we'll end up spewing multiple diagnostics. 4080 // Just return early; it's safer. 4081 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4082 return 0; 4083 4084 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4085 QualType R = TInfo->getType(); 4086 4087 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4088 UPPC_DeclarationType)) 4089 D.setInvalidType(); 4090 4091 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4092 ForRedeclaration); 4093 4094 // See if this is a redefinition of a variable in the same scope. 4095 if (!D.getCXXScopeSpec().isSet()) { 4096 bool IsLinkageLookup = false; 4097 4098 // If the declaration we're planning to build will be a function 4099 // or object with linkage, then look for another declaration with 4100 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4102 /* Do nothing*/; 4103 else if (R->isFunctionType()) { 4104 if (CurContext->isFunctionOrMethod() || 4105 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4106 IsLinkageLookup = true; 4107 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 4108 IsLinkageLookup = true; 4109 else if (CurContext->getRedeclContext()->isTranslationUnit() && 4110 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4111 IsLinkageLookup = true; 4112 4113 if (IsLinkageLookup) 4114 Previous.clear(LookupRedeclarationWithLinkage); 4115 4116 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 4117 } else { // Something like "int foo::x;" 4118 LookupQualifiedName(Previous, DC); 4119 4120 // C++ [dcl.meaning]p1: 4121 // When the declarator-id is qualified, the declaration shall refer to a 4122 // previously declared member of the class or namespace to which the 4123 // qualifier refers (or, in the case of a namespace, of an element of the 4124 // inline namespace set of that namespace (7.3.1)) or to a specialization 4125 // thereof; [...] 4126 // 4127 // Note that we already checked the context above, and that we do not have 4128 // enough information to make sure that Previous contains the declaration 4129 // we want to match. For example, given: 4130 // 4131 // class X { 4132 // void f(); 4133 // void f(float); 4134 // }; 4135 // 4136 // void X::f(int) { } // ill-formed 4137 // 4138 // In this case, Previous will point to the overload set 4139 // containing the two f's declared in X, but neither of them 4140 // matches. 4141 4142 // C++ [dcl.meaning]p1: 4143 // [...] the member shall not merely have been introduced by a 4144 // using-declaration in the scope of the class or namespace nominated by 4145 // the nested-name-specifier of the declarator-id. 4146 RemoveUsingDecls(Previous); 4147 } 4148 4149 if (Previous.isSingleResult() && 4150 Previous.getFoundDecl()->isTemplateParameter()) { 4151 // Maybe we will complain about the shadowed template parameter. 4152 if (!D.isInvalidType()) 4153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4154 Previous.getFoundDecl()); 4155 4156 // Just pretend that we didn't see the previous declaration. 4157 Previous.clear(); 4158 } 4159 4160 // In C++, the previous declaration we find might be a tag type 4161 // (class or enum). In this case, the new declaration will hide the 4162 // tag type. Note that this does does not apply if we're declaring a 4163 // typedef (C++ [dcl.typedef]p4). 4164 if (Previous.isSingleTagDecl() && 4165 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4166 Previous.clear(); 4167 4168 // Check that there are no default arguments other than in the parameters 4169 // of a function declaration (C++ only). 4170 if (getLangOpts().CPlusPlus) 4171 CheckExtraCXXDefaultArguments(D); 4172 4173 NamedDecl *New; 4174 4175 bool AddToScope = true; 4176 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4177 if (TemplateParamLists.size()) { 4178 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4179 return 0; 4180 } 4181 4182 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4183 } else if (R->isFunctionType()) { 4184 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4185 TemplateParamLists, 4186 AddToScope); 4187 } else { 4188 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 4189 TemplateParamLists); 4190 } 4191 4192 if (New == 0) 4193 return 0; 4194 4195 // If this has an identifier and is not an invalid redeclaration or 4196 // function template specialization, add it to the scope stack. 4197 if (New->getDeclName() && AddToScope && 4198 !(D.isRedeclaration() && New->isInvalidDecl())) 4199 PushOnScopeChains(New, S); 4200 4201 return New; 4202} 4203 4204/// Helper method to turn variable array types into constant array 4205/// types in certain situations which would otherwise be errors (for 4206/// GCC compatibility). 4207static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4208 ASTContext &Context, 4209 bool &SizeIsNegative, 4210 llvm::APSInt &Oversized) { 4211 // This method tries to turn a variable array into a constant 4212 // array even when the size isn't an ICE. This is necessary 4213 // for compatibility with code that depends on gcc's buggy 4214 // constant expression folding, like struct {char x[(int)(char*)2];} 4215 SizeIsNegative = false; 4216 Oversized = 0; 4217 4218 if (T->isDependentType()) 4219 return QualType(); 4220 4221 QualifierCollector Qs; 4222 const Type *Ty = Qs.strip(T); 4223 4224 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4225 QualType Pointee = PTy->getPointeeType(); 4226 QualType FixedType = 4227 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4228 Oversized); 4229 if (FixedType.isNull()) return FixedType; 4230 FixedType = Context.getPointerType(FixedType); 4231 return Qs.apply(Context, FixedType); 4232 } 4233 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4234 QualType Inner = PTy->getInnerType(); 4235 QualType FixedType = 4236 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4237 Oversized); 4238 if (FixedType.isNull()) return FixedType; 4239 FixedType = Context.getParenType(FixedType); 4240 return Qs.apply(Context, FixedType); 4241 } 4242 4243 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4244 if (!VLATy) 4245 return QualType(); 4246 // FIXME: We should probably handle this case 4247 if (VLATy->getElementType()->isVariablyModifiedType()) 4248 return QualType(); 4249 4250 llvm::APSInt Res; 4251 if (!VLATy->getSizeExpr() || 4252 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4253 return QualType(); 4254 4255 // Check whether the array size is negative. 4256 if (Res.isSigned() && Res.isNegative()) { 4257 SizeIsNegative = true; 4258 return QualType(); 4259 } 4260 4261 // Check whether the array is too large to be addressed. 4262 unsigned ActiveSizeBits 4263 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4264 Res); 4265 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4266 Oversized = Res; 4267 return QualType(); 4268 } 4269 4270 return Context.getConstantArrayType(VLATy->getElementType(), 4271 Res, ArrayType::Normal, 0); 4272} 4273 4274static void 4275FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4276 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4277 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4278 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4279 DstPTL.getPointeeLoc()); 4280 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4281 return; 4282 } 4283 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4284 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4285 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4286 DstPTL.getInnerLoc()); 4287 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4288 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4289 return; 4290 } 4291 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4292 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4293 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4294 TypeLoc DstElemTL = DstATL.getElementLoc(); 4295 DstElemTL.initializeFullCopy(SrcElemTL); 4296 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4297 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4298 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4299} 4300 4301/// Helper method to turn variable array types into constant array 4302/// types in certain situations which would otherwise be errors (for 4303/// GCC compatibility). 4304static TypeSourceInfo* 4305TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4306 ASTContext &Context, 4307 bool &SizeIsNegative, 4308 llvm::APSInt &Oversized) { 4309 QualType FixedTy 4310 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4311 SizeIsNegative, Oversized); 4312 if (FixedTy.isNull()) 4313 return 0; 4314 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4315 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4316 FixedTInfo->getTypeLoc()); 4317 return FixedTInfo; 4318} 4319 4320/// \brief Register the given locally-scoped extern "C" declaration so 4321/// that it can be found later for redeclarations 4322void 4323Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 4324 const LookupResult &Previous, 4325 Scope *S) { 4326 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 4327 "Decl is not a locally-scoped decl!"); 4328 // Note that we have a locally-scoped external with this name. 4329 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4330 4331 if (!Previous.isSingleResult()) 4332 return; 4333 4334 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4335 4336 // If there was a previous declaration of this entity, it may be in 4337 // our identifier chain. Update the identifier chain with the new 4338 // declaration. 4339 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 4340 // The previous declaration was found on the identifer resolver 4341 // chain, so remove it from its scope. 4342 4343 if (S->isDeclScope(PrevDecl)) { 4344 // Special case for redeclarations in the SAME scope. 4345 // Because this declaration is going to be added to the identifier chain 4346 // later, we should temporarily take it OFF the chain. 4347 IdResolver.RemoveDecl(ND); 4348 4349 } else { 4350 // Find the scope for the original declaration. 4351 while (S && !S->isDeclScope(PrevDecl)) 4352 S = S->getParent(); 4353 } 4354 4355 if (S) 4356 S->RemoveDecl(PrevDecl); 4357 } 4358} 4359 4360llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 4361Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4362 if (ExternalSource) { 4363 // Load locally-scoped external decls from the external source. 4364 SmallVector<NamedDecl *, 4> Decls; 4365 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4366 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4367 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4368 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4369 if (Pos == LocallyScopedExternCDecls.end()) 4370 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4371 } 4372 } 4373 4374 return LocallyScopedExternCDecls.find(Name); 4375} 4376 4377/// \brief Diagnose function specifiers on a declaration of an identifier that 4378/// does not identify a function. 4379void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4380 // FIXME: We should probably indicate the identifier in question to avoid 4381 // confusion for constructs like "inline int a(), b;" 4382 if (DS.isInlineSpecified()) 4383 Diag(DS.getInlineSpecLoc(), 4384 diag::err_inline_non_function); 4385 4386 if (DS.isVirtualSpecified()) 4387 Diag(DS.getVirtualSpecLoc(), 4388 diag::err_virtual_non_function); 4389 4390 if (DS.isExplicitSpecified()) 4391 Diag(DS.getExplicitSpecLoc(), 4392 diag::err_explicit_non_function); 4393 4394 if (DS.isNoreturnSpecified()) 4395 Diag(DS.getNoreturnSpecLoc(), 4396 diag::err_noreturn_non_function); 4397} 4398 4399NamedDecl* 4400Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4401 TypeSourceInfo *TInfo, LookupResult &Previous) { 4402 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4403 if (D.getCXXScopeSpec().isSet()) { 4404 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4405 << D.getCXXScopeSpec().getRange(); 4406 D.setInvalidType(); 4407 // Pretend we didn't see the scope specifier. 4408 DC = CurContext; 4409 Previous.clear(); 4410 } 4411 4412 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4413 4414 if (D.getDeclSpec().isThreadSpecified()) 4415 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4416 if (D.getDeclSpec().isConstexprSpecified()) 4417 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4418 << 1; 4419 4420 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4421 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4422 << D.getName().getSourceRange(); 4423 return 0; 4424 } 4425 4426 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4427 if (!NewTD) return 0; 4428 4429 // Handle attributes prior to checking for duplicates in MergeVarDecl 4430 ProcessDeclAttributes(S, NewTD, D); 4431 4432 CheckTypedefForVariablyModifiedType(S, NewTD); 4433 4434 bool Redeclaration = D.isRedeclaration(); 4435 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4436 D.setRedeclaration(Redeclaration); 4437 return ND; 4438} 4439 4440void 4441Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4442 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4443 // then it shall have block scope. 4444 // Note that variably modified types must be fixed before merging the decl so 4445 // that redeclarations will match. 4446 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4447 QualType T = TInfo->getType(); 4448 if (T->isVariablyModifiedType()) { 4449 getCurFunction()->setHasBranchProtectedScope(); 4450 4451 if (S->getFnParent() == 0) { 4452 bool SizeIsNegative; 4453 llvm::APSInt Oversized; 4454 TypeSourceInfo *FixedTInfo = 4455 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4456 SizeIsNegative, 4457 Oversized); 4458 if (FixedTInfo) { 4459 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4460 NewTD->setTypeSourceInfo(FixedTInfo); 4461 } else { 4462 if (SizeIsNegative) 4463 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4464 else if (T->isVariableArrayType()) 4465 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4466 else if (Oversized.getBoolValue()) 4467 Diag(NewTD->getLocation(), diag::err_array_too_large) 4468 << Oversized.toString(10); 4469 else 4470 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4471 NewTD->setInvalidDecl(); 4472 } 4473 } 4474 } 4475} 4476 4477 4478/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4479/// declares a typedef-name, either using the 'typedef' type specifier or via 4480/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4481NamedDecl* 4482Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4483 LookupResult &Previous, bool &Redeclaration) { 4484 // Merge the decl with the existing one if appropriate. If the decl is 4485 // in an outer scope, it isn't the same thing. 4486 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4487 /*ExplicitInstantiationOrSpecialization=*/false); 4488 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4489 if (!Previous.empty()) { 4490 Redeclaration = true; 4491 MergeTypedefNameDecl(NewTD, Previous); 4492 } 4493 4494 // If this is the C FILE type, notify the AST context. 4495 if (IdentifierInfo *II = NewTD->getIdentifier()) 4496 if (!NewTD->isInvalidDecl() && 4497 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4498 if (II->isStr("FILE")) 4499 Context.setFILEDecl(NewTD); 4500 else if (II->isStr("jmp_buf")) 4501 Context.setjmp_bufDecl(NewTD); 4502 else if (II->isStr("sigjmp_buf")) 4503 Context.setsigjmp_bufDecl(NewTD); 4504 else if (II->isStr("ucontext_t")) 4505 Context.setucontext_tDecl(NewTD); 4506 } 4507 4508 return NewTD; 4509} 4510 4511/// \brief Determines whether the given declaration is an out-of-scope 4512/// previous declaration. 4513/// 4514/// This routine should be invoked when name lookup has found a 4515/// previous declaration (PrevDecl) that is not in the scope where a 4516/// new declaration by the same name is being introduced. If the new 4517/// declaration occurs in a local scope, previous declarations with 4518/// linkage may still be considered previous declarations (C99 4519/// 6.2.2p4-5, C++ [basic.link]p6). 4520/// 4521/// \param PrevDecl the previous declaration found by name 4522/// lookup 4523/// 4524/// \param DC the context in which the new declaration is being 4525/// declared. 4526/// 4527/// \returns true if PrevDecl is an out-of-scope previous declaration 4528/// for a new delcaration with the same name. 4529static bool 4530isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4531 ASTContext &Context) { 4532 if (!PrevDecl) 4533 return false; 4534 4535 if (!PrevDecl->hasLinkage()) 4536 return false; 4537 4538 if (Context.getLangOpts().CPlusPlus) { 4539 // C++ [basic.link]p6: 4540 // If there is a visible declaration of an entity with linkage 4541 // having the same name and type, ignoring entities declared 4542 // outside the innermost enclosing namespace scope, the block 4543 // scope declaration declares that same entity and receives the 4544 // linkage of the previous declaration. 4545 DeclContext *OuterContext = DC->getRedeclContext(); 4546 if (!OuterContext->isFunctionOrMethod()) 4547 // This rule only applies to block-scope declarations. 4548 return false; 4549 4550 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4551 if (PrevOuterContext->isRecord()) 4552 // We found a member function: ignore it. 4553 return false; 4554 4555 // Find the innermost enclosing namespace for the new and 4556 // previous declarations. 4557 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4558 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4559 4560 // The previous declaration is in a different namespace, so it 4561 // isn't the same function. 4562 if (!OuterContext->Equals(PrevOuterContext)) 4563 return false; 4564 } 4565 4566 return true; 4567} 4568 4569static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4570 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4571 if (!SS.isSet()) return; 4572 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4573} 4574 4575bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4576 QualType type = decl->getType(); 4577 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4578 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4579 // Various kinds of declaration aren't allowed to be __autoreleasing. 4580 unsigned kind = -1U; 4581 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4582 if (var->hasAttr<BlocksAttr>()) 4583 kind = 0; // __block 4584 else if (!var->hasLocalStorage()) 4585 kind = 1; // global 4586 } else if (isa<ObjCIvarDecl>(decl)) { 4587 kind = 3; // ivar 4588 } else if (isa<FieldDecl>(decl)) { 4589 kind = 2; // field 4590 } 4591 4592 if (kind != -1U) { 4593 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4594 << kind; 4595 } 4596 } else if (lifetime == Qualifiers::OCL_None) { 4597 // Try to infer lifetime. 4598 if (!type->isObjCLifetimeType()) 4599 return false; 4600 4601 lifetime = type->getObjCARCImplicitLifetime(); 4602 type = Context.getLifetimeQualifiedType(type, lifetime); 4603 decl->setType(type); 4604 } 4605 4606 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4607 // Thread-local variables cannot have lifetime. 4608 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4609 var->isThreadSpecified()) { 4610 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4611 << var->getType(); 4612 return true; 4613 } 4614 } 4615 4616 return false; 4617} 4618 4619static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4620 // 'weak' only applies to declarations with external linkage. 4621 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4622 if (ND.getLinkage() != ExternalLinkage) { 4623 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4624 ND.dropAttr<WeakAttr>(); 4625 } 4626 } 4627 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4628 if (ND.hasExternalLinkage()) { 4629 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4630 ND.dropAttr<WeakRefAttr>(); 4631 } 4632 } 4633} 4634 4635static bool shouldConsiderLinkage(const VarDecl *VD) { 4636 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4637 if (DC->isFunctionOrMethod()) 4638 return VD->hasExternalStorageAsWritten(); 4639 if (DC->isFileContext()) 4640 return true; 4641 if (DC->isRecord()) 4642 return false; 4643 llvm_unreachable("Unexpected context"); 4644} 4645 4646static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4647 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4648 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4649 return true; 4650 if (DC->isRecord()) 4651 return false; 4652 llvm_unreachable("Unexpected context"); 4653} 4654 4655NamedDecl* 4656Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4657 TypeSourceInfo *TInfo, LookupResult &Previous, 4658 MultiTemplateParamsArg TemplateParamLists) { 4659 QualType R = TInfo->getType(); 4660 DeclarationName Name = GetNameForDeclarator(D).getName(); 4661 4662 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4663 assert(SCSpec != DeclSpec::SCS_typedef && 4664 "Parser allowed 'typedef' as storage class VarDecl."); 4665 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4666 4667 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) 4668 { 4669 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4670 // half array type (unless the cl_khr_fp16 extension is enabled). 4671 if (Context.getBaseElementType(R)->isHalfType()) { 4672 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4673 D.setInvalidType(); 4674 } 4675 } 4676 4677 if (SCSpec == DeclSpec::SCS_mutable) { 4678 // mutable can only appear on non-static class members, so it's always 4679 // an error here 4680 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4681 D.setInvalidType(); 4682 SC = SC_None; 4683 } 4684 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4685 VarDecl::StorageClass SCAsWritten 4686 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4687 4688 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4689 if (!II) { 4690 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4691 << Name; 4692 return 0; 4693 } 4694 4695 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4696 4697 if (!DC->isRecord() && S->getFnParent() == 0) { 4698 // C99 6.9p2: The storage-class specifiers auto and register shall not 4699 // appear in the declaration specifiers in an external declaration. 4700 if (SC == SC_Auto || SC == SC_Register) { 4701 4702 // If this is a register variable with an asm label specified, then this 4703 // is a GNU extension. 4704 if (SC == SC_Register && D.getAsmLabel()) 4705 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4706 else 4707 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4708 D.setInvalidType(); 4709 } 4710 } 4711 4712 if (getLangOpts().OpenCL) { 4713 // Set up the special work-group-local storage class for variables in the 4714 // OpenCL __local address space. 4715 if (R.getAddressSpace() == LangAS::opencl_local) { 4716 SC = SC_OpenCLWorkGroupLocal; 4717 SCAsWritten = SC_OpenCLWorkGroupLocal; 4718 } 4719 4720 // OpenCL v1.2 s6.9.b p4: 4721 // The sampler type cannot be used with the __local and __global address 4722 // space qualifiers. 4723 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 4724 R.getAddressSpace() == LangAS::opencl_global)) { 4725 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 4726 } 4727 4728 // OpenCL 1.2 spec, p6.9 r: 4729 // The event type cannot be used to declare a program scope variable. 4730 // The event type cannot be used with the __local, __constant and __global 4731 // address space qualifiers. 4732 if (R->isEventT()) { 4733 if (S->getParent() == 0) { 4734 Diag(D.getLocStart(), diag::err_event_t_global_var); 4735 D.setInvalidType(); 4736 } 4737 4738 if (R.getAddressSpace()) { 4739 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 4740 D.setInvalidType(); 4741 } 4742 } 4743 } 4744 4745 bool isExplicitSpecialization = false; 4746 VarDecl *NewVD; 4747 if (!getLangOpts().CPlusPlus) { 4748 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4749 D.getIdentifierLoc(), II, 4750 R, TInfo, SC, SCAsWritten); 4751 4752 if (D.isInvalidType()) 4753 NewVD->setInvalidDecl(); 4754 } else { 4755 if (DC->isRecord() && !CurContext->isRecord()) { 4756 // This is an out-of-line definition of a static data member. 4757 if (SC == SC_Static) { 4758 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4759 diag::err_static_out_of_line) 4760 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4761 } else if (SC == SC_None) 4762 SC = SC_Static; 4763 } 4764 if (SC == SC_Static && CurContext->isRecord()) { 4765 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4766 if (RD->isLocalClass()) 4767 Diag(D.getIdentifierLoc(), 4768 diag::err_static_data_member_not_allowed_in_local_class) 4769 << Name << RD->getDeclName(); 4770 4771 // C++98 [class.union]p1: If a union contains a static data member, 4772 // the program is ill-formed. C++11 drops this restriction. 4773 if (RD->isUnion()) 4774 Diag(D.getIdentifierLoc(), 4775 getLangOpts().CPlusPlus11 4776 ? diag::warn_cxx98_compat_static_data_member_in_union 4777 : diag::ext_static_data_member_in_union) << Name; 4778 // We conservatively disallow static data members in anonymous structs. 4779 else if (!RD->getDeclName()) 4780 Diag(D.getIdentifierLoc(), 4781 diag::err_static_data_member_not_allowed_in_anon_struct) 4782 << Name << RD->isUnion(); 4783 } 4784 } 4785 4786 // Match up the template parameter lists with the scope specifier, then 4787 // determine whether we have a template or a template specialization. 4788 isExplicitSpecialization = false; 4789 bool Invalid = false; 4790 if (TemplateParameterList *TemplateParams 4791 = MatchTemplateParametersToScopeSpecifier( 4792 D.getDeclSpec().getLocStart(), 4793 D.getIdentifierLoc(), 4794 D.getCXXScopeSpec(), 4795 TemplateParamLists.data(), 4796 TemplateParamLists.size(), 4797 /*never a friend*/ false, 4798 isExplicitSpecialization, 4799 Invalid)) { 4800 if (TemplateParams->size() > 0) { 4801 // There is no such thing as a variable template. 4802 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4803 << II 4804 << SourceRange(TemplateParams->getTemplateLoc(), 4805 TemplateParams->getRAngleLoc()); 4806 return 0; 4807 } else { 4808 // There is an extraneous 'template<>' for this variable. Complain 4809 // about it, but allow the declaration of the variable. 4810 Diag(TemplateParams->getTemplateLoc(), 4811 diag::err_template_variable_noparams) 4812 << II 4813 << SourceRange(TemplateParams->getTemplateLoc(), 4814 TemplateParams->getRAngleLoc()); 4815 } 4816 } 4817 4818 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4819 D.getIdentifierLoc(), II, 4820 R, TInfo, SC, SCAsWritten); 4821 4822 // If this decl has an auto type in need of deduction, make a note of the 4823 // Decl so we can diagnose uses of it in its own initializer. 4824 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4825 R->getContainedAutoType()) 4826 ParsingInitForAutoVars.insert(NewVD); 4827 4828 if (D.isInvalidType() || Invalid) 4829 NewVD->setInvalidDecl(); 4830 4831 SetNestedNameSpecifier(NewVD, D); 4832 4833 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4834 NewVD->setTemplateParameterListsInfo(Context, 4835 TemplateParamLists.size(), 4836 TemplateParamLists.data()); 4837 } 4838 4839 if (D.getDeclSpec().isConstexprSpecified()) 4840 NewVD->setConstexpr(true); 4841 } 4842 4843 // Set the lexical context. If the declarator has a C++ scope specifier, the 4844 // lexical context will be different from the semantic context. 4845 NewVD->setLexicalDeclContext(CurContext); 4846 4847 if (D.getDeclSpec().isThreadSpecified()) { 4848 if (NewVD->hasLocalStorage()) 4849 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4850 else if (!Context.getTargetInfo().isTLSSupported()) 4851 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4852 else 4853 NewVD->setThreadSpecified(true); 4854 } 4855 4856 if (D.getDeclSpec().isModulePrivateSpecified()) { 4857 if (isExplicitSpecialization) 4858 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4859 << 2 4860 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4861 else if (NewVD->hasLocalStorage()) 4862 Diag(NewVD->getLocation(), diag::err_module_private_local) 4863 << 0 << NewVD->getDeclName() 4864 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4865 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4866 else 4867 NewVD->setModulePrivate(); 4868 } 4869 4870 // Handle attributes prior to checking for duplicates in MergeVarDecl 4871 ProcessDeclAttributes(S, NewVD, D); 4872 4873 if (NewVD->hasAttrs()) 4874 CheckAlignasUnderalignment(NewVD); 4875 4876 if (getLangOpts().CUDA) { 4877 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4878 // storage [duration]." 4879 if (SC == SC_None && S->getFnParent() != 0 && 4880 (NewVD->hasAttr<CUDASharedAttr>() || 4881 NewVD->hasAttr<CUDAConstantAttr>())) { 4882 NewVD->setStorageClass(SC_Static); 4883 NewVD->setStorageClassAsWritten(SC_Static); 4884 } 4885 } 4886 4887 // In auto-retain/release, infer strong retension for variables of 4888 // retainable type. 4889 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4890 NewVD->setInvalidDecl(); 4891 4892 // Handle GNU asm-label extension (encoded as an attribute). 4893 if (Expr *E = (Expr*)D.getAsmLabel()) { 4894 // The parser guarantees this is a string. 4895 StringLiteral *SE = cast<StringLiteral>(E); 4896 StringRef Label = SE->getString(); 4897 if (S->getFnParent() != 0) { 4898 switch (SC) { 4899 case SC_None: 4900 case SC_Auto: 4901 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4902 break; 4903 case SC_Register: 4904 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4905 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4906 break; 4907 case SC_Static: 4908 case SC_Extern: 4909 case SC_PrivateExtern: 4910 case SC_OpenCLWorkGroupLocal: 4911 break; 4912 } 4913 } 4914 4915 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4916 Context, Label)); 4917 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4918 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4919 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4920 if (I != ExtnameUndeclaredIdentifiers.end()) { 4921 NewVD->addAttr(I->second); 4922 ExtnameUndeclaredIdentifiers.erase(I); 4923 } 4924 } 4925 4926 // Diagnose shadowed variables before filtering for scope. 4927 if (!D.getCXXScopeSpec().isSet()) 4928 CheckShadow(S, NewVD, Previous); 4929 4930 // Don't consider existing declarations that are in a different 4931 // scope and are out-of-semantic-context declarations (if the new 4932 // declaration has linkage). 4933 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewVD), 4934 isExplicitSpecialization); 4935 4936 if (!getLangOpts().CPlusPlus) { 4937 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4938 } else { 4939 // Merge the decl with the existing one if appropriate. 4940 if (!Previous.empty()) { 4941 if (Previous.isSingleResult() && 4942 isa<FieldDecl>(Previous.getFoundDecl()) && 4943 D.getCXXScopeSpec().isSet()) { 4944 // The user tried to define a non-static data member 4945 // out-of-line (C++ [dcl.meaning]p1). 4946 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4947 << D.getCXXScopeSpec().getRange(); 4948 Previous.clear(); 4949 NewVD->setInvalidDecl(); 4950 } 4951 } else if (D.getCXXScopeSpec().isSet()) { 4952 // No previous declaration in the qualifying scope. 4953 Diag(D.getIdentifierLoc(), diag::err_no_member) 4954 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4955 << D.getCXXScopeSpec().getRange(); 4956 NewVD->setInvalidDecl(); 4957 } 4958 4959 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4960 4961 // This is an explicit specialization of a static data member. Check it. 4962 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4963 CheckMemberSpecialization(NewVD, Previous)) 4964 NewVD->setInvalidDecl(); 4965 } 4966 4967 ProcessPragmaWeak(S, NewVD); 4968 checkAttributesAfterMerging(*this, *NewVD); 4969 4970 // If this is a locally-scoped extern C variable, update the map of 4971 // such variables. 4972 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4973 !NewVD->isInvalidDecl()) 4974 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4975 4976 return NewVD; 4977} 4978 4979/// \brief Diagnose variable or built-in function shadowing. Implements 4980/// -Wshadow. 4981/// 4982/// This method is called whenever a VarDecl is added to a "useful" 4983/// scope. 4984/// 4985/// \param S the scope in which the shadowing name is being declared 4986/// \param R the lookup of the name 4987/// 4988void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4989 // Return if warning is ignored. 4990 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4991 DiagnosticsEngine::Ignored) 4992 return; 4993 4994 // Don't diagnose declarations at file scope. 4995 if (D->hasGlobalStorage()) 4996 return; 4997 4998 DeclContext *NewDC = D->getDeclContext(); 4999 5000 // Only diagnose if we're shadowing an unambiguous field or variable. 5001 if (R.getResultKind() != LookupResult::Found) 5002 return; 5003 5004 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5005 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5006 return; 5007 5008 // Fields are not shadowed by variables in C++ static methods. 5009 if (isa<FieldDecl>(ShadowedDecl)) 5010 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5011 if (MD->isStatic()) 5012 return; 5013 5014 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5015 if (shadowedVar->isExternC()) { 5016 // For shadowing external vars, make sure that we point to the global 5017 // declaration, not a locally scoped extern declaration. 5018 for (VarDecl::redecl_iterator 5019 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5020 I != E; ++I) 5021 if (I->isFileVarDecl()) { 5022 ShadowedDecl = *I; 5023 break; 5024 } 5025 } 5026 5027 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5028 5029 // Only warn about certain kinds of shadowing for class members. 5030 if (NewDC && NewDC->isRecord()) { 5031 // In particular, don't warn about shadowing non-class members. 5032 if (!OldDC->isRecord()) 5033 return; 5034 5035 // TODO: should we warn about static data members shadowing 5036 // static data members from base classes? 5037 5038 // TODO: don't diagnose for inaccessible shadowed members. 5039 // This is hard to do perfectly because we might friend the 5040 // shadowing context, but that's just a false negative. 5041 } 5042 5043 // Determine what kind of declaration we're shadowing. 5044 unsigned Kind; 5045 if (isa<RecordDecl>(OldDC)) { 5046 if (isa<FieldDecl>(ShadowedDecl)) 5047 Kind = 3; // field 5048 else 5049 Kind = 2; // static data member 5050 } else if (OldDC->isFileContext()) 5051 Kind = 1; // global 5052 else 5053 Kind = 0; // local 5054 5055 DeclarationName Name = R.getLookupName(); 5056 5057 // Emit warning and note. 5058 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5059 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5060} 5061 5062/// \brief Check -Wshadow without the advantage of a previous lookup. 5063void Sema::CheckShadow(Scope *S, VarDecl *D) { 5064 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5065 DiagnosticsEngine::Ignored) 5066 return; 5067 5068 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5069 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5070 LookupName(R, S); 5071 CheckShadow(S, D, R); 5072} 5073 5074template<typename T> 5075static bool mayConflictWithNonVisibleExternC(const T *ND) { 5076 const DeclContext *DC = ND->getDeclContext(); 5077 if (DC->getRedeclContext()->isTranslationUnit()) 5078 return true; 5079 5080 // We know that is the first decl we see, other than function local 5081 // extern C ones. If this is C++ and the decl is not in a extern C context 5082 // it cannot have C language linkage. Avoid calling isExternC in that case. 5083 // We need to this because of code like 5084 // 5085 // namespace { struct bar {}; } 5086 // auto foo = bar(); 5087 // 5088 // This code runs before the init of foo is set, and therefore before 5089 // the type of foo is known. Not knowing the type we cannot know its linkage 5090 // unless it is in an extern C block. 5091 if (!DC->isExternCContext()) { 5092 const ASTContext &Context = ND->getASTContext(); 5093 if (Context.getLangOpts().CPlusPlus) 5094 return false; 5095 } 5096 5097 return ND->isExternC(); 5098} 5099 5100/// \brief Perform semantic checking on a newly-created variable 5101/// declaration. 5102/// 5103/// This routine performs all of the type-checking required for a 5104/// variable declaration once it has been built. It is used both to 5105/// check variables after they have been parsed and their declarators 5106/// have been translated into a declaration, and to check variables 5107/// that have been instantiated from a template. 5108/// 5109/// Sets NewVD->isInvalidDecl() if an error was encountered. 5110/// 5111/// Returns true if the variable declaration is a redeclaration. 5112bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 5113 LookupResult &Previous) { 5114 // If the decl is already known invalid, don't check it. 5115 if (NewVD->isInvalidDecl()) 5116 return false; 5117 5118 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5119 QualType T = TInfo->getType(); 5120 5121 if (T->isObjCObjectType()) { 5122 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5123 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5124 T = Context.getObjCObjectPointerType(T); 5125 NewVD->setType(T); 5126 } 5127 5128 // Emit an error if an address space was applied to decl with local storage. 5129 // This includes arrays of objects with address space qualifiers, but not 5130 // automatic variables that point to other address spaces. 5131 // ISO/IEC TR 18037 S5.1.2 5132 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5133 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5134 NewVD->setInvalidDecl(); 5135 return false; 5136 } 5137 5138 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5139 // scope. 5140 if ((getLangOpts().OpenCLVersion >= 120) 5141 && NewVD->isStaticLocal()) { 5142 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5143 NewVD->setInvalidDecl(); 5144 return false; 5145 } 5146 5147 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5148 && !NewVD->hasAttr<BlocksAttr>()) { 5149 if (getLangOpts().getGC() != LangOptions::NonGC) 5150 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5151 else { 5152 assert(!getLangOpts().ObjCAutoRefCount); 5153 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5154 } 5155 } 5156 5157 bool isVM = T->isVariablyModifiedType(); 5158 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5159 NewVD->hasAttr<BlocksAttr>()) 5160 getCurFunction()->setHasBranchProtectedScope(); 5161 5162 if ((isVM && NewVD->hasLinkage()) || 5163 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5164 bool SizeIsNegative; 5165 llvm::APSInt Oversized; 5166 TypeSourceInfo *FixedTInfo = 5167 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5168 SizeIsNegative, Oversized); 5169 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5170 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5171 // FIXME: This won't give the correct result for 5172 // int a[10][n]; 5173 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5174 5175 if (NewVD->isFileVarDecl()) 5176 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5177 << SizeRange; 5178 else if (NewVD->getStorageClass() == SC_Static) 5179 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5180 << SizeRange; 5181 else 5182 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5183 << SizeRange; 5184 NewVD->setInvalidDecl(); 5185 return false; 5186 } 5187 5188 if (FixedTInfo == 0) { 5189 if (NewVD->isFileVarDecl()) 5190 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5191 else 5192 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5193 NewVD->setInvalidDecl(); 5194 return false; 5195 } 5196 5197 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5198 NewVD->setType(FixedTInfo->getType()); 5199 NewVD->setTypeSourceInfo(FixedTInfo); 5200 } 5201 5202 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) { 5203 // Since we did not find anything by this name, look for a non-visible 5204 // extern "C" declaration with the same name. 5205 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5206 = findLocallyScopedExternCDecl(NewVD->getDeclName()); 5207 if (Pos != LocallyScopedExternCDecls.end()) 5208 Previous.addDecl(Pos->second); 5209 } 5210 5211 // Filter out any non-conflicting previous declarations. 5212 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5213 5214 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 5215 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5216 << T; 5217 NewVD->setInvalidDecl(); 5218 return false; 5219 } 5220 5221 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5222 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5223 NewVD->setInvalidDecl(); 5224 return false; 5225 } 5226 5227 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5228 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5229 NewVD->setInvalidDecl(); 5230 return false; 5231 } 5232 5233 if (NewVD->isConstexpr() && !T->isDependentType() && 5234 RequireLiteralType(NewVD->getLocation(), T, 5235 diag::err_constexpr_var_non_literal)) { 5236 NewVD->setInvalidDecl(); 5237 return false; 5238 } 5239 5240 if (!Previous.empty()) { 5241 MergeVarDecl(NewVD, Previous); 5242 return true; 5243 } 5244 return false; 5245} 5246 5247/// \brief Data used with FindOverriddenMethod 5248struct FindOverriddenMethodData { 5249 Sema *S; 5250 CXXMethodDecl *Method; 5251}; 5252 5253/// \brief Member lookup function that determines whether a given C++ 5254/// method overrides a method in a base class, to be used with 5255/// CXXRecordDecl::lookupInBases(). 5256static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5257 CXXBasePath &Path, 5258 void *UserData) { 5259 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5260 5261 FindOverriddenMethodData *Data 5262 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5263 5264 DeclarationName Name = Data->Method->getDeclName(); 5265 5266 // FIXME: Do we care about other names here too? 5267 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5268 // We really want to find the base class destructor here. 5269 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5270 CanQualType CT = Data->S->Context.getCanonicalType(T); 5271 5272 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5273 } 5274 5275 for (Path.Decls = BaseRecord->lookup(Name); 5276 !Path.Decls.empty(); 5277 Path.Decls = Path.Decls.slice(1)) { 5278 NamedDecl *D = Path.Decls.front(); 5279 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5280 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5281 return true; 5282 } 5283 } 5284 5285 return false; 5286} 5287 5288namespace { 5289 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5290} 5291/// \brief Report an error regarding overriding, along with any relevant 5292/// overriden methods. 5293/// 5294/// \param DiagID the primary error to report. 5295/// \param MD the overriding method. 5296/// \param OEK which overrides to include as notes. 5297static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5298 OverrideErrorKind OEK = OEK_All) { 5299 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5300 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5301 E = MD->end_overridden_methods(); 5302 I != E; ++I) { 5303 // This check (& the OEK parameter) could be replaced by a predicate, but 5304 // without lambdas that would be overkill. This is still nicer than writing 5305 // out the diag loop 3 times. 5306 if ((OEK == OEK_All) || 5307 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5308 (OEK == OEK_Deleted && (*I)->isDeleted())) 5309 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5310 } 5311} 5312 5313/// AddOverriddenMethods - See if a method overrides any in the base classes, 5314/// and if so, check that it's a valid override and remember it. 5315bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5316 // Look for virtual methods in base classes that this method might override. 5317 CXXBasePaths Paths; 5318 FindOverriddenMethodData Data; 5319 Data.Method = MD; 5320 Data.S = this; 5321 bool hasDeletedOverridenMethods = false; 5322 bool hasNonDeletedOverridenMethods = false; 5323 bool AddedAny = false; 5324 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5325 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5326 E = Paths.found_decls_end(); I != E; ++I) { 5327 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5328 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5329 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5330 !CheckOverridingFunctionAttributes(MD, OldMD) && 5331 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5332 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5333 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5334 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5335 AddedAny = true; 5336 } 5337 } 5338 } 5339 } 5340 5341 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5342 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5343 } 5344 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5345 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5346 } 5347 5348 return AddedAny; 5349} 5350 5351namespace { 5352 // Struct for holding all of the extra arguments needed by 5353 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5354 struct ActOnFDArgs { 5355 Scope *S; 5356 Declarator &D; 5357 MultiTemplateParamsArg TemplateParamLists; 5358 bool AddToScope; 5359 }; 5360} 5361 5362namespace { 5363 5364// Callback to only accept typo corrections that have a non-zero edit distance. 5365// Also only accept corrections that have the same parent decl. 5366class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5367 public: 5368 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5369 CXXRecordDecl *Parent) 5370 : Context(Context), OriginalFD(TypoFD), 5371 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5372 5373 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5374 if (candidate.getEditDistance() == 0) 5375 return false; 5376 5377 SmallVector<unsigned, 1> MismatchedParams; 5378 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5379 CDeclEnd = candidate.end(); 5380 CDecl != CDeclEnd; ++CDecl) { 5381 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5382 5383 if (FD && !FD->hasBody() && 5384 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 5385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5386 CXXRecordDecl *Parent = MD->getParent(); 5387 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 5388 return true; 5389 } else if (!ExpectedParent) { 5390 return true; 5391 } 5392 } 5393 } 5394 5395 return false; 5396 } 5397 5398 private: 5399 ASTContext &Context; 5400 FunctionDecl *OriginalFD; 5401 CXXRecordDecl *ExpectedParent; 5402}; 5403 5404} 5405 5406/// \brief Generate diagnostics for an invalid function redeclaration. 5407/// 5408/// This routine handles generating the diagnostic messages for an invalid 5409/// function redeclaration, including finding possible similar declarations 5410/// or performing typo correction if there are no previous declarations with 5411/// the same name. 5412/// 5413/// Returns a NamedDecl iff typo correction was performed and substituting in 5414/// the new declaration name does not cause new errors. 5415static NamedDecl* DiagnoseInvalidRedeclaration( 5416 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 5417 ActOnFDArgs &ExtraArgs) { 5418 NamedDecl *Result = NULL; 5419 DeclarationName Name = NewFD->getDeclName(); 5420 DeclContext *NewDC = NewFD->getDeclContext(); 5421 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 5422 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5423 SmallVector<unsigned, 1> MismatchedParams; 5424 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 5425 TypoCorrection Correction; 5426 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 5427 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 5428 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 5429 : diag::err_member_def_does_not_match; 5430 5431 NewFD->setInvalidDecl(); 5432 SemaRef.LookupQualifiedName(Prev, NewDC); 5433 assert(!Prev.isAmbiguous() && 5434 "Cannot have an ambiguity in previous-declaration lookup"); 5435 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5436 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 5437 MD ? MD->getParent() : 0); 5438 if (!Prev.empty()) { 5439 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 5440 Func != FuncEnd; ++Func) { 5441 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 5442 if (FD && 5443 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5444 // Add 1 to the index so that 0 can mean the mismatch didn't 5445 // involve a parameter 5446 unsigned ParamNum = 5447 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 5448 NearMatches.push_back(std::make_pair(FD, ParamNum)); 5449 } 5450 } 5451 // If the qualified name lookup yielded nothing, try typo correction 5452 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 5453 Prev.getLookupKind(), 0, 0, 5454 Validator, NewDC))) { 5455 // Trap errors. 5456 Sema::SFINAETrap Trap(SemaRef); 5457 5458 // Set up everything for the call to ActOnFunctionDeclarator 5459 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 5460 ExtraArgs.D.getIdentifierLoc()); 5461 Previous.clear(); 5462 Previous.setLookupName(Correction.getCorrection()); 5463 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 5464 CDeclEnd = Correction.end(); 5465 CDecl != CDeclEnd; ++CDecl) { 5466 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5467 if (FD && !FD->hasBody() && 5468 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5469 Previous.addDecl(FD); 5470 } 5471 } 5472 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 5473 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 5474 // pieces need to verify the typo-corrected C++ declaraction and hopefully 5475 // eliminate the need for the parameter pack ExtraArgs. 5476 Result = SemaRef.ActOnFunctionDeclarator( 5477 ExtraArgs.S, ExtraArgs.D, 5478 Correction.getCorrectionDecl()->getDeclContext(), 5479 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 5480 ExtraArgs.AddToScope); 5481 if (Trap.hasErrorOccurred()) { 5482 // Pretend the typo correction never occurred 5483 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 5484 ExtraArgs.D.getIdentifierLoc()); 5485 ExtraArgs.D.setRedeclaration(wasRedeclaration); 5486 Previous.clear(); 5487 Previous.setLookupName(Name); 5488 Result = NULL; 5489 } else { 5490 for (LookupResult::iterator Func = Previous.begin(), 5491 FuncEnd = Previous.end(); 5492 Func != FuncEnd; ++Func) { 5493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 5494 NearMatches.push_back(std::make_pair(FD, 0)); 5495 } 5496 } 5497 if (NearMatches.empty()) { 5498 // Ignore the correction if it didn't yield any close FunctionDecl matches 5499 Correction = TypoCorrection(); 5500 } else { 5501 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 5502 : diag::err_member_def_does_not_match_suggest; 5503 } 5504 } 5505 5506 if (Correction) { 5507 // FIXME: use Correction.getCorrectionRange() instead of computing the range 5508 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in 5509 // turn causes the correction to fully qualify the name. If we fix 5510 // CorrectTypo to minimally qualify then this change should be good. 5511 SourceRange FixItLoc(NewFD->getLocation()); 5512 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 5513 if (Correction.getCorrectionSpecifier() && SS.isValid()) 5514 FixItLoc.setBegin(SS.getBeginLoc()); 5515 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 5516 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 5517 << FixItHint::CreateReplacement( 5518 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 5519 } else { 5520 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 5521 << Name << NewDC << NewFD->getLocation(); 5522 } 5523 5524 bool NewFDisConst = false; 5525 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 5526 NewFDisConst = NewMD->isConst(); 5527 5528 for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator 5529 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 5530 NearMatch != NearMatchEnd; ++NearMatch) { 5531 FunctionDecl *FD = NearMatch->first; 5532 bool FDisConst = false; 5533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 5534 FDisConst = MD->isConst(); 5535 5536 if (unsigned Idx = NearMatch->second) { 5537 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 5538 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 5539 if (Loc.isInvalid()) Loc = FD->getLocation(); 5540 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 5541 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 5542 } else if (Correction) { 5543 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 5544 << Correction.getQuoted(SemaRef.getLangOpts()); 5545 } else if (FDisConst != NewFDisConst) { 5546 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 5547 << NewFDisConst << FD->getSourceRange().getEnd(); 5548 } else 5549 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 5550 } 5551 return Result; 5552} 5553 5554static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 5555 Declarator &D) { 5556 switch (D.getDeclSpec().getStorageClassSpec()) { 5557 default: llvm_unreachable("Unknown storage class!"); 5558 case DeclSpec::SCS_auto: 5559 case DeclSpec::SCS_register: 5560 case DeclSpec::SCS_mutable: 5561 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5562 diag::err_typecheck_sclass_func); 5563 D.setInvalidType(); 5564 break; 5565 case DeclSpec::SCS_unspecified: break; 5566 case DeclSpec::SCS_extern: return SC_Extern; 5567 case DeclSpec::SCS_static: { 5568 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 5569 // C99 6.7.1p5: 5570 // The declaration of an identifier for a function that has 5571 // block scope shall have no explicit storage-class specifier 5572 // other than extern 5573 // See also (C++ [dcl.stc]p4). 5574 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5575 diag::err_static_block_func); 5576 break; 5577 } else 5578 return SC_Static; 5579 } 5580 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5581 } 5582 5583 // No explicit storage class has already been returned 5584 return SC_None; 5585} 5586 5587static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 5588 DeclContext *DC, QualType &R, 5589 TypeSourceInfo *TInfo, 5590 FunctionDecl::StorageClass SC, 5591 bool &IsVirtualOkay) { 5592 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 5593 DeclarationName Name = NameInfo.getName(); 5594 5595 FunctionDecl *NewFD = 0; 5596 bool isInline = D.getDeclSpec().isInlineSpecified(); 5597 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 5598 FunctionDecl::StorageClass SCAsWritten 5599 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 5600 5601 if (!SemaRef.getLangOpts().CPlusPlus) { 5602 // Determine whether the function was written with a 5603 // prototype. This true when: 5604 // - there is a prototype in the declarator, or 5605 // - the type R of the function is some kind of typedef or other reference 5606 // to a type name (which eventually refers to a function type). 5607 bool HasPrototype = 5608 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 5609 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 5610 5611 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 5612 D.getLocStart(), NameInfo, R, 5613 TInfo, SC, SCAsWritten, isInline, 5614 HasPrototype); 5615 if (D.isInvalidType()) 5616 NewFD->setInvalidDecl(); 5617 5618 // Set the lexical context. 5619 NewFD->setLexicalDeclContext(SemaRef.CurContext); 5620 5621 return NewFD; 5622 } 5623 5624 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5625 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5626 5627 // Check that the return type is not an abstract class type. 5628 // For record types, this is done by the AbstractClassUsageDiagnoser once 5629 // the class has been completely parsed. 5630 if (!DC->isRecord() && 5631 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 5632 R->getAs<FunctionType>()->getResultType(), 5633 diag::err_abstract_type_in_decl, 5634 SemaRef.AbstractReturnType)) 5635 D.setInvalidType(); 5636 5637 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 5638 // This is a C++ constructor declaration. 5639 assert(DC->isRecord() && 5640 "Constructors can only be declared in a member context"); 5641 5642 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 5643 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5644 D.getLocStart(), NameInfo, 5645 R, TInfo, isExplicit, isInline, 5646 /*isImplicitlyDeclared=*/false, 5647 isConstexpr); 5648 5649 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5650 // This is a C++ destructor declaration. 5651 if (DC->isRecord()) { 5652 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 5653 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 5654 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 5655 SemaRef.Context, Record, 5656 D.getLocStart(), 5657 NameInfo, R, TInfo, isInline, 5658 /*isImplicitlyDeclared=*/false); 5659 5660 // If the class is complete, then we now create the implicit exception 5661 // specification. If the class is incomplete or dependent, we can't do 5662 // it yet. 5663 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 5664 Record->getDefinition() && !Record->isBeingDefined() && 5665 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5666 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5667 } 5668 5669 IsVirtualOkay = true; 5670 return NewDD; 5671 5672 } else { 5673 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5674 D.setInvalidType(); 5675 5676 // Create a FunctionDecl to satisfy the function definition parsing 5677 // code path. 5678 return FunctionDecl::Create(SemaRef.Context, DC, 5679 D.getLocStart(), 5680 D.getIdentifierLoc(), Name, R, TInfo, 5681 SC, SCAsWritten, isInline, 5682 /*hasPrototype=*/true, isConstexpr); 5683 } 5684 5685 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5686 if (!DC->isRecord()) { 5687 SemaRef.Diag(D.getIdentifierLoc(), 5688 diag::err_conv_function_not_member); 5689 return 0; 5690 } 5691 5692 SemaRef.CheckConversionDeclarator(D, R, SC); 5693 IsVirtualOkay = true; 5694 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5695 D.getLocStart(), NameInfo, 5696 R, TInfo, isInline, isExplicit, 5697 isConstexpr, SourceLocation()); 5698 5699 } else if (DC->isRecord()) { 5700 // If the name of the function is the same as the name of the record, 5701 // then this must be an invalid constructor that has a return type. 5702 // (The parser checks for a return type and makes the declarator a 5703 // constructor if it has no return type). 5704 if (Name.getAsIdentifierInfo() && 5705 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5706 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5707 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5708 << SourceRange(D.getIdentifierLoc()); 5709 return 0; 5710 } 5711 5712 bool isStatic = SC == SC_Static; 5713 5714 // [class.free]p1: 5715 // Any allocation function for a class T is a static member 5716 // (even if not explicitly declared static). 5717 if (Name.getCXXOverloadedOperator() == OO_New || 5718 Name.getCXXOverloadedOperator() == OO_Array_New) 5719 isStatic = true; 5720 5721 // [class.free]p6 Any deallocation function for a class X is a static member 5722 // (even if not explicitly declared static). 5723 if (Name.getCXXOverloadedOperator() == OO_Delete || 5724 Name.getCXXOverloadedOperator() == OO_Array_Delete) 5725 isStatic = true; 5726 5727 IsVirtualOkay = !isStatic; 5728 5729 // This is a C++ method declaration. 5730 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5731 D.getLocStart(), NameInfo, R, 5732 TInfo, isStatic, SCAsWritten, isInline, 5733 isConstexpr, SourceLocation()); 5734 5735 } else { 5736 // Determine whether the function was written with a 5737 // prototype. This true when: 5738 // - we're in C++ (where every function has a prototype), 5739 return FunctionDecl::Create(SemaRef.Context, DC, 5740 D.getLocStart(), 5741 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 5742 true/*HasPrototype*/, isConstexpr); 5743 } 5744} 5745 5746void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 5747 // In C++, the empty parameter-type-list must be spelled "void"; a 5748 // typedef of void is not permitted. 5749 if (getLangOpts().CPlusPlus && 5750 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5751 bool IsTypeAlias = false; 5752 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5753 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5754 else if (const TemplateSpecializationType *TST = 5755 Param->getType()->getAs<TemplateSpecializationType>()) 5756 IsTypeAlias = TST->isTypeAlias(); 5757 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5758 << IsTypeAlias; 5759 } 5760} 5761 5762NamedDecl* 5763Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5764 TypeSourceInfo *TInfo, LookupResult &Previous, 5765 MultiTemplateParamsArg TemplateParamLists, 5766 bool &AddToScope) { 5767 QualType R = TInfo->getType(); 5768 5769 assert(R.getTypePtr()->isFunctionType()); 5770 5771 // TODO: consider using NameInfo for diagnostic. 5772 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5773 DeclarationName Name = NameInfo.getName(); 5774 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5775 5776 if (D.getDeclSpec().isThreadSpecified()) 5777 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5778 5779 // Do not allow returning a objc interface by-value. 5780 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5781 Diag(D.getIdentifierLoc(), 5782 diag::err_object_cannot_be_passed_returned_by_value) << 0 5783 << R->getAs<FunctionType>()->getResultType() 5784 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5785 5786 QualType T = R->getAs<FunctionType>()->getResultType(); 5787 T = Context.getObjCObjectPointerType(T); 5788 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5789 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5790 R = Context.getFunctionType(T, 5791 ArrayRef<QualType>(FPT->arg_type_begin(), 5792 FPT->getNumArgs()), 5793 EPI); 5794 } 5795 else if (isa<FunctionNoProtoType>(R)) 5796 R = Context.getFunctionNoProtoType(T); 5797 } 5798 5799 bool isFriend = false; 5800 FunctionTemplateDecl *FunctionTemplate = 0; 5801 bool isExplicitSpecialization = false; 5802 bool isFunctionTemplateSpecialization = false; 5803 5804 bool isDependentClassScopeExplicitSpecialization = false; 5805 bool HasExplicitTemplateArgs = false; 5806 TemplateArgumentListInfo TemplateArgs; 5807 5808 bool isVirtualOkay = false; 5809 5810 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5811 isVirtualOkay); 5812 if (!NewFD) return 0; 5813 5814 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5815 NewFD->setTopLevelDeclInObjCContainer(); 5816 5817 if (getLangOpts().CPlusPlus) { 5818 bool isInline = D.getDeclSpec().isInlineSpecified(); 5819 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5820 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5821 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5822 isFriend = D.getDeclSpec().isFriendSpecified(); 5823 if (isFriend && !isInline && D.isFunctionDefinition()) { 5824 // C++ [class.friend]p5 5825 // A function can be defined in a friend declaration of a 5826 // class . . . . Such a function is implicitly inline. 5827 NewFD->setImplicitlyInline(); 5828 } 5829 5830 // If this is a method defined in an __interface, and is not a constructor 5831 // or an overloaded operator, then set the pure flag (isVirtual will already 5832 // return true). 5833 if (const CXXRecordDecl *Parent = 5834 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 5835 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 5836 NewFD->setPure(true); 5837 } 5838 5839 SetNestedNameSpecifier(NewFD, D); 5840 isExplicitSpecialization = false; 5841 isFunctionTemplateSpecialization = false; 5842 if (D.isInvalidType()) 5843 NewFD->setInvalidDecl(); 5844 5845 // Set the lexical context. If the declarator has a C++ 5846 // scope specifier, or is the object of a friend declaration, the 5847 // lexical context will be different from the semantic context. 5848 NewFD->setLexicalDeclContext(CurContext); 5849 5850 // Match up the template parameter lists with the scope specifier, then 5851 // determine whether we have a template or a template specialization. 5852 bool Invalid = false; 5853 if (TemplateParameterList *TemplateParams 5854 = MatchTemplateParametersToScopeSpecifier( 5855 D.getDeclSpec().getLocStart(), 5856 D.getIdentifierLoc(), 5857 D.getCXXScopeSpec(), 5858 TemplateParamLists.data(), 5859 TemplateParamLists.size(), 5860 isFriend, 5861 isExplicitSpecialization, 5862 Invalid)) { 5863 if (TemplateParams->size() > 0) { 5864 // This is a function template 5865 5866 // Check that we can declare a template here. 5867 if (CheckTemplateDeclScope(S, TemplateParams)) 5868 return 0; 5869 5870 // A destructor cannot be a template. 5871 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5872 Diag(NewFD->getLocation(), diag::err_destructor_template); 5873 return 0; 5874 } 5875 5876 // If we're adding a template to a dependent context, we may need to 5877 // rebuilding some of the types used within the template parameter list, 5878 // now that we know what the current instantiation is. 5879 if (DC->isDependentContext()) { 5880 ContextRAII SavedContext(*this, DC); 5881 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5882 Invalid = true; 5883 } 5884 5885 5886 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5887 NewFD->getLocation(), 5888 Name, TemplateParams, 5889 NewFD); 5890 FunctionTemplate->setLexicalDeclContext(CurContext); 5891 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5892 5893 // For source fidelity, store the other template param lists. 5894 if (TemplateParamLists.size() > 1) { 5895 NewFD->setTemplateParameterListsInfo(Context, 5896 TemplateParamLists.size() - 1, 5897 TemplateParamLists.data()); 5898 } 5899 } else { 5900 // This is a function template specialization. 5901 isFunctionTemplateSpecialization = true; 5902 // For source fidelity, store all the template param lists. 5903 NewFD->setTemplateParameterListsInfo(Context, 5904 TemplateParamLists.size(), 5905 TemplateParamLists.data()); 5906 5907 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5908 if (isFriend) { 5909 // We want to remove the "template<>", found here. 5910 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5911 5912 // If we remove the template<> and the name is not a 5913 // template-id, we're actually silently creating a problem: 5914 // the friend declaration will refer to an untemplated decl, 5915 // and clearly the user wants a template specialization. So 5916 // we need to insert '<>' after the name. 5917 SourceLocation InsertLoc; 5918 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5919 InsertLoc = D.getName().getSourceRange().getEnd(); 5920 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5921 } 5922 5923 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5924 << Name << RemoveRange 5925 << FixItHint::CreateRemoval(RemoveRange) 5926 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5927 } 5928 } 5929 } 5930 else { 5931 // All template param lists were matched against the scope specifier: 5932 // this is NOT (an explicit specialization of) a template. 5933 if (TemplateParamLists.size() > 0) 5934 // For source fidelity, store all the template param lists. 5935 NewFD->setTemplateParameterListsInfo(Context, 5936 TemplateParamLists.size(), 5937 TemplateParamLists.data()); 5938 } 5939 5940 if (Invalid) { 5941 NewFD->setInvalidDecl(); 5942 if (FunctionTemplate) 5943 FunctionTemplate->setInvalidDecl(); 5944 } 5945 5946 // C++ [dcl.fct.spec]p5: 5947 // The virtual specifier shall only be used in declarations of 5948 // nonstatic class member functions that appear within a 5949 // member-specification of a class declaration; see 10.3. 5950 // 5951 if (isVirtual && !NewFD->isInvalidDecl()) { 5952 if (!isVirtualOkay) { 5953 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5954 diag::err_virtual_non_function); 5955 } else if (!CurContext->isRecord()) { 5956 // 'virtual' was specified outside of the class. 5957 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5958 diag::err_virtual_out_of_class) 5959 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5960 } else if (NewFD->getDescribedFunctionTemplate()) { 5961 // C++ [temp.mem]p3: 5962 // A member function template shall not be virtual. 5963 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5964 diag::err_virtual_member_function_template) 5965 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5966 } else { 5967 // Okay: Add virtual to the method. 5968 NewFD->setVirtualAsWritten(true); 5969 } 5970 } 5971 5972 // C++ [dcl.fct.spec]p3: 5973 // The inline specifier shall not appear on a block scope function 5974 // declaration. 5975 if (isInline && !NewFD->isInvalidDecl()) { 5976 if (CurContext->isFunctionOrMethod()) { 5977 // 'inline' is not allowed on block scope function declaration. 5978 Diag(D.getDeclSpec().getInlineSpecLoc(), 5979 diag::err_inline_declaration_block_scope) << Name 5980 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5981 } 5982 } 5983 5984 // C++ [dcl.fct.spec]p6: 5985 // The explicit specifier shall be used only in the declaration of a 5986 // constructor or conversion function within its class definition; 5987 // see 12.3.1 and 12.3.2. 5988 if (isExplicit && !NewFD->isInvalidDecl()) { 5989 if (!CurContext->isRecord()) { 5990 // 'explicit' was specified outside of the class. 5991 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5992 diag::err_explicit_out_of_class) 5993 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5994 } else if (!isa<CXXConstructorDecl>(NewFD) && 5995 !isa<CXXConversionDecl>(NewFD)) { 5996 // 'explicit' was specified on a function that wasn't a constructor 5997 // or conversion function. 5998 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5999 diag::err_explicit_non_ctor_or_conv_function) 6000 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6001 } 6002 } 6003 6004 if (isConstexpr) { 6005 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6006 // are implicitly inline. 6007 NewFD->setImplicitlyInline(); 6008 6009 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6010 // be either constructors or to return a literal type. Therefore, 6011 // destructors cannot be declared constexpr. 6012 if (isa<CXXDestructorDecl>(NewFD)) 6013 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6014 } 6015 6016 // If __module_private__ was specified, mark the function accordingly. 6017 if (D.getDeclSpec().isModulePrivateSpecified()) { 6018 if (isFunctionTemplateSpecialization) { 6019 SourceLocation ModulePrivateLoc 6020 = D.getDeclSpec().getModulePrivateSpecLoc(); 6021 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6022 << 0 6023 << FixItHint::CreateRemoval(ModulePrivateLoc); 6024 } else { 6025 NewFD->setModulePrivate(); 6026 if (FunctionTemplate) 6027 FunctionTemplate->setModulePrivate(); 6028 } 6029 } 6030 6031 if (isFriend) { 6032 // For now, claim that the objects have no previous declaration. 6033 if (FunctionTemplate) { 6034 FunctionTemplate->setObjectOfFriendDecl(false); 6035 FunctionTemplate->setAccess(AS_public); 6036 } 6037 NewFD->setObjectOfFriendDecl(false); 6038 NewFD->setAccess(AS_public); 6039 } 6040 6041 // If a function is defined as defaulted or deleted, mark it as such now. 6042 switch (D.getFunctionDefinitionKind()) { 6043 case FDK_Declaration: 6044 case FDK_Definition: 6045 break; 6046 6047 case FDK_Defaulted: 6048 NewFD->setDefaulted(); 6049 break; 6050 6051 case FDK_Deleted: 6052 NewFD->setDeletedAsWritten(); 6053 break; 6054 } 6055 6056 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6057 D.isFunctionDefinition()) { 6058 // C++ [class.mfct]p2: 6059 // A member function may be defined (8.4) in its class definition, in 6060 // which case it is an inline member function (7.1.2) 6061 NewFD->setImplicitlyInline(); 6062 } 6063 6064 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6065 !CurContext->isRecord()) { 6066 // C++ [class.static]p1: 6067 // A data or function member of a class may be declared static 6068 // in a class definition, in which case it is a static member of 6069 // the class. 6070 6071 // Complain about the 'static' specifier if it's on an out-of-line 6072 // member function definition. 6073 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6074 diag::err_static_out_of_line) 6075 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6076 } 6077 6078 // C++11 [except.spec]p15: 6079 // A deallocation function with no exception-specification is treated 6080 // as if it were specified with noexcept(true). 6081 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6082 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6083 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6084 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6085 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6086 EPI.ExceptionSpecType = EST_BasicNoexcept; 6087 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6088 ArrayRef<QualType>(FPT->arg_type_begin(), 6089 FPT->getNumArgs()), 6090 EPI)); 6091 } 6092 } 6093 6094 // Filter out previous declarations that don't match the scope. 6095 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewFD), 6096 isExplicitSpecialization || 6097 isFunctionTemplateSpecialization); 6098 6099 // Handle GNU asm-label extension (encoded as an attribute). 6100 if (Expr *E = (Expr*) D.getAsmLabel()) { 6101 // The parser guarantees this is a string. 6102 StringLiteral *SE = cast<StringLiteral>(E); 6103 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6104 SE->getString())); 6105 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6106 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6107 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6108 if (I != ExtnameUndeclaredIdentifiers.end()) { 6109 NewFD->addAttr(I->second); 6110 ExtnameUndeclaredIdentifiers.erase(I); 6111 } 6112 } 6113 6114 // Copy the parameter declarations from the declarator D to the function 6115 // declaration NewFD, if they are available. First scavenge them into Params. 6116 SmallVector<ParmVarDecl*, 16> Params; 6117 if (D.isFunctionDeclarator()) { 6118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6119 6120 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6121 // function that takes no arguments, not a function that takes a 6122 // single void argument. 6123 // We let through "const void" here because Sema::GetTypeForDeclarator 6124 // already checks for that case. 6125 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6126 FTI.ArgInfo[0].Param && 6127 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6128 // Empty arg list, don't push any params. 6129 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6130 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6131 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6132 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6133 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6134 Param->setDeclContext(NewFD); 6135 Params.push_back(Param); 6136 6137 if (Param->isInvalidDecl()) 6138 NewFD->setInvalidDecl(); 6139 } 6140 } 6141 6142 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6143 // When we're declaring a function with a typedef, typeof, etc as in the 6144 // following example, we'll need to synthesize (unnamed) 6145 // parameters for use in the declaration. 6146 // 6147 // @code 6148 // typedef void fn(int); 6149 // fn f; 6150 // @endcode 6151 6152 // Synthesize a parameter for each argument type. 6153 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6154 AE = FT->arg_type_end(); AI != AE; ++AI) { 6155 ParmVarDecl *Param = 6156 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6157 Param->setScopeInfo(0, Params.size()); 6158 Params.push_back(Param); 6159 } 6160 } else { 6161 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6162 "Should not need args for typedef of non-prototype fn"); 6163 } 6164 6165 // Finally, we know we have the right number of parameters, install them. 6166 NewFD->setParams(Params); 6167 6168 // Find all anonymous symbols defined during the declaration of this function 6169 // and add to NewFD. This lets us track decls such 'enum Y' in: 6170 // 6171 // void f(enum Y {AA} x) {} 6172 // 6173 // which would otherwise incorrectly end up in the translation unit scope. 6174 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6175 DeclsInPrototypeScope.clear(); 6176 6177 if (D.getDeclSpec().isNoreturnSpecified()) 6178 NewFD->addAttr( 6179 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6180 Context)); 6181 6182 // Process the non-inheritable attributes on this declaration. 6183 ProcessDeclAttributes(S, NewFD, D, 6184 /*NonInheritable=*/true, /*Inheritable=*/false); 6185 6186 // Functions returning a variably modified type violate C99 6.7.5.2p2 6187 // because all functions have linkage. 6188 if (!NewFD->isInvalidDecl() && 6189 NewFD->getResultType()->isVariablyModifiedType()) { 6190 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6191 NewFD->setInvalidDecl(); 6192 } 6193 6194 // Handle attributes. 6195 ProcessDeclAttributes(S, NewFD, D, 6196 /*NonInheritable=*/false, /*Inheritable=*/true); 6197 6198 QualType RetType = NewFD->getResultType(); 6199 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6200 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6201 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6202 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6203 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6204 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) { 6205 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6206 Context)); 6207 } 6208 } 6209 6210 if (!getLangOpts().CPlusPlus) { 6211 // Perform semantic checking on the function declaration. 6212 bool isExplicitSpecialization=false; 6213 if (!NewFD->isInvalidDecl()) { 6214 if (NewFD->isMain()) 6215 CheckMain(NewFD, D.getDeclSpec()); 6216 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6217 isExplicitSpecialization)); 6218 } 6219 // Make graceful recovery from an invalid redeclaration. 6220 else if (!Previous.empty()) 6221 D.setRedeclaration(true); 6222 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6223 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6224 "previous declaration set still overloaded"); 6225 } else { 6226 // If the declarator is a template-id, translate the parser's template 6227 // argument list into our AST format. 6228 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6229 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 6230 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 6231 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 6232 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6233 TemplateId->NumArgs); 6234 translateTemplateArguments(TemplateArgsPtr, 6235 TemplateArgs); 6236 6237 HasExplicitTemplateArgs = true; 6238 6239 if (NewFD->isInvalidDecl()) { 6240 HasExplicitTemplateArgs = false; 6241 } else if (FunctionTemplate) { 6242 // Function template with explicit template arguments. 6243 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 6244 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 6245 6246 HasExplicitTemplateArgs = false; 6247 } else if (!isFunctionTemplateSpecialization && 6248 !D.getDeclSpec().isFriendSpecified()) { 6249 // We have encountered something that the user meant to be a 6250 // specialization (because it has explicitly-specified template 6251 // arguments) but that was not introduced with a "template<>" (or had 6252 // too few of them). 6253 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 6254 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 6255 << FixItHint::CreateInsertion( 6256 D.getDeclSpec().getLocStart(), 6257 "template<> "); 6258 isFunctionTemplateSpecialization = true; 6259 } else { 6260 // "friend void foo<>(int);" is an implicit specialization decl. 6261 isFunctionTemplateSpecialization = true; 6262 } 6263 } else if (isFriend && isFunctionTemplateSpecialization) { 6264 // This combination is only possible in a recovery case; the user 6265 // wrote something like: 6266 // template <> friend void foo(int); 6267 // which we're recovering from as if the user had written: 6268 // friend void foo<>(int); 6269 // Go ahead and fake up a template id. 6270 HasExplicitTemplateArgs = true; 6271 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 6272 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 6273 } 6274 6275 // If it's a friend (and only if it's a friend), it's possible 6276 // that either the specialized function type or the specialized 6277 // template is dependent, and therefore matching will fail. In 6278 // this case, don't check the specialization yet. 6279 bool InstantiationDependent = false; 6280 if (isFunctionTemplateSpecialization && isFriend && 6281 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 6282 TemplateSpecializationType::anyDependentTemplateArguments( 6283 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 6284 InstantiationDependent))) { 6285 assert(HasExplicitTemplateArgs && 6286 "friend function specialization without template args"); 6287 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 6288 Previous)) 6289 NewFD->setInvalidDecl(); 6290 } else if (isFunctionTemplateSpecialization) { 6291 if (CurContext->isDependentContext() && CurContext->isRecord() 6292 && !isFriend) { 6293 isDependentClassScopeExplicitSpecialization = true; 6294 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 6295 diag::ext_function_specialization_in_class : 6296 diag::err_function_specialization_in_class) 6297 << NewFD->getDeclName(); 6298 } else if (CheckFunctionTemplateSpecialization(NewFD, 6299 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 6300 Previous)) 6301 NewFD->setInvalidDecl(); 6302 6303 // C++ [dcl.stc]p1: 6304 // A storage-class-specifier shall not be specified in an explicit 6305 // specialization (14.7.3) 6306 if (SC != SC_None) { 6307 if (SC != NewFD->getStorageClass()) 6308 Diag(NewFD->getLocation(), 6309 diag::err_explicit_specialization_inconsistent_storage_class) 6310 << SC 6311 << FixItHint::CreateRemoval( 6312 D.getDeclSpec().getStorageClassSpecLoc()); 6313 6314 else 6315 Diag(NewFD->getLocation(), 6316 diag::ext_explicit_specialization_storage_class) 6317 << FixItHint::CreateRemoval( 6318 D.getDeclSpec().getStorageClassSpecLoc()); 6319 } 6320 6321 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 6322 if (CheckMemberSpecialization(NewFD, Previous)) 6323 NewFD->setInvalidDecl(); 6324 } 6325 6326 // Perform semantic checking on the function declaration. 6327 if (!isDependentClassScopeExplicitSpecialization) { 6328 if (NewFD->isInvalidDecl()) { 6329 // If this is a class member, mark the class invalid immediately. 6330 // This avoids some consistency errors later. 6331 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 6332 methodDecl->getParent()->setInvalidDecl(); 6333 } else { 6334 if (NewFD->isMain()) 6335 CheckMain(NewFD, D.getDeclSpec()); 6336 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6337 isExplicitSpecialization)); 6338 } 6339 } 6340 6341 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6342 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6343 "previous declaration set still overloaded"); 6344 6345 NamedDecl *PrincipalDecl = (FunctionTemplate 6346 ? cast<NamedDecl>(FunctionTemplate) 6347 : NewFD); 6348 6349 if (isFriend && D.isRedeclaration()) { 6350 AccessSpecifier Access = AS_public; 6351 if (!NewFD->isInvalidDecl()) 6352 Access = NewFD->getPreviousDecl()->getAccess(); 6353 6354 NewFD->setAccess(Access); 6355 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 6356 6357 PrincipalDecl->setObjectOfFriendDecl(true); 6358 } 6359 6360 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 6361 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 6362 PrincipalDecl->setNonMemberOperator(); 6363 6364 // If we have a function template, check the template parameter 6365 // list. This will check and merge default template arguments. 6366 if (FunctionTemplate) { 6367 FunctionTemplateDecl *PrevTemplate = 6368 FunctionTemplate->getPreviousDecl(); 6369 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 6370 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 6371 D.getDeclSpec().isFriendSpecified() 6372 ? (D.isFunctionDefinition() 6373 ? TPC_FriendFunctionTemplateDefinition 6374 : TPC_FriendFunctionTemplate) 6375 : (D.getCXXScopeSpec().isSet() && 6376 DC && DC->isRecord() && 6377 DC->isDependentContext()) 6378 ? TPC_ClassTemplateMember 6379 : TPC_FunctionTemplate); 6380 } 6381 6382 if (NewFD->isInvalidDecl()) { 6383 // Ignore all the rest of this. 6384 } else if (!D.isRedeclaration()) { 6385 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 6386 AddToScope }; 6387 // Fake up an access specifier if it's supposed to be a class member. 6388 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 6389 NewFD->setAccess(AS_public); 6390 6391 // Qualified decls generally require a previous declaration. 6392 if (D.getCXXScopeSpec().isSet()) { 6393 // ...with the major exception of templated-scope or 6394 // dependent-scope friend declarations. 6395 6396 // TODO: we currently also suppress this check in dependent 6397 // contexts because (1) the parameter depth will be off when 6398 // matching friend templates and (2) we might actually be 6399 // selecting a friend based on a dependent factor. But there 6400 // are situations where these conditions don't apply and we 6401 // can actually do this check immediately. 6402 if (isFriend && 6403 (TemplateParamLists.size() || 6404 D.getCXXScopeSpec().getScopeRep()->isDependent() || 6405 CurContext->isDependentContext())) { 6406 // ignore these 6407 } else { 6408 // The user tried to provide an out-of-line definition for a 6409 // function that is a member of a class or namespace, but there 6410 // was no such member function declared (C++ [class.mfct]p2, 6411 // C++ [namespace.memdef]p2). For example: 6412 // 6413 // class X { 6414 // void f() const; 6415 // }; 6416 // 6417 // void X::f() { } // ill-formed 6418 // 6419 // Complain about this problem, and attempt to suggest close 6420 // matches (e.g., those that differ only in cv-qualifiers and 6421 // whether the parameter types are references). 6422 6423 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6424 NewFD, 6425 ExtraArgs)) { 6426 AddToScope = ExtraArgs.AddToScope; 6427 return Result; 6428 } 6429 } 6430 6431 // Unqualified local friend declarations are required to resolve 6432 // to something. 6433 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 6434 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6435 NewFD, 6436 ExtraArgs)) { 6437 AddToScope = ExtraArgs.AddToScope; 6438 return Result; 6439 } 6440 } 6441 6442 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 6443 !isFriend && !isFunctionTemplateSpecialization && 6444 !isExplicitSpecialization) { 6445 // An out-of-line member function declaration must also be a 6446 // definition (C++ [dcl.meaning]p1). 6447 // Note that this is not the case for explicit specializations of 6448 // function templates or member functions of class templates, per 6449 // C++ [temp.expl.spec]p2. We also allow these declarations as an 6450 // extension for compatibility with old SWIG code which likes to 6451 // generate them. 6452 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 6453 << D.getCXXScopeSpec().getRange(); 6454 } 6455 } 6456 6457 ProcessPragmaWeak(S, NewFD); 6458 checkAttributesAfterMerging(*this, *NewFD); 6459 6460 AddKnownFunctionAttributes(NewFD); 6461 6462 if (NewFD->hasAttr<OverloadableAttr>() && 6463 !NewFD->getType()->getAs<FunctionProtoType>()) { 6464 Diag(NewFD->getLocation(), 6465 diag::err_attribute_overloadable_no_prototype) 6466 << NewFD; 6467 6468 // Turn this into a variadic function with no parameters. 6469 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 6470 FunctionProtoType::ExtProtoInfo EPI; 6471 EPI.Variadic = true; 6472 EPI.ExtInfo = FT->getExtInfo(); 6473 6474 QualType R = Context.getFunctionType(FT->getResultType(), 6475 ArrayRef<QualType>(), 6476 EPI); 6477 NewFD->setType(R); 6478 } 6479 6480 // If there's a #pragma GCC visibility in scope, and this isn't a class 6481 // member, set the visibility of this function. 6482 if (!DC->isRecord() && NewFD->hasExternalLinkage()) 6483 AddPushedVisibilityAttribute(NewFD); 6484 6485 // If there's a #pragma clang arc_cf_code_audited in scope, consider 6486 // marking the function. 6487 AddCFAuditedAttribute(NewFD); 6488 6489 // If this is a locally-scoped extern C function, update the 6490 // map of such names. 6491 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 6492 && !NewFD->isInvalidDecl()) 6493 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 6494 6495 // Set this FunctionDecl's range up to the right paren. 6496 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 6497 6498 if (getLangOpts().CPlusPlus) { 6499 if (FunctionTemplate) { 6500 if (NewFD->isInvalidDecl()) 6501 FunctionTemplate->setInvalidDecl(); 6502 return FunctionTemplate; 6503 } 6504 } 6505 6506 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 6507 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 6508 if ((getLangOpts().OpenCLVersion >= 120) 6509 && (SC == SC_Static)) { 6510 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 6511 D.setInvalidType(); 6512 } 6513 6514 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 6515 if (!NewFD->getResultType()->isVoidType()) { 6516 Diag(D.getIdentifierLoc(), 6517 diag::err_expected_kernel_void_return_type); 6518 D.setInvalidType(); 6519 } 6520 6521 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 6522 PE = NewFD->param_end(); PI != PE; ++PI) { 6523 ParmVarDecl *Param = *PI; 6524 QualType PT = Param->getType(); 6525 6526 // OpenCL v1.2 s6.9.a: 6527 // A kernel function argument cannot be declared as a 6528 // pointer to a pointer type. 6529 if (PT->isPointerType() && PT->getPointeeType()->isPointerType()) { 6530 Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_arg); 6531 D.setInvalidType(); 6532 } 6533 6534 // OpenCL v1.2 s6.8 n: 6535 // A kernel function argument cannot be declared 6536 // of event_t type. 6537 if (PT->isEventT()) { 6538 Diag(Param->getLocation(), diag::err_event_t_kernel_arg); 6539 D.setInvalidType(); 6540 } 6541 } 6542 } 6543 6544 MarkUnusedFileScopedDecl(NewFD); 6545 6546 if (getLangOpts().CUDA) 6547 if (IdentifierInfo *II = NewFD->getIdentifier()) 6548 if (!NewFD->isInvalidDecl() && 6549 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6550 if (II->isStr("cudaConfigureCall")) { 6551 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 6552 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 6553 6554 Context.setcudaConfigureCallDecl(NewFD); 6555 } 6556 } 6557 6558 // Here we have an function template explicit specialization at class scope. 6559 // The actually specialization will be postponed to template instatiation 6560 // time via the ClassScopeFunctionSpecializationDecl node. 6561 if (isDependentClassScopeExplicitSpecialization) { 6562 ClassScopeFunctionSpecializationDecl *NewSpec = 6563 ClassScopeFunctionSpecializationDecl::Create( 6564 Context, CurContext, SourceLocation(), 6565 cast<CXXMethodDecl>(NewFD), 6566 HasExplicitTemplateArgs, TemplateArgs); 6567 CurContext->addDecl(NewSpec); 6568 AddToScope = false; 6569 } 6570 6571 return NewFD; 6572} 6573 6574/// \brief Perform semantic checking of a new function declaration. 6575/// 6576/// Performs semantic analysis of the new function declaration 6577/// NewFD. This routine performs all semantic checking that does not 6578/// require the actual declarator involved in the declaration, and is 6579/// used both for the declaration of functions as they are parsed 6580/// (called via ActOnDeclarator) and for the declaration of functions 6581/// that have been instantiated via C++ template instantiation (called 6582/// via InstantiateDecl). 6583/// 6584/// \param IsExplicitSpecialization whether this new function declaration is 6585/// an explicit specialization of the previous declaration. 6586/// 6587/// This sets NewFD->isInvalidDecl() to true if there was an error. 6588/// 6589/// \returns true if the function declaration is a redeclaration. 6590bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 6591 LookupResult &Previous, 6592 bool IsExplicitSpecialization) { 6593 assert(!NewFD->getResultType()->isVariablyModifiedType() 6594 && "Variably modified return types are not handled here"); 6595 6596 // Check for a previous declaration of this name. 6597 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) { 6598 // Since we did not find anything by this name, look for a non-visible 6599 // extern "C" declaration with the same name. 6600 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6601 = findLocallyScopedExternCDecl(NewFD->getDeclName()); 6602 if (Pos != LocallyScopedExternCDecls.end()) 6603 Previous.addDecl(Pos->second); 6604 } 6605 6606 // Filter out any non-conflicting previous declarations. 6607 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 6608 6609 bool Redeclaration = false; 6610 NamedDecl *OldDecl = 0; 6611 6612 // Merge or overload the declaration with an existing declaration of 6613 // the same name, if appropriate. 6614 if (!Previous.empty()) { 6615 // Determine whether NewFD is an overload of PrevDecl or 6616 // a declaration that requires merging. If it's an overload, 6617 // there's no more work to do here; we'll just add the new 6618 // function to the scope. 6619 if (!AllowOverloadingOfFunction(Previous, Context)) { 6620 Redeclaration = true; 6621 OldDecl = Previous.getFoundDecl(); 6622 } else { 6623 switch (CheckOverload(S, NewFD, Previous, OldDecl, 6624 /*NewIsUsingDecl*/ false)) { 6625 case Ovl_Match: 6626 Redeclaration = true; 6627 break; 6628 6629 case Ovl_NonFunction: 6630 Redeclaration = true; 6631 break; 6632 6633 case Ovl_Overload: 6634 Redeclaration = false; 6635 break; 6636 } 6637 6638 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 6639 // If a function name is overloadable in C, then every function 6640 // with that name must be marked "overloadable". 6641 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 6642 << Redeclaration << NewFD; 6643 NamedDecl *OverloadedDecl = 0; 6644 if (Redeclaration) 6645 OverloadedDecl = OldDecl; 6646 else if (!Previous.empty()) 6647 OverloadedDecl = Previous.getRepresentativeDecl(); 6648 if (OverloadedDecl) 6649 Diag(OverloadedDecl->getLocation(), 6650 diag::note_attribute_overloadable_prev_overload); 6651 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 6652 Context)); 6653 } 6654 } 6655 } 6656 6657 // C++11 [dcl.constexpr]p8: 6658 // A constexpr specifier for a non-static member function that is not 6659 // a constructor declares that member function to be const. 6660 // 6661 // This needs to be delayed until we know whether this is an out-of-line 6662 // definition of a static member function. 6663 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6664 if (MD && MD->isConstexpr() && !MD->isStatic() && 6665 !isa<CXXConstructorDecl>(MD) && 6666 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 6667 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 6668 if (FunctionTemplateDecl *OldTD = 6669 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 6670 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 6671 if (!OldMD || !OldMD->isStatic()) { 6672 const FunctionProtoType *FPT = 6673 MD->getType()->castAs<FunctionProtoType>(); 6674 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6675 EPI.TypeQuals |= Qualifiers::Const; 6676 MD->setType(Context.getFunctionType(FPT->getResultType(), 6677 ArrayRef<QualType>(FPT->arg_type_begin(), 6678 FPT->getNumArgs()), 6679 EPI)); 6680 } 6681 } 6682 6683 if (Redeclaration) { 6684 // NewFD and OldDecl represent declarations that need to be 6685 // merged. 6686 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 6687 NewFD->setInvalidDecl(); 6688 return Redeclaration; 6689 } 6690 6691 Previous.clear(); 6692 Previous.addDecl(OldDecl); 6693 6694 if (FunctionTemplateDecl *OldTemplateDecl 6695 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 6696 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 6697 FunctionTemplateDecl *NewTemplateDecl 6698 = NewFD->getDescribedFunctionTemplate(); 6699 assert(NewTemplateDecl && "Template/non-template mismatch"); 6700 if (CXXMethodDecl *Method 6701 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 6702 Method->setAccess(OldTemplateDecl->getAccess()); 6703 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 6704 } 6705 6706 // If this is an explicit specialization of a member that is a function 6707 // template, mark it as a member specialization. 6708 if (IsExplicitSpecialization && 6709 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 6710 NewTemplateDecl->setMemberSpecialization(); 6711 assert(OldTemplateDecl->isMemberSpecialization()); 6712 } 6713 6714 } else { 6715 // This needs to happen first so that 'inline' propagates. 6716 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 6717 6718 if (isa<CXXMethodDecl>(NewFD)) { 6719 // A valid redeclaration of a C++ method must be out-of-line, 6720 // but (unfortunately) it's not necessarily a definition 6721 // because of templates, which means that the previous 6722 // declaration is not necessarily from the class definition. 6723 6724 // For just setting the access, that doesn't matter. 6725 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 6726 NewFD->setAccess(oldMethod->getAccess()); 6727 6728 // Update the key-function state if necessary for this ABI. 6729 if (NewFD->isInlined() && 6730 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 6731 // setNonKeyFunction needs to work with the original 6732 // declaration from the class definition, and isVirtual() is 6733 // just faster in that case, so map back to that now. 6734 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration()); 6735 if (oldMethod->isVirtual()) { 6736 Context.setNonKeyFunction(oldMethod); 6737 } 6738 } 6739 } 6740 } 6741 } 6742 6743 // Semantic checking for this function declaration (in isolation). 6744 if (getLangOpts().CPlusPlus) { 6745 // C++-specific checks. 6746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 6747 CheckConstructor(Constructor); 6748 } else if (CXXDestructorDecl *Destructor = 6749 dyn_cast<CXXDestructorDecl>(NewFD)) { 6750 CXXRecordDecl *Record = Destructor->getParent(); 6751 QualType ClassType = Context.getTypeDeclType(Record); 6752 6753 // FIXME: Shouldn't we be able to perform this check even when the class 6754 // type is dependent? Both gcc and edg can handle that. 6755 if (!ClassType->isDependentType()) { 6756 DeclarationName Name 6757 = Context.DeclarationNames.getCXXDestructorName( 6758 Context.getCanonicalType(ClassType)); 6759 if (NewFD->getDeclName() != Name) { 6760 Diag(NewFD->getLocation(), diag::err_destructor_name); 6761 NewFD->setInvalidDecl(); 6762 return Redeclaration; 6763 } 6764 } 6765 } else if (CXXConversionDecl *Conversion 6766 = dyn_cast<CXXConversionDecl>(NewFD)) { 6767 ActOnConversionDeclarator(Conversion); 6768 } 6769 6770 // Find any virtual functions that this function overrides. 6771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 6772 if (!Method->isFunctionTemplateSpecialization() && 6773 !Method->getDescribedFunctionTemplate() && 6774 Method->isCanonicalDecl()) { 6775 if (AddOverriddenMethods(Method->getParent(), Method)) { 6776 // If the function was marked as "static", we have a problem. 6777 if (NewFD->getStorageClass() == SC_Static) { 6778 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 6779 } 6780 } 6781 } 6782 6783 if (Method->isStatic()) 6784 checkThisInStaticMemberFunctionType(Method); 6785 } 6786 6787 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6788 if (NewFD->isOverloadedOperator() && 6789 CheckOverloadedOperatorDeclaration(NewFD)) { 6790 NewFD->setInvalidDecl(); 6791 return Redeclaration; 6792 } 6793 6794 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6795 if (NewFD->getLiteralIdentifier() && 6796 CheckLiteralOperatorDeclaration(NewFD)) { 6797 NewFD->setInvalidDecl(); 6798 return Redeclaration; 6799 } 6800 6801 // In C++, check default arguments now that we have merged decls. Unless 6802 // the lexical context is the class, because in this case this is done 6803 // during delayed parsing anyway. 6804 if (!CurContext->isRecord()) 6805 CheckCXXDefaultArguments(NewFD); 6806 6807 // If this function declares a builtin function, check the type of this 6808 // declaration against the expected type for the builtin. 6809 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6810 ASTContext::GetBuiltinTypeError Error; 6811 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 6812 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6813 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6814 // The type of this function differs from the type of the builtin, 6815 // so forget about the builtin entirely. 6816 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6817 } 6818 } 6819 6820 // If this function is declared as being extern "C", then check to see if 6821 // the function returns a UDT (class, struct, or union type) that is not C 6822 // compatible, and if it does, warn the user. 6823 // But, issue any diagnostic on the first declaration only. 6824 if (NewFD->isExternC() && Previous.empty()) { 6825 QualType R = NewFD->getResultType(); 6826 if (R->isIncompleteType() && !R->isVoidType()) 6827 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6828 << NewFD << R; 6829 else if (!R.isPODType(Context) && !R->isVoidType() && 6830 !R->isObjCObjectPointerType()) 6831 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6832 } 6833 } 6834 return Redeclaration; 6835} 6836 6837static SourceRange getResultSourceRange(const FunctionDecl *FD) { 6838 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6839 if (!TSI) 6840 return SourceRange(); 6841 6842 TypeLoc TL = TSI->getTypeLoc(); 6843 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 6844 if (!FunctionTL) 6845 return SourceRange(); 6846 6847 TypeLoc ResultTL = FunctionTL.getResultLoc(); 6848 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 6849 return ResultTL.getSourceRange(); 6850 6851 return SourceRange(); 6852} 6853 6854void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6855 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6856 // static or constexpr is ill-formed. 6857 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 6858 // appear in a declaration of main. 6859 // static main is not an error under C99, but we should warn about it. 6860 // We accept _Noreturn main as an extension. 6861 if (FD->getStorageClass() == SC_Static) 6862 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6863 ? diag::err_static_main : diag::warn_static_main) 6864 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6865 if (FD->isInlineSpecified()) 6866 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6867 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6868 if (DS.isNoreturnSpecified()) { 6869 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 6870 SourceRange NoreturnRange(NoreturnLoc, 6871 PP.getLocForEndOfToken(NoreturnLoc)); 6872 Diag(NoreturnLoc, diag::ext_noreturn_main); 6873 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 6874 << FixItHint::CreateRemoval(NoreturnRange); 6875 } 6876 if (FD->isConstexpr()) { 6877 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6878 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6879 FD->setConstexpr(false); 6880 } 6881 6882 QualType T = FD->getType(); 6883 assert(T->isFunctionType() && "function decl is not of function type"); 6884 const FunctionType* FT = T->castAs<FunctionType>(); 6885 6886 // All the standards say that main() should should return 'int'. 6887 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6888 // In C and C++, main magically returns 0 if you fall off the end; 6889 // set the flag which tells us that. 6890 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6891 FD->setHasImplicitReturnZero(true); 6892 6893 // In C with GNU extensions we allow main() to have non-integer return 6894 // type, but we should warn about the extension, and we disable the 6895 // implicit-return-zero rule. 6896 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6897 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6898 6899 SourceRange ResultRange = getResultSourceRange(FD); 6900 if (ResultRange.isValid()) 6901 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 6902 << FixItHint::CreateReplacement(ResultRange, "int"); 6903 6904 // Otherwise, this is just a flat-out error. 6905 } else { 6906 SourceRange ResultRange = getResultSourceRange(FD); 6907 if (ResultRange.isValid()) 6908 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 6909 << FixItHint::CreateReplacement(ResultRange, "int"); 6910 else 6911 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6912 6913 FD->setInvalidDecl(true); 6914 } 6915 6916 // Treat protoless main() as nullary. 6917 if (isa<FunctionNoProtoType>(FT)) return; 6918 6919 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6920 unsigned nparams = FTP->getNumArgs(); 6921 assert(FD->getNumParams() == nparams); 6922 6923 bool HasExtraParameters = (nparams > 3); 6924 6925 // Darwin passes an undocumented fourth argument of type char**. If 6926 // other platforms start sprouting these, the logic below will start 6927 // getting shifty. 6928 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6929 HasExtraParameters = false; 6930 6931 if (HasExtraParameters) { 6932 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6933 FD->setInvalidDecl(true); 6934 nparams = 3; 6935 } 6936 6937 // FIXME: a lot of the following diagnostics would be improved 6938 // if we had some location information about types. 6939 6940 QualType CharPP = 6941 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6942 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6943 6944 for (unsigned i = 0; i < nparams; ++i) { 6945 QualType AT = FTP->getArgType(i); 6946 6947 bool mismatch = true; 6948 6949 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6950 mismatch = false; 6951 else if (Expected[i] == CharPP) { 6952 // As an extension, the following forms are okay: 6953 // char const ** 6954 // char const * const * 6955 // char * const * 6956 6957 QualifierCollector qs; 6958 const PointerType* PT; 6959 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 6960 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 6961 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 6962 Context.CharTy)) { 6963 qs.removeConst(); 6964 mismatch = !qs.empty(); 6965 } 6966 } 6967 6968 if (mismatch) { 6969 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 6970 // TODO: suggest replacing given type with expected type 6971 FD->setInvalidDecl(true); 6972 } 6973 } 6974 6975 if (nparams == 1 && !FD->isInvalidDecl()) { 6976 Diag(FD->getLocation(), diag::warn_main_one_arg); 6977 } 6978 6979 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 6980 Diag(FD->getLocation(), diag::err_main_template_decl); 6981 FD->setInvalidDecl(); 6982 } 6983} 6984 6985bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 6986 // FIXME: Need strict checking. In C89, we need to check for 6987 // any assignment, increment, decrement, function-calls, or 6988 // commas outside of a sizeof. In C99, it's the same list, 6989 // except that the aforementioned are allowed in unevaluated 6990 // expressions. Everything else falls under the 6991 // "may accept other forms of constant expressions" exception. 6992 // (We never end up here for C++, so the constant expression 6993 // rules there don't matter.) 6994 if (Init->isConstantInitializer(Context, false)) 6995 return false; 6996 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 6997 << Init->getSourceRange(); 6998 return true; 6999} 7000 7001namespace { 7002 // Visits an initialization expression to see if OrigDecl is evaluated in 7003 // its own initialization and throws a warning if it does. 7004 class SelfReferenceChecker 7005 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7006 Sema &S; 7007 Decl *OrigDecl; 7008 bool isRecordType; 7009 bool isPODType; 7010 bool isReferenceType; 7011 7012 public: 7013 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7014 7015 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7016 S(S), OrigDecl(OrigDecl) { 7017 isPODType = false; 7018 isRecordType = false; 7019 isReferenceType = false; 7020 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7021 isPODType = VD->getType().isPODType(S.Context); 7022 isRecordType = VD->getType()->isRecordType(); 7023 isReferenceType = VD->getType()->isReferenceType(); 7024 } 7025 } 7026 7027 // For most expressions, the cast is directly above the DeclRefExpr. 7028 // For conditional operators, the cast can be outside the conditional 7029 // operator if both expressions are DeclRefExpr's. 7030 void HandleValue(Expr *E) { 7031 if (isReferenceType) 7032 return; 7033 E = E->IgnoreParenImpCasts(); 7034 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7035 HandleDeclRefExpr(DRE); 7036 return; 7037 } 7038 7039 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7040 HandleValue(CO->getTrueExpr()); 7041 HandleValue(CO->getFalseExpr()); 7042 return; 7043 } 7044 7045 if (isa<MemberExpr>(E)) { 7046 Expr *Base = E->IgnoreParenImpCasts(); 7047 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7048 // Check for static member variables and don't warn on them. 7049 if (!isa<FieldDecl>(ME->getMemberDecl())) 7050 return; 7051 Base = ME->getBase()->IgnoreParenImpCasts(); 7052 } 7053 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7054 HandleDeclRefExpr(DRE); 7055 return; 7056 } 7057 } 7058 7059 // Reference types are handled here since all uses of references are 7060 // bad, not just r-value uses. 7061 void VisitDeclRefExpr(DeclRefExpr *E) { 7062 if (isReferenceType) 7063 HandleDeclRefExpr(E); 7064 } 7065 7066 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7067 if (E->getCastKind() == CK_LValueToRValue || 7068 (isRecordType && E->getCastKind() == CK_NoOp)) 7069 HandleValue(E->getSubExpr()); 7070 7071 Inherited::VisitImplicitCastExpr(E); 7072 } 7073 7074 void VisitMemberExpr(MemberExpr *E) { 7075 // Don't warn on arrays since they can be treated as pointers. 7076 if (E->getType()->canDecayToPointerType()) return; 7077 7078 // Warn when a non-static method call is followed by non-static member 7079 // field accesses, which is followed by a DeclRefExpr. 7080 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7081 bool Warn = (MD && !MD->isStatic()); 7082 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7083 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7084 if (!isa<FieldDecl>(ME->getMemberDecl())) 7085 Warn = false; 7086 Base = ME->getBase()->IgnoreParenImpCasts(); 7087 } 7088 7089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7090 if (Warn) 7091 HandleDeclRefExpr(DRE); 7092 return; 7093 } 7094 7095 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7096 // Visit that expression. 7097 Visit(Base); 7098 } 7099 7100 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7101 if (E->getNumArgs() > 0) 7102 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7103 HandleDeclRefExpr(DRE); 7104 7105 Inherited::VisitCXXOperatorCallExpr(E); 7106 } 7107 7108 void VisitUnaryOperator(UnaryOperator *E) { 7109 // For POD record types, addresses of its own members are well-defined. 7110 if (E->getOpcode() == UO_AddrOf && isRecordType && 7111 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7112 if (!isPODType) 7113 HandleValue(E->getSubExpr()); 7114 return; 7115 } 7116 Inherited::VisitUnaryOperator(E); 7117 } 7118 7119 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7120 7121 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7122 Decl* ReferenceDecl = DRE->getDecl(); 7123 if (OrigDecl != ReferenceDecl) return; 7124 unsigned diag; 7125 if (isReferenceType) { 7126 diag = diag::warn_uninit_self_reference_in_reference_init; 7127 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7128 diag = diag::warn_static_self_reference_in_init; 7129 } else { 7130 diag = diag::warn_uninit_self_reference_in_init; 7131 } 7132 7133 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7134 S.PDiag(diag) 7135 << DRE->getNameInfo().getName() 7136 << OrigDecl->getLocation() 7137 << DRE->getSourceRange()); 7138 } 7139 }; 7140 7141 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7142 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7143 bool DirectInit) { 7144 // Parameters arguments are occassionially constructed with itself, 7145 // for instance, in recursive functions. Skip them. 7146 if (isa<ParmVarDecl>(OrigDecl)) 7147 return; 7148 7149 E = E->IgnoreParens(); 7150 7151 // Skip checking T a = a where T is not a record or reference type. 7152 // Doing so is a way to silence uninitialized warnings. 7153 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7154 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7155 if (ICE->getCastKind() == CK_LValueToRValue) 7156 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7157 if (DRE->getDecl() == OrigDecl) 7158 return; 7159 7160 SelfReferenceChecker(S, OrigDecl).Visit(E); 7161 } 7162} 7163 7164/// AddInitializerToDecl - Adds the initializer Init to the 7165/// declaration dcl. If DirectInit is true, this is C++ direct 7166/// initialization rather than copy initialization. 7167void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 7168 bool DirectInit, bool TypeMayContainAuto) { 7169 // If there is no declaration, there was an error parsing it. Just ignore 7170 // the initializer. 7171 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 7172 return; 7173 7174 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 7175 // With declarators parsed the way they are, the parser cannot 7176 // distinguish between a normal initializer and a pure-specifier. 7177 // Thus this grotesque test. 7178 IntegerLiteral *IL; 7179 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 7180 Context.getCanonicalType(IL->getType()) == Context.IntTy) 7181 CheckPureMethod(Method, Init->getSourceRange()); 7182 else { 7183 Diag(Method->getLocation(), diag::err_member_function_initialization) 7184 << Method->getDeclName() << Init->getSourceRange(); 7185 Method->setInvalidDecl(); 7186 } 7187 return; 7188 } 7189 7190 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 7191 if (!VDecl) { 7192 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 7193 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 7194 RealDecl->setInvalidDecl(); 7195 return; 7196 } 7197 7198 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 7199 7200 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 7201 AutoType *Auto = 0; 7202 if (TypeMayContainAuto && 7203 (Auto = VDecl->getType()->getContainedAutoType()) && 7204 !Auto->isDeduced()) { 7205 Expr *DeduceInit = Init; 7206 // Initializer could be a C++ direct-initializer. Deduction only works if it 7207 // contains exactly one expression. 7208 if (CXXDirectInit) { 7209 if (CXXDirectInit->getNumExprs() == 0) { 7210 // It isn't possible to write this directly, but it is possible to 7211 // end up in this situation with "auto x(some_pack...);" 7212 Diag(CXXDirectInit->getLocStart(), 7213 diag::err_auto_var_init_no_expression) 7214 << VDecl->getDeclName() << VDecl->getType() 7215 << VDecl->getSourceRange(); 7216 RealDecl->setInvalidDecl(); 7217 return; 7218 } else if (CXXDirectInit->getNumExprs() > 1) { 7219 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 7220 diag::err_auto_var_init_multiple_expressions) 7221 << VDecl->getDeclName() << VDecl->getType() 7222 << VDecl->getSourceRange(); 7223 RealDecl->setInvalidDecl(); 7224 return; 7225 } else { 7226 DeduceInit = CXXDirectInit->getExpr(0); 7227 } 7228 } 7229 7230 // Expressions default to 'id' when we're in a debugger. 7231 bool DefaultedToAuto = false; 7232 if (getLangOpts().DebuggerCastResultToId && 7233 Init->getType() == Context.UnknownAnyTy) { 7234 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7235 if (Result.isInvalid()) { 7236 VDecl->setInvalidDecl(); 7237 return; 7238 } 7239 Init = Result.take(); 7240 DefaultedToAuto = true; 7241 } 7242 7243 TypeSourceInfo *DeducedType = 0; 7244 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 7245 DAR_Failed) 7246 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 7247 if (!DeducedType) { 7248 RealDecl->setInvalidDecl(); 7249 return; 7250 } 7251 VDecl->setTypeSourceInfo(DeducedType); 7252 VDecl->setType(DeducedType->getType()); 7253 assert(VDecl->isLinkageValid()); 7254 7255 // In ARC, infer lifetime. 7256 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 7257 VDecl->setInvalidDecl(); 7258 7259 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 7260 // 'id' instead of a specific object type prevents most of our usual checks. 7261 // We only want to warn outside of template instantiations, though: 7262 // inside a template, the 'id' could have come from a parameter. 7263 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 7264 DeducedType->getType()->isObjCIdType()) { 7265 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 7266 Diag(Loc, diag::warn_auto_var_is_id) 7267 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 7268 } 7269 7270 // If this is a redeclaration, check that the type we just deduced matches 7271 // the previously declared type. 7272 if (VarDecl *Old = VDecl->getPreviousDecl()) 7273 MergeVarDeclTypes(VDecl, Old); 7274 } 7275 7276 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 7277 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 7278 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 7279 VDecl->setInvalidDecl(); 7280 return; 7281 } 7282 7283 if (!VDecl->getType()->isDependentType()) { 7284 // A definition must end up with a complete type, which means it must be 7285 // complete with the restriction that an array type might be completed by 7286 // the initializer; note that later code assumes this restriction. 7287 QualType BaseDeclType = VDecl->getType(); 7288 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 7289 BaseDeclType = Array->getElementType(); 7290 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 7291 diag::err_typecheck_decl_incomplete_type)) { 7292 RealDecl->setInvalidDecl(); 7293 return; 7294 } 7295 7296 // The variable can not have an abstract class type. 7297 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 7298 diag::err_abstract_type_in_decl, 7299 AbstractVariableType)) 7300 VDecl->setInvalidDecl(); 7301 } 7302 7303 const VarDecl *Def; 7304 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 7305 Diag(VDecl->getLocation(), diag::err_redefinition) 7306 << VDecl->getDeclName(); 7307 Diag(Def->getLocation(), diag::note_previous_definition); 7308 VDecl->setInvalidDecl(); 7309 return; 7310 } 7311 7312 const VarDecl* PrevInit = 0; 7313 if (getLangOpts().CPlusPlus) { 7314 // C++ [class.static.data]p4 7315 // If a static data member is of const integral or const 7316 // enumeration type, its declaration in the class definition can 7317 // specify a constant-initializer which shall be an integral 7318 // constant expression (5.19). In that case, the member can appear 7319 // in integral constant expressions. The member shall still be 7320 // defined in a namespace scope if it is used in the program and the 7321 // namespace scope definition shall not contain an initializer. 7322 // 7323 // We already performed a redefinition check above, but for static 7324 // data members we also need to check whether there was an in-class 7325 // declaration with an initializer. 7326 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 7327 Diag(VDecl->getLocation(), diag::err_redefinition) 7328 << VDecl->getDeclName(); 7329 Diag(PrevInit->getLocation(), diag::note_previous_definition); 7330 return; 7331 } 7332 7333 if (VDecl->hasLocalStorage()) 7334 getCurFunction()->setHasBranchProtectedScope(); 7335 7336 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 7337 VDecl->setInvalidDecl(); 7338 return; 7339 } 7340 } 7341 7342 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 7343 // a kernel function cannot be initialized." 7344 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 7345 Diag(VDecl->getLocation(), diag::err_local_cant_init); 7346 VDecl->setInvalidDecl(); 7347 return; 7348 } 7349 7350 // Get the decls type and save a reference for later, since 7351 // CheckInitializerTypes may change it. 7352 QualType DclT = VDecl->getType(), SavT = DclT; 7353 7354 // Expressions default to 'id' when we're in a debugger 7355 // and we are assigning it to a variable of Objective-C pointer type. 7356 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 7357 Init->getType() == Context.UnknownAnyTy) { 7358 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7359 if (Result.isInvalid()) { 7360 VDecl->setInvalidDecl(); 7361 return; 7362 } 7363 Init = Result.take(); 7364 } 7365 7366 // Perform the initialization. 7367 if (!VDecl->isInvalidDecl()) { 7368 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 7369 InitializationKind Kind 7370 = DirectInit ? 7371 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 7372 Init->getLocStart(), 7373 Init->getLocEnd()) 7374 : InitializationKind::CreateDirectList( 7375 VDecl->getLocation()) 7376 : InitializationKind::CreateCopy(VDecl->getLocation(), 7377 Init->getLocStart()); 7378 7379 Expr **Args = &Init; 7380 unsigned NumArgs = 1; 7381 if (CXXDirectInit) { 7382 Args = CXXDirectInit->getExprs(); 7383 NumArgs = CXXDirectInit->getNumExprs(); 7384 } 7385 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 7386 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 7387 MultiExprArg(Args, NumArgs), &DclT); 7388 if (Result.isInvalid()) { 7389 VDecl->setInvalidDecl(); 7390 return; 7391 } 7392 7393 Init = Result.takeAs<Expr>(); 7394 } 7395 7396 // Check for self-references within variable initializers. 7397 // Variables declared within a function/method body (except for references) 7398 // are handled by a dataflow analysis. 7399 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 7400 VDecl->getType()->isReferenceType()) { 7401 CheckSelfReference(*this, RealDecl, Init, DirectInit); 7402 } 7403 7404 // If the type changed, it means we had an incomplete type that was 7405 // completed by the initializer. For example: 7406 // int ary[] = { 1, 3, 5 }; 7407 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 7408 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 7409 VDecl->setType(DclT); 7410 7411 if (!VDecl->isInvalidDecl()) { 7412 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 7413 7414 if (VDecl->hasAttr<BlocksAttr>()) 7415 checkRetainCycles(VDecl, Init); 7416 7417 // It is safe to assign a weak reference into a strong variable. 7418 // Although this code can still have problems: 7419 // id x = self.weakProp; 7420 // id y = self.weakProp; 7421 // we do not warn to warn spuriously when 'x' and 'y' are on separate 7422 // paths through the function. This should be revisited if 7423 // -Wrepeated-use-of-weak is made flow-sensitive. 7424 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 7425 DiagnosticsEngine::Level Level = 7426 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 7427 Init->getLocStart()); 7428 if (Level != DiagnosticsEngine::Ignored) 7429 getCurFunction()->markSafeWeakUse(Init); 7430 } 7431 } 7432 7433 // The initialization is usually a full-expression. 7434 // 7435 // FIXME: If this is a braced initialization of an aggregate, it is not 7436 // an expression, and each individual field initializer is a separate 7437 // full-expression. For instance, in: 7438 // 7439 // struct Temp { ~Temp(); }; 7440 // struct S { S(Temp); }; 7441 // struct T { S a, b; } t = { Temp(), Temp() } 7442 // 7443 // we should destroy the first Temp before constructing the second. 7444 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 7445 false, 7446 VDecl->isConstexpr()); 7447 if (Result.isInvalid()) { 7448 VDecl->setInvalidDecl(); 7449 return; 7450 } 7451 Init = Result.take(); 7452 7453 // Attach the initializer to the decl. 7454 VDecl->setInit(Init); 7455 7456 if (VDecl->isLocalVarDecl()) { 7457 // C99 6.7.8p4: All the expressions in an initializer for an object that has 7458 // static storage duration shall be constant expressions or string literals. 7459 // C++ does not have this restriction. 7460 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 7461 VDecl->getStorageClass() == SC_Static) 7462 CheckForConstantInitializer(Init, DclT); 7463 } else if (VDecl->isStaticDataMember() && 7464 VDecl->getLexicalDeclContext()->isRecord()) { 7465 // This is an in-class initialization for a static data member, e.g., 7466 // 7467 // struct S { 7468 // static const int value = 17; 7469 // }; 7470 7471 // C++ [class.mem]p4: 7472 // A member-declarator can contain a constant-initializer only 7473 // if it declares a static member (9.4) of const integral or 7474 // const enumeration type, see 9.4.2. 7475 // 7476 // C++11 [class.static.data]p3: 7477 // If a non-volatile const static data member is of integral or 7478 // enumeration type, its declaration in the class definition can 7479 // specify a brace-or-equal-initializer in which every initalizer-clause 7480 // that is an assignment-expression is a constant expression. A static 7481 // data member of literal type can be declared in the class definition 7482 // with the constexpr specifier; if so, its declaration shall specify a 7483 // brace-or-equal-initializer in which every initializer-clause that is 7484 // an assignment-expression is a constant expression. 7485 7486 // Do nothing on dependent types. 7487 if (DclT->isDependentType()) { 7488 7489 // Allow any 'static constexpr' members, whether or not they are of literal 7490 // type. We separately check that every constexpr variable is of literal 7491 // type. 7492 } else if (VDecl->isConstexpr()) { 7493 7494 // Require constness. 7495 } else if (!DclT.isConstQualified()) { 7496 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 7497 << Init->getSourceRange(); 7498 VDecl->setInvalidDecl(); 7499 7500 // We allow integer constant expressions in all cases. 7501 } else if (DclT->isIntegralOrEnumerationType()) { 7502 // Check whether the expression is a constant expression. 7503 SourceLocation Loc; 7504 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 7505 // In C++11, a non-constexpr const static data member with an 7506 // in-class initializer cannot be volatile. 7507 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 7508 else if (Init->isValueDependent()) 7509 ; // Nothing to check. 7510 else if (Init->isIntegerConstantExpr(Context, &Loc)) 7511 ; // Ok, it's an ICE! 7512 else if (Init->isEvaluatable(Context)) { 7513 // If we can constant fold the initializer through heroics, accept it, 7514 // but report this as a use of an extension for -pedantic. 7515 Diag(Loc, diag::ext_in_class_initializer_non_constant) 7516 << Init->getSourceRange(); 7517 } else { 7518 // Otherwise, this is some crazy unknown case. Report the issue at the 7519 // location provided by the isIntegerConstantExpr failed check. 7520 Diag(Loc, diag::err_in_class_initializer_non_constant) 7521 << Init->getSourceRange(); 7522 VDecl->setInvalidDecl(); 7523 } 7524 7525 // We allow foldable floating-point constants as an extension. 7526 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 7527 // In C++98, this is a GNU extension. In C++11, it is not, but we support 7528 // it anyway and provide a fixit to add the 'constexpr'. 7529 if (getLangOpts().CPlusPlus11) { 7530 Diag(VDecl->getLocation(), 7531 diag::ext_in_class_initializer_float_type_cxx11) 7532 << DclT << Init->getSourceRange(); 7533 Diag(VDecl->getLocStart(), 7534 diag::note_in_class_initializer_float_type_cxx11) 7535 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7536 } else { 7537 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 7538 << DclT << Init->getSourceRange(); 7539 7540 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 7541 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 7542 << Init->getSourceRange(); 7543 VDecl->setInvalidDecl(); 7544 } 7545 } 7546 7547 // Suggest adding 'constexpr' in C++11 for literal types. 7548 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) { 7549 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 7550 << DclT << Init->getSourceRange() 7551 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7552 VDecl->setConstexpr(true); 7553 7554 } else { 7555 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 7556 << DclT << Init->getSourceRange(); 7557 VDecl->setInvalidDecl(); 7558 } 7559 } else if (VDecl->isFileVarDecl()) { 7560 if (VDecl->getStorageClassAsWritten() == SC_Extern && 7561 (!getLangOpts().CPlusPlus || 7562 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 7563 Diag(VDecl->getLocation(), diag::warn_extern_init); 7564 7565 // C99 6.7.8p4. All file scoped initializers need to be constant. 7566 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 7567 CheckForConstantInitializer(Init, DclT); 7568 } 7569 7570 // We will represent direct-initialization similarly to copy-initialization: 7571 // int x(1); -as-> int x = 1; 7572 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 7573 // 7574 // Clients that want to distinguish between the two forms, can check for 7575 // direct initializer using VarDecl::getInitStyle(). 7576 // A major benefit is that clients that don't particularly care about which 7577 // exactly form was it (like the CodeGen) can handle both cases without 7578 // special case code. 7579 7580 // C++ 8.5p11: 7581 // The form of initialization (using parentheses or '=') is generally 7582 // insignificant, but does matter when the entity being initialized has a 7583 // class type. 7584 if (CXXDirectInit) { 7585 assert(DirectInit && "Call-style initializer must be direct init."); 7586 VDecl->setInitStyle(VarDecl::CallInit); 7587 } else if (DirectInit) { 7588 // This must be list-initialization. No other way is direct-initialization. 7589 VDecl->setInitStyle(VarDecl::ListInit); 7590 } 7591 7592 CheckCompleteVariableDeclaration(VDecl); 7593} 7594 7595/// ActOnInitializerError - Given that there was an error parsing an 7596/// initializer for the given declaration, try to return to some form 7597/// of sanity. 7598void Sema::ActOnInitializerError(Decl *D) { 7599 // Our main concern here is re-establishing invariants like "a 7600 // variable's type is either dependent or complete". 7601 if (!D || D->isInvalidDecl()) return; 7602 7603 VarDecl *VD = dyn_cast<VarDecl>(D); 7604 if (!VD) return; 7605 7606 // Auto types are meaningless if we can't make sense of the initializer. 7607 if (ParsingInitForAutoVars.count(D)) { 7608 D->setInvalidDecl(); 7609 return; 7610 } 7611 7612 QualType Ty = VD->getType(); 7613 if (Ty->isDependentType()) return; 7614 7615 // Require a complete type. 7616 if (RequireCompleteType(VD->getLocation(), 7617 Context.getBaseElementType(Ty), 7618 diag::err_typecheck_decl_incomplete_type)) { 7619 VD->setInvalidDecl(); 7620 return; 7621 } 7622 7623 // Require an abstract type. 7624 if (RequireNonAbstractType(VD->getLocation(), Ty, 7625 diag::err_abstract_type_in_decl, 7626 AbstractVariableType)) { 7627 VD->setInvalidDecl(); 7628 return; 7629 } 7630 7631 // Don't bother complaining about constructors or destructors, 7632 // though. 7633} 7634 7635void Sema::ActOnUninitializedDecl(Decl *RealDecl, 7636 bool TypeMayContainAuto) { 7637 // If there is no declaration, there was an error parsing it. Just ignore it. 7638 if (RealDecl == 0) 7639 return; 7640 7641 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 7642 QualType Type = Var->getType(); 7643 7644 // C++11 [dcl.spec.auto]p3 7645 if (TypeMayContainAuto && Type->getContainedAutoType()) { 7646 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 7647 << Var->getDeclName() << Type; 7648 Var->setInvalidDecl(); 7649 return; 7650 } 7651 7652 // C++11 [class.static.data]p3: A static data member can be declared with 7653 // the constexpr specifier; if so, its declaration shall specify 7654 // a brace-or-equal-initializer. 7655 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 7656 // the definition of a variable [...] or the declaration of a static data 7657 // member. 7658 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 7659 if (Var->isStaticDataMember()) 7660 Diag(Var->getLocation(), 7661 diag::err_constexpr_static_mem_var_requires_init) 7662 << Var->getDeclName(); 7663 else 7664 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 7665 Var->setInvalidDecl(); 7666 return; 7667 } 7668 7669 switch (Var->isThisDeclarationADefinition()) { 7670 case VarDecl::Definition: 7671 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 7672 break; 7673 7674 // We have an out-of-line definition of a static data member 7675 // that has an in-class initializer, so we type-check this like 7676 // a declaration. 7677 // 7678 // Fall through 7679 7680 case VarDecl::DeclarationOnly: 7681 // It's only a declaration. 7682 7683 // Block scope. C99 6.7p7: If an identifier for an object is 7684 // declared with no linkage (C99 6.2.2p6), the type for the 7685 // object shall be complete. 7686 if (!Type->isDependentType() && Var->isLocalVarDecl() && 7687 !Var->getLinkage() && !Var->isInvalidDecl() && 7688 RequireCompleteType(Var->getLocation(), Type, 7689 diag::err_typecheck_decl_incomplete_type)) 7690 Var->setInvalidDecl(); 7691 7692 // Make sure that the type is not abstract. 7693 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7694 RequireNonAbstractType(Var->getLocation(), Type, 7695 diag::err_abstract_type_in_decl, 7696 AbstractVariableType)) 7697 Var->setInvalidDecl(); 7698 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7699 Var->getStorageClass() == SC_PrivateExtern) { 7700 Diag(Var->getLocation(), diag::warn_private_extern); 7701 Diag(Var->getLocation(), diag::note_private_extern); 7702 } 7703 7704 return; 7705 7706 case VarDecl::TentativeDefinition: 7707 // File scope. C99 6.9.2p2: A declaration of an identifier for an 7708 // object that has file scope without an initializer, and without a 7709 // storage-class specifier or with the storage-class specifier "static", 7710 // constitutes a tentative definition. Note: A tentative definition with 7711 // external linkage is valid (C99 6.2.2p5). 7712 if (!Var->isInvalidDecl()) { 7713 if (const IncompleteArrayType *ArrayT 7714 = Context.getAsIncompleteArrayType(Type)) { 7715 if (RequireCompleteType(Var->getLocation(), 7716 ArrayT->getElementType(), 7717 diag::err_illegal_decl_array_incomplete_type)) 7718 Var->setInvalidDecl(); 7719 } else if (Var->getStorageClass() == SC_Static) { 7720 // C99 6.9.2p3: If the declaration of an identifier for an object is 7721 // a tentative definition and has internal linkage (C99 6.2.2p3), the 7722 // declared type shall not be an incomplete type. 7723 // NOTE: code such as the following 7724 // static struct s; 7725 // struct s { int a; }; 7726 // is accepted by gcc. Hence here we issue a warning instead of 7727 // an error and we do not invalidate the static declaration. 7728 // NOTE: to avoid multiple warnings, only check the first declaration. 7729 if (Var->getPreviousDecl() == 0) 7730 RequireCompleteType(Var->getLocation(), Type, 7731 diag::ext_typecheck_decl_incomplete_type); 7732 } 7733 } 7734 7735 // Record the tentative definition; we're done. 7736 if (!Var->isInvalidDecl()) 7737 TentativeDefinitions.push_back(Var); 7738 return; 7739 } 7740 7741 // Provide a specific diagnostic for uninitialized variable 7742 // definitions with incomplete array type. 7743 if (Type->isIncompleteArrayType()) { 7744 Diag(Var->getLocation(), 7745 diag::err_typecheck_incomplete_array_needs_initializer); 7746 Var->setInvalidDecl(); 7747 return; 7748 } 7749 7750 // Provide a specific diagnostic for uninitialized variable 7751 // definitions with reference type. 7752 if (Type->isReferenceType()) { 7753 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 7754 << Var->getDeclName() 7755 << SourceRange(Var->getLocation(), Var->getLocation()); 7756 Var->setInvalidDecl(); 7757 return; 7758 } 7759 7760 // Do not attempt to type-check the default initializer for a 7761 // variable with dependent type. 7762 if (Type->isDependentType()) 7763 return; 7764 7765 if (Var->isInvalidDecl()) 7766 return; 7767 7768 if (RequireCompleteType(Var->getLocation(), 7769 Context.getBaseElementType(Type), 7770 diag::err_typecheck_decl_incomplete_type)) { 7771 Var->setInvalidDecl(); 7772 return; 7773 } 7774 7775 // The variable can not have an abstract class type. 7776 if (RequireNonAbstractType(Var->getLocation(), Type, 7777 diag::err_abstract_type_in_decl, 7778 AbstractVariableType)) { 7779 Var->setInvalidDecl(); 7780 return; 7781 } 7782 7783 // Check for jumps past the implicit initializer. C++0x 7784 // clarifies that this applies to a "variable with automatic 7785 // storage duration", not a "local variable". 7786 // C++11 [stmt.dcl]p3 7787 // A program that jumps from a point where a variable with automatic 7788 // storage duration is not in scope to a point where it is in scope is 7789 // ill-formed unless the variable has scalar type, class type with a 7790 // trivial default constructor and a trivial destructor, a cv-qualified 7791 // version of one of these types, or an array of one of the preceding 7792 // types and is declared without an initializer. 7793 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 7794 if (const RecordType *Record 7795 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 7796 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 7797 // Mark the function for further checking even if the looser rules of 7798 // C++11 do not require such checks, so that we can diagnose 7799 // incompatibilities with C++98. 7800 if (!CXXRecord->isPOD()) 7801 getCurFunction()->setHasBranchProtectedScope(); 7802 } 7803 } 7804 7805 // C++03 [dcl.init]p9: 7806 // If no initializer is specified for an object, and the 7807 // object is of (possibly cv-qualified) non-POD class type (or 7808 // array thereof), the object shall be default-initialized; if 7809 // the object is of const-qualified type, the underlying class 7810 // type shall have a user-declared default 7811 // constructor. Otherwise, if no initializer is specified for 7812 // a non- static object, the object and its subobjects, if 7813 // any, have an indeterminate initial value); if the object 7814 // or any of its subobjects are of const-qualified type, the 7815 // program is ill-formed. 7816 // C++0x [dcl.init]p11: 7817 // If no initializer is specified for an object, the object is 7818 // default-initialized; [...]. 7819 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 7820 InitializationKind Kind 7821 = InitializationKind::CreateDefault(Var->getLocation()); 7822 7823 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 7824 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg()); 7825 if (Init.isInvalid()) 7826 Var->setInvalidDecl(); 7827 else if (Init.get()) { 7828 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 7829 // This is important for template substitution. 7830 Var->setInitStyle(VarDecl::CallInit); 7831 } 7832 7833 CheckCompleteVariableDeclaration(Var); 7834 } 7835} 7836 7837void Sema::ActOnCXXForRangeDecl(Decl *D) { 7838 VarDecl *VD = dyn_cast<VarDecl>(D); 7839 if (!VD) { 7840 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 7841 D->setInvalidDecl(); 7842 return; 7843 } 7844 7845 VD->setCXXForRangeDecl(true); 7846 7847 // for-range-declaration cannot be given a storage class specifier. 7848 int Error = -1; 7849 switch (VD->getStorageClassAsWritten()) { 7850 case SC_None: 7851 break; 7852 case SC_Extern: 7853 Error = 0; 7854 break; 7855 case SC_Static: 7856 Error = 1; 7857 break; 7858 case SC_PrivateExtern: 7859 Error = 2; 7860 break; 7861 case SC_Auto: 7862 Error = 3; 7863 break; 7864 case SC_Register: 7865 Error = 4; 7866 break; 7867 case SC_OpenCLWorkGroupLocal: 7868 llvm_unreachable("Unexpected storage class"); 7869 } 7870 if (VD->isConstexpr()) 7871 Error = 5; 7872 if (Error != -1) { 7873 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 7874 << VD->getDeclName() << Error; 7875 D->setInvalidDecl(); 7876 } 7877} 7878 7879void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 7880 if (var->isInvalidDecl()) return; 7881 7882 // In ARC, don't allow jumps past the implicit initialization of a 7883 // local retaining variable. 7884 if (getLangOpts().ObjCAutoRefCount && 7885 var->hasLocalStorage()) { 7886 switch (var->getType().getObjCLifetime()) { 7887 case Qualifiers::OCL_None: 7888 case Qualifiers::OCL_ExplicitNone: 7889 case Qualifiers::OCL_Autoreleasing: 7890 break; 7891 7892 case Qualifiers::OCL_Weak: 7893 case Qualifiers::OCL_Strong: 7894 getCurFunction()->setHasBranchProtectedScope(); 7895 break; 7896 } 7897 } 7898 7899 if (var->isThisDeclarationADefinition() && 7900 var->hasExternalLinkage() && 7901 getDiagnostics().getDiagnosticLevel( 7902 diag::warn_missing_variable_declarations, 7903 var->getLocation())) { 7904 // Find a previous declaration that's not a definition. 7905 VarDecl *prev = var->getPreviousDecl(); 7906 while (prev && prev->isThisDeclarationADefinition()) 7907 prev = prev->getPreviousDecl(); 7908 7909 if (!prev) 7910 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 7911 } 7912 7913 // All the following checks are C++ only. 7914 if (!getLangOpts().CPlusPlus) return; 7915 7916 QualType type = var->getType(); 7917 if (type->isDependentType()) return; 7918 7919 // __block variables might require us to capture a copy-initializer. 7920 if (var->hasAttr<BlocksAttr>()) { 7921 // It's currently invalid to ever have a __block variable with an 7922 // array type; should we diagnose that here? 7923 7924 // Regardless, we don't want to ignore array nesting when 7925 // constructing this copy. 7926 if (type->isStructureOrClassType()) { 7927 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 7928 SourceLocation poi = var->getLocation(); 7929 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 7930 ExprResult result 7931 = PerformMoveOrCopyInitialization( 7932 InitializedEntity::InitializeBlock(poi, type, false), 7933 var, var->getType(), varRef, /*AllowNRVO=*/true); 7934 if (!result.isInvalid()) { 7935 result = MaybeCreateExprWithCleanups(result); 7936 Expr *init = result.takeAs<Expr>(); 7937 Context.setBlockVarCopyInits(var, init); 7938 } 7939 } 7940 } 7941 7942 Expr *Init = var->getInit(); 7943 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7944 QualType baseType = Context.getBaseElementType(type); 7945 7946 if (!var->getDeclContext()->isDependentContext() && 7947 Init && !Init->isValueDependent()) { 7948 if (IsGlobal && !var->isConstexpr() && 7949 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 7950 var->getLocation()) 7951 != DiagnosticsEngine::Ignored && 7952 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 7953 Diag(var->getLocation(), diag::warn_global_constructor) 7954 << Init->getSourceRange(); 7955 7956 if (var->isConstexpr()) { 7957 SmallVector<PartialDiagnosticAt, 8> Notes; 7958 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 7959 SourceLocation DiagLoc = var->getLocation(); 7960 // If the note doesn't add any useful information other than a source 7961 // location, fold it into the primary diagnostic. 7962 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 7963 diag::note_invalid_subexpr_in_const_expr) { 7964 DiagLoc = Notes[0].first; 7965 Notes.clear(); 7966 } 7967 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 7968 << var << Init->getSourceRange(); 7969 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 7970 Diag(Notes[I].first, Notes[I].second); 7971 } 7972 } else if (var->isUsableInConstantExpressions(Context)) { 7973 // Check whether the initializer of a const variable of integral or 7974 // enumeration type is an ICE now, since we can't tell whether it was 7975 // initialized by a constant expression if we check later. 7976 var->checkInitIsICE(); 7977 } 7978 } 7979 7980 // Require the destructor. 7981 if (const RecordType *recordType = baseType->getAs<RecordType>()) 7982 FinalizeVarWithDestructor(var, recordType); 7983} 7984 7985/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 7986/// any semantic actions necessary after any initializer has been attached. 7987void 7988Sema::FinalizeDeclaration(Decl *ThisDecl) { 7989 // Note that we are no longer parsing the initializer for this declaration. 7990 ParsingInitForAutoVars.erase(ThisDecl); 7991 7992 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 7993 if (!VD) 7994 return; 7995 7996 const DeclContext *DC = VD->getDeclContext(); 7997 // If there's a #pragma GCC visibility in scope, and this isn't a class 7998 // member, set the visibility of this variable. 7999 if (!DC->isRecord() && VD->hasExternalLinkage()) 8000 AddPushedVisibilityAttribute(VD); 8001 8002 if (VD->isFileVarDecl()) 8003 MarkUnusedFileScopedDecl(VD); 8004 8005 // Now we have parsed the initializer and can update the table of magic 8006 // tag values. 8007 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8008 !VD->getType()->isIntegralOrEnumerationType()) 8009 return; 8010 8011 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8012 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8013 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8014 I != E; ++I) { 8015 const Expr *MagicValueExpr = VD->getInit(); 8016 if (!MagicValueExpr) { 8017 continue; 8018 } 8019 llvm::APSInt MagicValueInt; 8020 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8021 Diag(I->getRange().getBegin(), 8022 diag::err_type_tag_for_datatype_not_ice) 8023 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8024 continue; 8025 } 8026 if (MagicValueInt.getActiveBits() > 64) { 8027 Diag(I->getRange().getBegin(), 8028 diag::err_type_tag_for_datatype_too_large) 8029 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8030 continue; 8031 } 8032 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8033 RegisterTypeTagForDatatype(I->getArgumentKind(), 8034 MagicValue, 8035 I->getMatchingCType(), 8036 I->getLayoutCompatible(), 8037 I->getMustBeNull()); 8038 } 8039} 8040 8041Sema::DeclGroupPtrTy 8042Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8043 Decl **Group, unsigned NumDecls) { 8044 SmallVector<Decl*, 8> Decls; 8045 8046 if (DS.isTypeSpecOwned()) 8047 Decls.push_back(DS.getRepAsDecl()); 8048 8049 for (unsigned i = 0; i != NumDecls; ++i) 8050 if (Decl *D = Group[i]) 8051 Decls.push_back(D); 8052 8053 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) 8054 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) 8055 getASTContext().addUnnamedTag(Tag); 8056 8057 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 8058 DS.getTypeSpecType() == DeclSpec::TST_auto); 8059} 8060 8061/// BuildDeclaratorGroup - convert a list of declarations into a declaration 8062/// group, performing any necessary semantic checking. 8063Sema::DeclGroupPtrTy 8064Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 8065 bool TypeMayContainAuto) { 8066 // C++0x [dcl.spec.auto]p7: 8067 // If the type deduced for the template parameter U is not the same in each 8068 // deduction, the program is ill-formed. 8069 // FIXME: When initializer-list support is added, a distinction is needed 8070 // between the deduced type U and the deduced type which 'auto' stands for. 8071 // auto a = 0, b = { 1, 2, 3 }; 8072 // is legal because the deduced type U is 'int' in both cases. 8073 if (TypeMayContainAuto && NumDecls > 1) { 8074 QualType Deduced; 8075 CanQualType DeducedCanon; 8076 VarDecl *DeducedDecl = 0; 8077 for (unsigned i = 0; i != NumDecls; ++i) { 8078 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 8079 AutoType *AT = D->getType()->getContainedAutoType(); 8080 // Don't reissue diagnostics when instantiating a template. 8081 if (AT && D->isInvalidDecl()) 8082 break; 8083 if (AT && AT->isDeduced()) { 8084 QualType U = AT->getDeducedType(); 8085 CanQualType UCanon = Context.getCanonicalType(U); 8086 if (Deduced.isNull()) { 8087 Deduced = U; 8088 DeducedCanon = UCanon; 8089 DeducedDecl = D; 8090 } else if (DeducedCanon != UCanon) { 8091 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 8092 diag::err_auto_different_deductions) 8093 << Deduced << DeducedDecl->getDeclName() 8094 << U << D->getDeclName() 8095 << DeducedDecl->getInit()->getSourceRange() 8096 << D->getInit()->getSourceRange(); 8097 D->setInvalidDecl(); 8098 break; 8099 } 8100 } 8101 } 8102 } 8103 } 8104 8105 ActOnDocumentableDecls(Group, NumDecls); 8106 8107 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 8108} 8109 8110void Sema::ActOnDocumentableDecl(Decl *D) { 8111 ActOnDocumentableDecls(&D, 1); 8112} 8113 8114void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 8115 // Don't parse the comment if Doxygen diagnostics are ignored. 8116 if (NumDecls == 0 || !Group[0]) 8117 return; 8118 8119 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 8120 Group[0]->getLocation()) 8121 == DiagnosticsEngine::Ignored) 8122 return; 8123 8124 if (NumDecls >= 2) { 8125 // This is a decl group. Normally it will contain only declarations 8126 // procuded from declarator list. But in case we have any definitions or 8127 // additional declaration references: 8128 // 'typedef struct S {} S;' 8129 // 'typedef struct S *S;' 8130 // 'struct S *pS;' 8131 // FinalizeDeclaratorGroup adds these as separate declarations. 8132 Decl *MaybeTagDecl = Group[0]; 8133 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 8134 Group++; 8135 NumDecls--; 8136 } 8137 } 8138 8139 // See if there are any new comments that are not attached to a decl. 8140 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 8141 if (!Comments.empty() && 8142 !Comments.back()->isAttached()) { 8143 // There is at least one comment that not attached to a decl. 8144 // Maybe it should be attached to one of these decls? 8145 // 8146 // Note that this way we pick up not only comments that precede the 8147 // declaration, but also comments that *follow* the declaration -- thanks to 8148 // the lookahead in the lexer: we've consumed the semicolon and looked 8149 // ahead through comments. 8150 for (unsigned i = 0; i != NumDecls; ++i) 8151 Context.getCommentForDecl(Group[i], &PP); 8152 } 8153} 8154 8155/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 8156/// to introduce parameters into function prototype scope. 8157Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 8158 const DeclSpec &DS = D.getDeclSpec(); 8159 8160 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 8161 // C++03 [dcl.stc]p2 also permits 'auto'. 8162 VarDecl::StorageClass StorageClass = SC_None; 8163 VarDecl::StorageClass StorageClassAsWritten = SC_None; 8164 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 8165 StorageClass = SC_Register; 8166 StorageClassAsWritten = SC_Register; 8167 } else if (getLangOpts().CPlusPlus && 8168 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 8169 StorageClass = SC_Auto; 8170 StorageClassAsWritten = SC_Auto; 8171 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 8172 Diag(DS.getStorageClassSpecLoc(), 8173 diag::err_invalid_storage_class_in_func_decl); 8174 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8175 } 8176 8177 if (D.getDeclSpec().isThreadSpecified()) 8178 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 8179 if (D.getDeclSpec().isConstexprSpecified()) 8180 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 8181 << 0; 8182 8183 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 8184 8185 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8186 QualType parmDeclType = TInfo->getType(); 8187 8188 if (getLangOpts().CPlusPlus) { 8189 // Check that there are no default arguments inside the type of this 8190 // parameter. 8191 CheckExtraCXXDefaultArguments(D); 8192 8193 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 8194 if (D.getCXXScopeSpec().isSet()) { 8195 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 8196 << D.getCXXScopeSpec().getRange(); 8197 D.getCXXScopeSpec().clear(); 8198 } 8199 } 8200 8201 // Ensure we have a valid name 8202 IdentifierInfo *II = 0; 8203 if (D.hasName()) { 8204 II = D.getIdentifier(); 8205 if (!II) { 8206 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 8207 << GetNameForDeclarator(D).getName().getAsString(); 8208 D.setInvalidType(true); 8209 } 8210 } 8211 8212 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 8213 if (II) { 8214 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 8215 ForRedeclaration); 8216 LookupName(R, S); 8217 if (R.isSingleResult()) { 8218 NamedDecl *PrevDecl = R.getFoundDecl(); 8219 if (PrevDecl->isTemplateParameter()) { 8220 // Maybe we will complain about the shadowed template parameter. 8221 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8222 // Just pretend that we didn't see the previous declaration. 8223 PrevDecl = 0; 8224 } else if (S->isDeclScope(PrevDecl)) { 8225 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 8226 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8227 8228 // Recover by removing the name 8229 II = 0; 8230 D.SetIdentifier(0, D.getIdentifierLoc()); 8231 D.setInvalidType(true); 8232 } 8233 } 8234 } 8235 8236 // Temporarily put parameter variables in the translation unit, not 8237 // the enclosing context. This prevents them from accidentally 8238 // looking like class members in C++. 8239 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 8240 D.getLocStart(), 8241 D.getIdentifierLoc(), II, 8242 parmDeclType, TInfo, 8243 StorageClass, StorageClassAsWritten); 8244 8245 if (D.isInvalidType()) 8246 New->setInvalidDecl(); 8247 8248 assert(S->isFunctionPrototypeScope()); 8249 assert(S->getFunctionPrototypeDepth() >= 1); 8250 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 8251 S->getNextFunctionPrototypeIndex()); 8252 8253 // Add the parameter declaration into this scope. 8254 S->AddDecl(New); 8255 if (II) 8256 IdResolver.AddDecl(New); 8257 8258 ProcessDeclAttributes(S, New, D); 8259 8260 if (D.getDeclSpec().isModulePrivateSpecified()) 8261 Diag(New->getLocation(), diag::err_module_private_local) 8262 << 1 << New->getDeclName() 8263 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8264 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8265 8266 if (New->hasAttr<BlocksAttr>()) { 8267 Diag(New->getLocation(), diag::err_block_on_nonlocal); 8268 } 8269 return New; 8270} 8271 8272/// \brief Synthesizes a variable for a parameter arising from a 8273/// typedef. 8274ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 8275 SourceLocation Loc, 8276 QualType T) { 8277 /* FIXME: setting StartLoc == Loc. 8278 Would it be worth to modify callers so as to provide proper source 8279 location for the unnamed parameters, embedding the parameter's type? */ 8280 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 8281 T, Context.getTrivialTypeSourceInfo(T, Loc), 8282 SC_None, SC_None, 0); 8283 Param->setImplicit(); 8284 return Param; 8285} 8286 8287void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 8288 ParmVarDecl * const *ParamEnd) { 8289 // Don't diagnose unused-parameter errors in template instantiations; we 8290 // will already have done so in the template itself. 8291 if (!ActiveTemplateInstantiations.empty()) 8292 return; 8293 8294 for (; Param != ParamEnd; ++Param) { 8295 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 8296 !(*Param)->hasAttr<UnusedAttr>()) { 8297 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 8298 << (*Param)->getDeclName(); 8299 } 8300 } 8301} 8302 8303void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 8304 ParmVarDecl * const *ParamEnd, 8305 QualType ReturnTy, 8306 NamedDecl *D) { 8307 if (LangOpts.NumLargeByValueCopy == 0) // No check. 8308 return; 8309 8310 // Warn if the return value is pass-by-value and larger than the specified 8311 // threshold. 8312 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 8313 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 8314 if (Size > LangOpts.NumLargeByValueCopy) 8315 Diag(D->getLocation(), diag::warn_return_value_size) 8316 << D->getDeclName() << Size; 8317 } 8318 8319 // Warn if any parameter is pass-by-value and larger than the specified 8320 // threshold. 8321 for (; Param != ParamEnd; ++Param) { 8322 QualType T = (*Param)->getType(); 8323 if (T->isDependentType() || !T.isPODType(Context)) 8324 continue; 8325 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 8326 if (Size > LangOpts.NumLargeByValueCopy) 8327 Diag((*Param)->getLocation(), diag::warn_parameter_size) 8328 << (*Param)->getDeclName() << Size; 8329 } 8330} 8331 8332ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 8333 SourceLocation NameLoc, IdentifierInfo *Name, 8334 QualType T, TypeSourceInfo *TSInfo, 8335 VarDecl::StorageClass StorageClass, 8336 VarDecl::StorageClass StorageClassAsWritten) { 8337 // In ARC, infer a lifetime qualifier for appropriate parameter types. 8338 if (getLangOpts().ObjCAutoRefCount && 8339 T.getObjCLifetime() == Qualifiers::OCL_None && 8340 T->isObjCLifetimeType()) { 8341 8342 Qualifiers::ObjCLifetime lifetime; 8343 8344 // Special cases for arrays: 8345 // - if it's const, use __unsafe_unretained 8346 // - otherwise, it's an error 8347 if (T->isArrayType()) { 8348 if (!T.isConstQualified()) { 8349 DelayedDiagnostics.add( 8350 sema::DelayedDiagnostic::makeForbiddenType( 8351 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 8352 } 8353 lifetime = Qualifiers::OCL_ExplicitNone; 8354 } else { 8355 lifetime = T->getObjCARCImplicitLifetime(); 8356 } 8357 T = Context.getLifetimeQualifiedType(T, lifetime); 8358 } 8359 8360 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 8361 Context.getAdjustedParameterType(T), 8362 TSInfo, 8363 StorageClass, StorageClassAsWritten, 8364 0); 8365 8366 // Parameters can not be abstract class types. 8367 // For record types, this is done by the AbstractClassUsageDiagnoser once 8368 // the class has been completely parsed. 8369 if (!CurContext->isRecord() && 8370 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 8371 AbstractParamType)) 8372 New->setInvalidDecl(); 8373 8374 // Parameter declarators cannot be interface types. All ObjC objects are 8375 // passed by reference. 8376 if (T->isObjCObjectType()) { 8377 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 8378 Diag(NameLoc, 8379 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 8380 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 8381 T = Context.getObjCObjectPointerType(T); 8382 New->setType(T); 8383 } 8384 8385 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 8386 // duration shall not be qualified by an address-space qualifier." 8387 // Since all parameters have automatic store duration, they can not have 8388 // an address space. 8389 if (T.getAddressSpace() != 0) { 8390 Diag(NameLoc, diag::err_arg_with_address_space); 8391 New->setInvalidDecl(); 8392 } 8393 8394 return New; 8395} 8396 8397void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 8398 SourceLocation LocAfterDecls) { 8399 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8400 8401 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 8402 // for a K&R function. 8403 if (!FTI.hasPrototype) { 8404 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 8405 --i; 8406 if (FTI.ArgInfo[i].Param == 0) { 8407 SmallString<256> Code; 8408 llvm::raw_svector_ostream(Code) << " int " 8409 << FTI.ArgInfo[i].Ident->getName() 8410 << ";\n"; 8411 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 8412 << FTI.ArgInfo[i].Ident 8413 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 8414 8415 // Implicitly declare the argument as type 'int' for lack of a better 8416 // type. 8417 AttributeFactory attrs; 8418 DeclSpec DS(attrs); 8419 const char* PrevSpec; // unused 8420 unsigned DiagID; // unused 8421 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 8422 PrevSpec, DiagID); 8423 // Use the identifier location for the type source range. 8424 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 8425 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 8426 Declarator ParamD(DS, Declarator::KNRTypeListContext); 8427 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 8428 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 8429 } 8430 } 8431 } 8432} 8433 8434Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 8435 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 8436 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 8437 Scope *ParentScope = FnBodyScope->getParent(); 8438 8439 D.setFunctionDefinitionKind(FDK_Definition); 8440 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 8441 return ActOnStartOfFunctionDef(FnBodyScope, DP); 8442} 8443 8444static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 8445 const FunctionDecl*& PossibleZeroParamPrototype) { 8446 // Don't warn about invalid declarations. 8447 if (FD->isInvalidDecl()) 8448 return false; 8449 8450 // Or declarations that aren't global. 8451 if (!FD->isGlobal()) 8452 return false; 8453 8454 // Don't warn about C++ member functions. 8455 if (isa<CXXMethodDecl>(FD)) 8456 return false; 8457 8458 // Don't warn about 'main'. 8459 if (FD->isMain()) 8460 return false; 8461 8462 // Don't warn about inline functions. 8463 if (FD->isInlined()) 8464 return false; 8465 8466 // Don't warn about function templates. 8467 if (FD->getDescribedFunctionTemplate()) 8468 return false; 8469 8470 // Don't warn about function template specializations. 8471 if (FD->isFunctionTemplateSpecialization()) 8472 return false; 8473 8474 // Don't warn for OpenCL kernels. 8475 if (FD->hasAttr<OpenCLKernelAttr>()) 8476 return false; 8477 8478 bool MissingPrototype = true; 8479 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 8480 Prev; Prev = Prev->getPreviousDecl()) { 8481 // Ignore any declarations that occur in function or method 8482 // scope, because they aren't visible from the header. 8483 if (Prev->getDeclContext()->isFunctionOrMethod()) 8484 continue; 8485 8486 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 8487 if (FD->getNumParams() == 0) 8488 PossibleZeroParamPrototype = Prev; 8489 break; 8490 } 8491 8492 return MissingPrototype; 8493} 8494 8495void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 8496 // Don't complain if we're in GNU89 mode and the previous definition 8497 // was an extern inline function. 8498 const FunctionDecl *Definition; 8499 if (FD->isDefined(Definition) && 8500 !canRedefineFunction(Definition, getLangOpts())) { 8501 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 8502 Definition->getStorageClass() == SC_Extern) 8503 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 8504 << FD->getDeclName() << getLangOpts().CPlusPlus; 8505 else 8506 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 8507 Diag(Definition->getLocation(), diag::note_previous_definition); 8508 FD->setInvalidDecl(); 8509 } 8510} 8511 8512Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 8513 // Clear the last template instantiation error context. 8514 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 8515 8516 if (!D) 8517 return D; 8518 FunctionDecl *FD = 0; 8519 8520 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 8521 FD = FunTmpl->getTemplatedDecl(); 8522 else 8523 FD = cast<FunctionDecl>(D); 8524 8525 // Enter a new function scope 8526 PushFunctionScope(); 8527 8528 // See if this is a redefinition. 8529 if (!FD->isLateTemplateParsed()) 8530 CheckForFunctionRedefinition(FD); 8531 8532 // Builtin functions cannot be defined. 8533 if (unsigned BuiltinID = FD->getBuiltinID()) { 8534 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 8535 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 8536 FD->setInvalidDecl(); 8537 } 8538 } 8539 8540 // The return type of a function definition must be complete 8541 // (C99 6.9.1p3, C++ [dcl.fct]p6). 8542 QualType ResultType = FD->getResultType(); 8543 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 8544 !FD->isInvalidDecl() && 8545 RequireCompleteType(FD->getLocation(), ResultType, 8546 diag::err_func_def_incomplete_result)) 8547 FD->setInvalidDecl(); 8548 8549 // GNU warning -Wmissing-prototypes: 8550 // Warn if a global function is defined without a previous 8551 // prototype declaration. This warning is issued even if the 8552 // definition itself provides a prototype. The aim is to detect 8553 // global functions that fail to be declared in header files. 8554 const FunctionDecl *PossibleZeroParamPrototype = 0; 8555 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 8556 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 8557 8558 if (PossibleZeroParamPrototype) { 8559 // We found a declaration that is not a prototype, 8560 // but that could be a zero-parameter prototype 8561 TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo(); 8562 TypeLoc TL = TI->getTypeLoc(); 8563 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 8564 Diag(PossibleZeroParamPrototype->getLocation(), 8565 diag::note_declaration_not_a_prototype) 8566 << PossibleZeroParamPrototype 8567 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 8568 } 8569 } 8570 8571 if (FnBodyScope) 8572 PushDeclContext(FnBodyScope, FD); 8573 8574 // Check the validity of our function parameters 8575 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 8576 /*CheckParameterNames=*/true); 8577 8578 // Introduce our parameters into the function scope 8579 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 8580 ParmVarDecl *Param = FD->getParamDecl(p); 8581 Param->setOwningFunction(FD); 8582 8583 // If this has an identifier, add it to the scope stack. 8584 if (Param->getIdentifier() && FnBodyScope) { 8585 CheckShadow(FnBodyScope, Param); 8586 8587 PushOnScopeChains(Param, FnBodyScope); 8588 } 8589 } 8590 8591 // If we had any tags defined in the function prototype, 8592 // introduce them into the function scope. 8593 if (FnBodyScope) { 8594 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 8595 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 8596 NamedDecl *D = *I; 8597 8598 // Some of these decls (like enums) may have been pinned to the translation unit 8599 // for lack of a real context earlier. If so, remove from the translation unit 8600 // and reattach to the current context. 8601 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 8602 // Is the decl actually in the context? 8603 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 8604 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 8605 if (*DI == D) { 8606 Context.getTranslationUnitDecl()->removeDecl(D); 8607 break; 8608 } 8609 } 8610 // Either way, reassign the lexical decl context to our FunctionDecl. 8611 D->setLexicalDeclContext(CurContext); 8612 } 8613 8614 // If the decl has a non-null name, make accessible in the current scope. 8615 if (!D->getName().empty()) 8616 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 8617 8618 // Similarly, dive into enums and fish their constants out, making them 8619 // accessible in this scope. 8620 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 8621 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 8622 EE = ED->enumerator_end(); EI != EE; ++EI) 8623 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 8624 } 8625 } 8626 } 8627 8628 // Ensure that the function's exception specification is instantiated. 8629 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 8630 ResolveExceptionSpec(D->getLocation(), FPT); 8631 8632 // Checking attributes of current function definition 8633 // dllimport attribute. 8634 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 8635 if (DA && (!FD->getAttr<DLLExportAttr>())) { 8636 // dllimport attribute cannot be directly applied to definition. 8637 // Microsoft accepts dllimport for functions defined within class scope. 8638 if (!DA->isInherited() && 8639 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 8640 Diag(FD->getLocation(), 8641 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 8642 << "dllimport"; 8643 FD->setInvalidDecl(); 8644 return D; 8645 } 8646 8647 // Visual C++ appears to not think this is an issue, so only issue 8648 // a warning when Microsoft extensions are disabled. 8649 if (!LangOpts.MicrosoftExt) { 8650 // If a symbol previously declared dllimport is later defined, the 8651 // attribute is ignored in subsequent references, and a warning is 8652 // emitted. 8653 Diag(FD->getLocation(), 8654 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 8655 << FD->getName() << "dllimport"; 8656 } 8657 } 8658 // We want to attach documentation to original Decl (which might be 8659 // a function template). 8660 ActOnDocumentableDecl(D); 8661 return D; 8662} 8663 8664/// \brief Given the set of return statements within a function body, 8665/// compute the variables that are subject to the named return value 8666/// optimization. 8667/// 8668/// Each of the variables that is subject to the named return value 8669/// optimization will be marked as NRVO variables in the AST, and any 8670/// return statement that has a marked NRVO variable as its NRVO candidate can 8671/// use the named return value optimization. 8672/// 8673/// This function applies a very simplistic algorithm for NRVO: if every return 8674/// statement in the function has the same NRVO candidate, that candidate is 8675/// the NRVO variable. 8676/// 8677/// FIXME: Employ a smarter algorithm that accounts for multiple return 8678/// statements and the lifetimes of the NRVO candidates. We should be able to 8679/// find a maximal set of NRVO variables. 8680void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 8681 ReturnStmt **Returns = Scope->Returns.data(); 8682 8683 const VarDecl *NRVOCandidate = 0; 8684 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 8685 if (!Returns[I]->getNRVOCandidate()) 8686 return; 8687 8688 if (!NRVOCandidate) 8689 NRVOCandidate = Returns[I]->getNRVOCandidate(); 8690 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 8691 return; 8692 } 8693 8694 if (NRVOCandidate) 8695 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 8696} 8697 8698bool Sema::canSkipFunctionBody(Decl *D) { 8699 if (!Consumer.shouldSkipFunctionBody(D)) 8700 return false; 8701 8702 if (isa<ObjCMethodDecl>(D)) 8703 return true; 8704 8705 FunctionDecl *FD = 0; 8706 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 8707 FD = FTD->getTemplatedDecl(); 8708 else 8709 FD = cast<FunctionDecl>(D); 8710 8711 // We cannot skip the body of a function (or function template) which is 8712 // constexpr, since we may need to evaluate its body in order to parse the 8713 // rest of the file. 8714 return !FD->isConstexpr(); 8715} 8716 8717Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 8718 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 8719 FD->setHasSkippedBody(); 8720 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 8721 MD->setHasSkippedBody(); 8722 return ActOnFinishFunctionBody(Decl, 0); 8723} 8724 8725Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 8726 return ActOnFinishFunctionBody(D, BodyArg, false); 8727} 8728 8729Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 8730 bool IsInstantiation) { 8731 FunctionDecl *FD = 0; 8732 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 8733 if (FunTmpl) 8734 FD = FunTmpl->getTemplatedDecl(); 8735 else 8736 FD = dyn_cast_or_null<FunctionDecl>(dcl); 8737 8738 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 8739 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 8740 8741 if (FD) { 8742 FD->setBody(Body); 8743 8744 // The only way to be included in UndefinedButUsed is if there is an 8745 // ODR use before the definition. Avoid the expensive map lookup if this 8746 // is the first declaration. 8747 if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) { 8748 if (FD->getLinkage() != ExternalLinkage) 8749 UndefinedButUsed.erase(FD); 8750 else if (FD->isInlined() && 8751 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 8752 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 8753 UndefinedButUsed.erase(FD); 8754 } 8755 8756 // If the function implicitly returns zero (like 'main') or is naked, 8757 // don't complain about missing return statements. 8758 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 8759 WP.disableCheckFallThrough(); 8760 8761 // MSVC permits the use of pure specifier (=0) on function definition, 8762 // defined at class scope, warn about this non standard construct. 8763 if (getLangOpts().MicrosoftExt && FD->isPure()) 8764 Diag(FD->getLocation(), diag::warn_pure_function_definition); 8765 8766 if (!FD->isInvalidDecl()) { 8767 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 8768 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 8769 FD->getResultType(), FD); 8770 8771 // If this is a constructor, we need a vtable. 8772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 8773 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 8774 8775 // Try to apply the named return value optimization. We have to check 8776 // if we can do this here because lambdas keep return statements around 8777 // to deduce an implicit return type. 8778 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 8779 !FD->isDependentContext()) 8780 computeNRVO(Body, getCurFunction()); 8781 } 8782 8783 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 8784 "Function parsing confused"); 8785 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 8786 assert(MD == getCurMethodDecl() && "Method parsing confused"); 8787 MD->setBody(Body); 8788 if (!MD->isInvalidDecl()) { 8789 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 8790 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 8791 MD->getResultType(), MD); 8792 8793 if (Body) 8794 computeNRVO(Body, getCurFunction()); 8795 } 8796 if (getCurFunction()->ObjCShouldCallSuper) { 8797 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 8798 << MD->getSelector().getAsString(); 8799 getCurFunction()->ObjCShouldCallSuper = false; 8800 } 8801 } else { 8802 return 0; 8803 } 8804 8805 assert(!getCurFunction()->ObjCShouldCallSuper && 8806 "This should only be set for ObjC methods, which should have been " 8807 "handled in the block above."); 8808 8809 // Verify and clean out per-function state. 8810 if (Body) { 8811 // C++ constructors that have function-try-blocks can't have return 8812 // statements in the handlers of that block. (C++ [except.handle]p14) 8813 // Verify this. 8814 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 8815 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 8816 8817 // Verify that gotos and switch cases don't jump into scopes illegally. 8818 if (getCurFunction()->NeedsScopeChecking() && 8819 !dcl->isInvalidDecl() && 8820 !hasAnyUnrecoverableErrorsInThisFunction() && 8821 !PP.isCodeCompletionEnabled()) 8822 DiagnoseInvalidJumps(Body); 8823 8824 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 8825 if (!Destructor->getParent()->isDependentType()) 8826 CheckDestructor(Destructor); 8827 8828 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8829 Destructor->getParent()); 8830 } 8831 8832 // If any errors have occurred, clear out any temporaries that may have 8833 // been leftover. This ensures that these temporaries won't be picked up for 8834 // deletion in some later function. 8835 if (PP.getDiagnostics().hasErrorOccurred() || 8836 PP.getDiagnostics().getSuppressAllDiagnostics()) { 8837 DiscardCleanupsInEvaluationContext(); 8838 } 8839 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 8840 !isa<FunctionTemplateDecl>(dcl)) { 8841 // Since the body is valid, issue any analysis-based warnings that are 8842 // enabled. 8843 ActivePolicy = &WP; 8844 } 8845 8846 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 8847 (!CheckConstexprFunctionDecl(FD) || 8848 !CheckConstexprFunctionBody(FD, Body))) 8849 FD->setInvalidDecl(); 8850 8851 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 8852 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 8853 assert(MaybeODRUseExprs.empty() && 8854 "Leftover expressions for odr-use checking"); 8855 } 8856 8857 if (!IsInstantiation) 8858 PopDeclContext(); 8859 8860 PopFunctionScopeInfo(ActivePolicy, dcl); 8861 8862 // If any errors have occurred, clear out any temporaries that may have 8863 // been leftover. This ensures that these temporaries won't be picked up for 8864 // deletion in some later function. 8865 if (getDiagnostics().hasErrorOccurred()) { 8866 DiscardCleanupsInEvaluationContext(); 8867 } 8868 8869 return dcl; 8870} 8871 8872 8873/// When we finish delayed parsing of an attribute, we must attach it to the 8874/// relevant Decl. 8875void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 8876 ParsedAttributes &Attrs) { 8877 // Always attach attributes to the underlying decl. 8878 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8879 D = TD->getTemplatedDecl(); 8880 ProcessDeclAttributeList(S, D, Attrs.getList()); 8881 8882 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 8883 if (Method->isStatic()) 8884 checkThisInStaticMemberFunctionAttributes(Method); 8885} 8886 8887 8888/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 8889/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 8890NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 8891 IdentifierInfo &II, Scope *S) { 8892 // Before we produce a declaration for an implicitly defined 8893 // function, see whether there was a locally-scoped declaration of 8894 // this name as a function or variable. If so, use that 8895 // (non-visible) declaration, and complain about it. 8896 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 8897 = findLocallyScopedExternCDecl(&II); 8898 if (Pos != LocallyScopedExternCDecls.end()) { 8899 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 8900 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 8901 return Pos->second; 8902 } 8903 8904 // Extension in C99. Legal in C90, but warn about it. 8905 unsigned diag_id; 8906 if (II.getName().startswith("__builtin_")) 8907 diag_id = diag::warn_builtin_unknown; 8908 else if (getLangOpts().C99) 8909 diag_id = diag::ext_implicit_function_decl; 8910 else 8911 diag_id = diag::warn_implicit_function_decl; 8912 Diag(Loc, diag_id) << &II; 8913 8914 // Because typo correction is expensive, only do it if the implicit 8915 // function declaration is going to be treated as an error. 8916 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 8917 TypoCorrection Corrected; 8918 DeclFilterCCC<FunctionDecl> Validator; 8919 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 8920 LookupOrdinaryName, S, 0, Validator))) { 8921 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 8922 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 8923 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 8924 8925 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 8926 << FixItHint::CreateReplacement(Loc, CorrectedStr); 8927 8928 if (Func->getLocation().isValid() 8929 && !II.getName().startswith("__builtin_")) 8930 Diag(Func->getLocation(), diag::note_previous_decl) 8931 << CorrectedQuotedStr; 8932 } 8933 } 8934 8935 // Set a Declarator for the implicit definition: int foo(); 8936 const char *Dummy; 8937 AttributeFactory attrFactory; 8938 DeclSpec DS(attrFactory); 8939 unsigned DiagID; 8940 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 8941 (void)Error; // Silence warning. 8942 assert(!Error && "Error setting up implicit decl!"); 8943 SourceLocation NoLoc; 8944 Declarator D(DS, Declarator::BlockContext); 8945 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 8946 /*IsAmbiguous=*/false, 8947 /*RParenLoc=*/NoLoc, 8948 /*ArgInfo=*/0, 8949 /*NumArgs=*/0, 8950 /*EllipsisLoc=*/NoLoc, 8951 /*RParenLoc=*/NoLoc, 8952 /*TypeQuals=*/0, 8953 /*RefQualifierIsLvalueRef=*/true, 8954 /*RefQualifierLoc=*/NoLoc, 8955 /*ConstQualifierLoc=*/NoLoc, 8956 /*VolatileQualifierLoc=*/NoLoc, 8957 /*MutableLoc=*/NoLoc, 8958 EST_None, 8959 /*ESpecLoc=*/NoLoc, 8960 /*Exceptions=*/0, 8961 /*ExceptionRanges=*/0, 8962 /*NumExceptions=*/0, 8963 /*NoexceptExpr=*/0, 8964 Loc, Loc, D), 8965 DS.getAttributes(), 8966 SourceLocation()); 8967 D.SetIdentifier(&II, Loc); 8968 8969 // Insert this function into translation-unit scope. 8970 8971 DeclContext *PrevDC = CurContext; 8972 CurContext = Context.getTranslationUnitDecl(); 8973 8974 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 8975 FD->setImplicit(); 8976 8977 CurContext = PrevDC; 8978 8979 AddKnownFunctionAttributes(FD); 8980 8981 return FD; 8982} 8983 8984/// \brief Adds any function attributes that we know a priori based on 8985/// the declaration of this function. 8986/// 8987/// These attributes can apply both to implicitly-declared builtins 8988/// (like __builtin___printf_chk) or to library-declared functions 8989/// like NSLog or printf. 8990/// 8991/// We need to check for duplicate attributes both here and where user-written 8992/// attributes are applied to declarations. 8993void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 8994 if (FD->isInvalidDecl()) 8995 return; 8996 8997 // If this is a built-in function, map its builtin attributes to 8998 // actual attributes. 8999 if (unsigned BuiltinID = FD->getBuiltinID()) { 9000 // Handle printf-formatting attributes. 9001 unsigned FormatIdx; 9002 bool HasVAListArg; 9003 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 9004 if (!FD->getAttr<FormatAttr>()) { 9005 const char *fmt = "printf"; 9006 unsigned int NumParams = FD->getNumParams(); 9007 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 9008 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 9009 fmt = "NSString"; 9010 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9011 fmt, FormatIdx+1, 9012 HasVAListArg ? 0 : FormatIdx+2)); 9013 } 9014 } 9015 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 9016 HasVAListArg)) { 9017 if (!FD->getAttr<FormatAttr>()) 9018 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9019 "scanf", FormatIdx+1, 9020 HasVAListArg ? 0 : FormatIdx+2)); 9021 } 9022 9023 // Mark const if we don't care about errno and that is the only 9024 // thing preventing the function from being const. This allows 9025 // IRgen to use LLVM intrinsics for such functions. 9026 if (!getLangOpts().MathErrno && 9027 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 9028 if (!FD->getAttr<ConstAttr>()) 9029 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9030 } 9031 9032 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 9033 !FD->getAttr<ReturnsTwiceAttr>()) 9034 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 9035 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 9036 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 9037 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 9038 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9039 } 9040 9041 IdentifierInfo *Name = FD->getIdentifier(); 9042 if (!Name) 9043 return; 9044 if ((!getLangOpts().CPlusPlus && 9045 FD->getDeclContext()->isTranslationUnit()) || 9046 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 9047 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 9048 LinkageSpecDecl::lang_c)) { 9049 // Okay: this could be a libc/libm/Objective-C function we know 9050 // about. 9051 } else 9052 return; 9053 9054 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 9055 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 9056 // target-specific builtins, perhaps? 9057 if (!FD->getAttr<FormatAttr>()) 9058 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9059 "printf", 2, 9060 Name->isStr("vasprintf") ? 0 : 3)); 9061 } 9062 9063 if (Name->isStr("__CFStringMakeConstantString")) { 9064 // We already have a __builtin___CFStringMakeConstantString, 9065 // but builds that use -fno-constant-cfstrings don't go through that. 9066 if (!FD->getAttr<FormatArgAttr>()) 9067 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 9068 } 9069} 9070 9071TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 9072 TypeSourceInfo *TInfo) { 9073 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 9074 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 9075 9076 if (!TInfo) { 9077 assert(D.isInvalidType() && "no declarator info for valid type"); 9078 TInfo = Context.getTrivialTypeSourceInfo(T); 9079 } 9080 9081 // Scope manipulation handled by caller. 9082 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 9083 D.getLocStart(), 9084 D.getIdentifierLoc(), 9085 D.getIdentifier(), 9086 TInfo); 9087 9088 // Bail out immediately if we have an invalid declaration. 9089 if (D.isInvalidType()) { 9090 NewTD->setInvalidDecl(); 9091 return NewTD; 9092 } 9093 9094 if (D.getDeclSpec().isModulePrivateSpecified()) { 9095 if (CurContext->isFunctionOrMethod()) 9096 Diag(NewTD->getLocation(), diag::err_module_private_local) 9097 << 2 << NewTD->getDeclName() 9098 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9099 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9100 else 9101 NewTD->setModulePrivate(); 9102 } 9103 9104 // C++ [dcl.typedef]p8: 9105 // If the typedef declaration defines an unnamed class (or 9106 // enum), the first typedef-name declared by the declaration 9107 // to be that class type (or enum type) is used to denote the 9108 // class type (or enum type) for linkage purposes only. 9109 // We need to check whether the type was declared in the declaration. 9110 switch (D.getDeclSpec().getTypeSpecType()) { 9111 case TST_enum: 9112 case TST_struct: 9113 case TST_interface: 9114 case TST_union: 9115 case TST_class: { 9116 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 9117 9118 // Do nothing if the tag is not anonymous or already has an 9119 // associated typedef (from an earlier typedef in this decl group). 9120 if (tagFromDeclSpec->getIdentifier()) break; 9121 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 9122 9123 // A well-formed anonymous tag must always be a TUK_Definition. 9124 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 9125 9126 // The type must match the tag exactly; no qualifiers allowed. 9127 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 9128 break; 9129 9130 // Otherwise, set this is the anon-decl typedef for the tag. 9131 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 9132 break; 9133 } 9134 9135 default: 9136 break; 9137 } 9138 9139 return NewTD; 9140} 9141 9142 9143/// \brief Check that this is a valid underlying type for an enum declaration. 9144bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 9145 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 9146 QualType T = TI->getType(); 9147 9148 if (T->isDependentType()) 9149 return false; 9150 9151 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 9152 if (BT->isInteger()) 9153 return false; 9154 9155 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 9156 return true; 9157} 9158 9159/// Check whether this is a valid redeclaration of a previous enumeration. 9160/// \return true if the redeclaration was invalid. 9161bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 9162 QualType EnumUnderlyingTy, 9163 const EnumDecl *Prev) { 9164 bool IsFixed = !EnumUnderlyingTy.isNull(); 9165 9166 if (IsScoped != Prev->isScoped()) { 9167 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 9168 << Prev->isScoped(); 9169 Diag(Prev->getLocation(), diag::note_previous_use); 9170 return true; 9171 } 9172 9173 if (IsFixed && Prev->isFixed()) { 9174 if (!EnumUnderlyingTy->isDependentType() && 9175 !Prev->getIntegerType()->isDependentType() && 9176 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 9177 Prev->getIntegerType())) { 9178 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 9179 << EnumUnderlyingTy << Prev->getIntegerType(); 9180 Diag(Prev->getLocation(), diag::note_previous_use); 9181 return true; 9182 } 9183 } else if (IsFixed != Prev->isFixed()) { 9184 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 9185 << Prev->isFixed(); 9186 Diag(Prev->getLocation(), diag::note_previous_use); 9187 return true; 9188 } 9189 9190 return false; 9191} 9192 9193/// \brief Get diagnostic %select index for tag kind for 9194/// redeclaration diagnostic message. 9195/// WARNING: Indexes apply to particular diagnostics only! 9196/// 9197/// \returns diagnostic %select index. 9198static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 9199 switch (Tag) { 9200 case TTK_Struct: return 0; 9201 case TTK_Interface: return 1; 9202 case TTK_Class: return 2; 9203 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 9204 } 9205} 9206 9207/// \brief Determine if tag kind is a class-key compatible with 9208/// class for redeclaration (class, struct, or __interface). 9209/// 9210/// \returns true iff the tag kind is compatible. 9211static bool isClassCompatTagKind(TagTypeKind Tag) 9212{ 9213 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 9214} 9215 9216/// \brief Determine whether a tag with a given kind is acceptable 9217/// as a redeclaration of the given tag declaration. 9218/// 9219/// \returns true if the new tag kind is acceptable, false otherwise. 9220bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 9221 TagTypeKind NewTag, bool isDefinition, 9222 SourceLocation NewTagLoc, 9223 const IdentifierInfo &Name) { 9224 // C++ [dcl.type.elab]p3: 9225 // The class-key or enum keyword present in the 9226 // elaborated-type-specifier shall agree in kind with the 9227 // declaration to which the name in the elaborated-type-specifier 9228 // refers. This rule also applies to the form of 9229 // elaborated-type-specifier that declares a class-name or 9230 // friend class since it can be construed as referring to the 9231 // definition of the class. Thus, in any 9232 // elaborated-type-specifier, the enum keyword shall be used to 9233 // refer to an enumeration (7.2), the union class-key shall be 9234 // used to refer to a union (clause 9), and either the class or 9235 // struct class-key shall be used to refer to a class (clause 9) 9236 // declared using the class or struct class-key. 9237 TagTypeKind OldTag = Previous->getTagKind(); 9238 if (!isDefinition || !isClassCompatTagKind(NewTag)) 9239 if (OldTag == NewTag) 9240 return true; 9241 9242 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 9243 // Warn about the struct/class tag mismatch. 9244 bool isTemplate = false; 9245 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 9246 isTemplate = Record->getDescribedClassTemplate(); 9247 9248 if (!ActiveTemplateInstantiations.empty()) { 9249 // In a template instantiation, do not offer fix-its for tag mismatches 9250 // since they usually mess up the template instead of fixing the problem. 9251 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9252 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9253 << getRedeclDiagFromTagKind(OldTag); 9254 return true; 9255 } 9256 9257 if (isDefinition) { 9258 // On definitions, check previous tags and issue a fix-it for each 9259 // one that doesn't match the current tag. 9260 if (Previous->getDefinition()) { 9261 // Don't suggest fix-its for redefinitions. 9262 return true; 9263 } 9264 9265 bool previousMismatch = false; 9266 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 9267 E(Previous->redecls_end()); I != E; ++I) { 9268 if (I->getTagKind() != NewTag) { 9269 if (!previousMismatch) { 9270 previousMismatch = true; 9271 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 9272 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9273 << getRedeclDiagFromTagKind(I->getTagKind()); 9274 } 9275 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 9276 << getRedeclDiagFromTagKind(NewTag) 9277 << FixItHint::CreateReplacement(I->getInnerLocStart(), 9278 TypeWithKeyword::getTagTypeKindName(NewTag)); 9279 } 9280 } 9281 return true; 9282 } 9283 9284 // Check for a previous definition. If current tag and definition 9285 // are same type, do nothing. If no definition, but disagree with 9286 // with previous tag type, give a warning, but no fix-it. 9287 const TagDecl *Redecl = Previous->getDefinition() ? 9288 Previous->getDefinition() : Previous; 9289 if (Redecl->getTagKind() == NewTag) { 9290 return true; 9291 } 9292 9293 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9294 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9295 << getRedeclDiagFromTagKind(OldTag); 9296 Diag(Redecl->getLocation(), diag::note_previous_use); 9297 9298 // If there is a previous defintion, suggest a fix-it. 9299 if (Previous->getDefinition()) { 9300 Diag(NewTagLoc, diag::note_struct_class_suggestion) 9301 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 9302 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 9303 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 9304 } 9305 9306 return true; 9307 } 9308 return false; 9309} 9310 9311/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 9312/// former case, Name will be non-null. In the later case, Name will be null. 9313/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 9314/// reference/declaration/definition of a tag. 9315Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 9316 SourceLocation KWLoc, CXXScopeSpec &SS, 9317 IdentifierInfo *Name, SourceLocation NameLoc, 9318 AttributeList *Attr, AccessSpecifier AS, 9319 SourceLocation ModulePrivateLoc, 9320 MultiTemplateParamsArg TemplateParameterLists, 9321 bool &OwnedDecl, bool &IsDependent, 9322 SourceLocation ScopedEnumKWLoc, 9323 bool ScopedEnumUsesClassTag, 9324 TypeResult UnderlyingType) { 9325 // If this is not a definition, it must have a name. 9326 IdentifierInfo *OrigName = Name; 9327 assert((Name != 0 || TUK == TUK_Definition) && 9328 "Nameless record must be a definition!"); 9329 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 9330 9331 OwnedDecl = false; 9332 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9333 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 9334 9335 // FIXME: Check explicit specializations more carefully. 9336 bool isExplicitSpecialization = false; 9337 bool Invalid = false; 9338 9339 // We only need to do this matching if we have template parameters 9340 // or a scope specifier, which also conveniently avoids this work 9341 // for non-C++ cases. 9342 if (TemplateParameterLists.size() > 0 || 9343 (SS.isNotEmpty() && TUK != TUK_Reference)) { 9344 if (TemplateParameterList *TemplateParams 9345 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 9346 TemplateParameterLists.data(), 9347 TemplateParameterLists.size(), 9348 TUK == TUK_Friend, 9349 isExplicitSpecialization, 9350 Invalid)) { 9351 if (TemplateParams->size() > 0) { 9352 // This is a declaration or definition of a class template (which may 9353 // be a member of another template). 9354 9355 if (Invalid) 9356 return 0; 9357 9358 OwnedDecl = false; 9359 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 9360 SS, Name, NameLoc, Attr, 9361 TemplateParams, AS, 9362 ModulePrivateLoc, 9363 TemplateParameterLists.size()-1, 9364 TemplateParameterLists.data()); 9365 return Result.get(); 9366 } else { 9367 // The "template<>" header is extraneous. 9368 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9369 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9370 isExplicitSpecialization = true; 9371 } 9372 } 9373 } 9374 9375 // Figure out the underlying type if this a enum declaration. We need to do 9376 // this early, because it's needed to detect if this is an incompatible 9377 // redeclaration. 9378 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 9379 9380 if (Kind == TTK_Enum) { 9381 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 9382 // No underlying type explicitly specified, or we failed to parse the 9383 // type, default to int. 9384 EnumUnderlying = Context.IntTy.getTypePtr(); 9385 else if (UnderlyingType.get()) { 9386 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 9387 // integral type; any cv-qualification is ignored. 9388 TypeSourceInfo *TI = 0; 9389 GetTypeFromParser(UnderlyingType.get(), &TI); 9390 EnumUnderlying = TI; 9391 9392 if (CheckEnumUnderlyingType(TI)) 9393 // Recover by falling back to int. 9394 EnumUnderlying = Context.IntTy.getTypePtr(); 9395 9396 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 9397 UPPC_FixedUnderlyingType)) 9398 EnumUnderlying = Context.IntTy.getTypePtr(); 9399 9400 } else if (getLangOpts().MicrosoftMode) 9401 // Microsoft enums are always of int type. 9402 EnumUnderlying = Context.IntTy.getTypePtr(); 9403 } 9404 9405 DeclContext *SearchDC = CurContext; 9406 DeclContext *DC = CurContext; 9407 bool isStdBadAlloc = false; 9408 9409 RedeclarationKind Redecl = ForRedeclaration; 9410 if (TUK == TUK_Friend || TUK == TUK_Reference) 9411 Redecl = NotForRedeclaration; 9412 9413 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 9414 9415 if (Name && SS.isNotEmpty()) { 9416 // We have a nested-name tag ('struct foo::bar'). 9417 9418 // Check for invalid 'foo::'. 9419 if (SS.isInvalid()) { 9420 Name = 0; 9421 goto CreateNewDecl; 9422 } 9423 9424 // If this is a friend or a reference to a class in a dependent 9425 // context, don't try to make a decl for it. 9426 if (TUK == TUK_Friend || TUK == TUK_Reference) { 9427 DC = computeDeclContext(SS, false); 9428 if (!DC) { 9429 IsDependent = true; 9430 return 0; 9431 } 9432 } else { 9433 DC = computeDeclContext(SS, true); 9434 if (!DC) { 9435 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 9436 << SS.getRange(); 9437 return 0; 9438 } 9439 } 9440 9441 if (RequireCompleteDeclContext(SS, DC)) 9442 return 0; 9443 9444 SearchDC = DC; 9445 // Look-up name inside 'foo::'. 9446 LookupQualifiedName(Previous, DC); 9447 9448 if (Previous.isAmbiguous()) 9449 return 0; 9450 9451 if (Previous.empty()) { 9452 // Name lookup did not find anything. However, if the 9453 // nested-name-specifier refers to the current instantiation, 9454 // and that current instantiation has any dependent base 9455 // classes, we might find something at instantiation time: treat 9456 // this as a dependent elaborated-type-specifier. 9457 // But this only makes any sense for reference-like lookups. 9458 if (Previous.wasNotFoundInCurrentInstantiation() && 9459 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9460 IsDependent = true; 9461 return 0; 9462 } 9463 9464 // A tag 'foo::bar' must already exist. 9465 Diag(NameLoc, diag::err_not_tag_in_scope) 9466 << Kind << Name << DC << SS.getRange(); 9467 Name = 0; 9468 Invalid = true; 9469 goto CreateNewDecl; 9470 } 9471 } else if (Name) { 9472 // If this is a named struct, check to see if there was a previous forward 9473 // declaration or definition. 9474 // FIXME: We're looking into outer scopes here, even when we 9475 // shouldn't be. Doing so can result in ambiguities that we 9476 // shouldn't be diagnosing. 9477 LookupName(Previous, S); 9478 9479 // When declaring or defining a tag, ignore ambiguities introduced 9480 // by types using'ed into this scope. 9481 if (Previous.isAmbiguous() && 9482 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 9483 LookupResult::Filter F = Previous.makeFilter(); 9484 while (F.hasNext()) { 9485 NamedDecl *ND = F.next(); 9486 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 9487 F.erase(); 9488 } 9489 F.done(); 9490 } 9491 9492 // C++11 [namespace.memdef]p3: 9493 // If the name in a friend declaration is neither qualified nor 9494 // a template-id and the declaration is a function or an 9495 // elaborated-type-specifier, the lookup to determine whether 9496 // the entity has been previously declared shall not consider 9497 // any scopes outside the innermost enclosing namespace. 9498 // 9499 // Does it matter that this should be by scope instead of by 9500 // semantic context? 9501 if (!Previous.empty() && TUK == TUK_Friend) { 9502 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 9503 LookupResult::Filter F = Previous.makeFilter(); 9504 while (F.hasNext()) { 9505 NamedDecl *ND = F.next(); 9506 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 9507 if (DC->isFileContext() && !EnclosingNS->Encloses(ND->getDeclContext())) 9508 F.erase(); 9509 } 9510 F.done(); 9511 } 9512 9513 // Note: there used to be some attempt at recovery here. 9514 if (Previous.isAmbiguous()) 9515 return 0; 9516 9517 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 9518 // FIXME: This makes sure that we ignore the contexts associated 9519 // with C structs, unions, and enums when looking for a matching 9520 // tag declaration or definition. See the similar lookup tweak 9521 // in Sema::LookupName; is there a better way to deal with this? 9522 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 9523 SearchDC = SearchDC->getParent(); 9524 } 9525 } else if (S->isFunctionPrototypeScope()) { 9526 // If this is an enum declaration in function prototype scope, set its 9527 // initial context to the translation unit. 9528 // FIXME: [citation needed] 9529 SearchDC = Context.getTranslationUnitDecl(); 9530 } 9531 9532 if (Previous.isSingleResult() && 9533 Previous.getFoundDecl()->isTemplateParameter()) { 9534 // Maybe we will complain about the shadowed template parameter. 9535 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 9536 // Just pretend that we didn't see the previous declaration. 9537 Previous.clear(); 9538 } 9539 9540 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 9541 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 9542 // This is a declaration of or a reference to "std::bad_alloc". 9543 isStdBadAlloc = true; 9544 9545 if (Previous.empty() && StdBadAlloc) { 9546 // std::bad_alloc has been implicitly declared (but made invisible to 9547 // name lookup). Fill in this implicit declaration as the previous 9548 // declaration, so that the declarations get chained appropriately. 9549 Previous.addDecl(getStdBadAlloc()); 9550 } 9551 } 9552 9553 // If we didn't find a previous declaration, and this is a reference 9554 // (or friend reference), move to the correct scope. In C++, we 9555 // also need to do a redeclaration lookup there, just in case 9556 // there's a shadow friend decl. 9557 if (Name && Previous.empty() && 9558 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9559 if (Invalid) goto CreateNewDecl; 9560 assert(SS.isEmpty()); 9561 9562 if (TUK == TUK_Reference) { 9563 // C++ [basic.scope.pdecl]p5: 9564 // -- for an elaborated-type-specifier of the form 9565 // 9566 // class-key identifier 9567 // 9568 // if the elaborated-type-specifier is used in the 9569 // decl-specifier-seq or parameter-declaration-clause of a 9570 // function defined in namespace scope, the identifier is 9571 // declared as a class-name in the namespace that contains 9572 // the declaration; otherwise, except as a friend 9573 // declaration, the identifier is declared in the smallest 9574 // non-class, non-function-prototype scope that contains the 9575 // declaration. 9576 // 9577 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 9578 // C structs and unions. 9579 // 9580 // It is an error in C++ to declare (rather than define) an enum 9581 // type, including via an elaborated type specifier. We'll 9582 // diagnose that later; for now, declare the enum in the same 9583 // scope as we would have picked for any other tag type. 9584 // 9585 // GNU C also supports this behavior as part of its incomplete 9586 // enum types extension, while GNU C++ does not. 9587 // 9588 // Find the context where we'll be declaring the tag. 9589 // FIXME: We would like to maintain the current DeclContext as the 9590 // lexical context, 9591 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 9592 SearchDC = SearchDC->getParent(); 9593 9594 // Find the scope where we'll be declaring the tag. 9595 while (S->isClassScope() || 9596 (getLangOpts().CPlusPlus && 9597 S->isFunctionPrototypeScope()) || 9598 ((S->getFlags() & Scope::DeclScope) == 0) || 9599 (S->getEntity() && 9600 ((DeclContext *)S->getEntity())->isTransparentContext())) 9601 S = S->getParent(); 9602 } else { 9603 assert(TUK == TUK_Friend); 9604 // C++ [namespace.memdef]p3: 9605 // If a friend declaration in a non-local class first declares a 9606 // class or function, the friend class or function is a member of 9607 // the innermost enclosing namespace. 9608 SearchDC = SearchDC->getEnclosingNamespaceContext(); 9609 } 9610 9611 // In C++, we need to do a redeclaration lookup to properly 9612 // diagnose some problems. 9613 if (getLangOpts().CPlusPlus) { 9614 Previous.setRedeclarationKind(ForRedeclaration); 9615 LookupQualifiedName(Previous, SearchDC); 9616 } 9617 } 9618 9619 if (!Previous.empty()) { 9620 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 9621 9622 // It's okay to have a tag decl in the same scope as a typedef 9623 // which hides a tag decl in the same scope. Finding this 9624 // insanity with a redeclaration lookup can only actually happen 9625 // in C++. 9626 // 9627 // This is also okay for elaborated-type-specifiers, which is 9628 // technically forbidden by the current standard but which is 9629 // okay according to the likely resolution of an open issue; 9630 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 9631 if (getLangOpts().CPlusPlus) { 9632 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9633 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 9634 TagDecl *Tag = TT->getDecl(); 9635 if (Tag->getDeclName() == Name && 9636 Tag->getDeclContext()->getRedeclContext() 9637 ->Equals(TD->getDeclContext()->getRedeclContext())) { 9638 PrevDecl = Tag; 9639 Previous.clear(); 9640 Previous.addDecl(Tag); 9641 Previous.resolveKind(); 9642 } 9643 } 9644 } 9645 } 9646 9647 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 9648 // If this is a use of a previous tag, or if the tag is already declared 9649 // in the same scope (so that the definition/declaration completes or 9650 // rementions the tag), reuse the decl. 9651 if (TUK == TUK_Reference || TUK == TUK_Friend || 9652 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 9653 // Make sure that this wasn't declared as an enum and now used as a 9654 // struct or something similar. 9655 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 9656 TUK == TUK_Definition, KWLoc, 9657 *Name)) { 9658 bool SafeToContinue 9659 = (PrevTagDecl->getTagKind() != TTK_Enum && 9660 Kind != TTK_Enum); 9661 if (SafeToContinue) 9662 Diag(KWLoc, diag::err_use_with_wrong_tag) 9663 << Name 9664 << FixItHint::CreateReplacement(SourceRange(KWLoc), 9665 PrevTagDecl->getKindName()); 9666 else 9667 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 9668 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 9669 9670 if (SafeToContinue) 9671 Kind = PrevTagDecl->getTagKind(); 9672 else { 9673 // Recover by making this an anonymous redefinition. 9674 Name = 0; 9675 Previous.clear(); 9676 Invalid = true; 9677 } 9678 } 9679 9680 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 9681 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 9682 9683 // If this is an elaborated-type-specifier for a scoped enumeration, 9684 // the 'class' keyword is not necessary and not permitted. 9685 if (TUK == TUK_Reference || TUK == TUK_Friend) { 9686 if (ScopedEnum) 9687 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 9688 << PrevEnum->isScoped() 9689 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 9690 return PrevTagDecl; 9691 } 9692 9693 QualType EnumUnderlyingTy; 9694 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9695 EnumUnderlyingTy = TI->getType(); 9696 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 9697 EnumUnderlyingTy = QualType(T, 0); 9698 9699 // All conflicts with previous declarations are recovered by 9700 // returning the previous declaration, unless this is a definition, 9701 // in which case we want the caller to bail out. 9702 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 9703 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 9704 return TUK == TUK_Declaration ? PrevTagDecl : 0; 9705 } 9706 9707 if (!Invalid) { 9708 // If this is a use, just return the declaration we found. 9709 9710 // FIXME: In the future, return a variant or some other clue 9711 // for the consumer of this Decl to know it doesn't own it. 9712 // For our current ASTs this shouldn't be a problem, but will 9713 // need to be changed with DeclGroups. 9714 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 9715 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 9716 return PrevTagDecl; 9717 9718 // Diagnose attempts to redefine a tag. 9719 if (TUK == TUK_Definition) { 9720 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 9721 // If we're defining a specialization and the previous definition 9722 // is from an implicit instantiation, don't emit an error 9723 // here; we'll catch this in the general case below. 9724 bool IsExplicitSpecializationAfterInstantiation = false; 9725 if (isExplicitSpecialization) { 9726 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 9727 IsExplicitSpecializationAfterInstantiation = 9728 RD->getTemplateSpecializationKind() != 9729 TSK_ExplicitSpecialization; 9730 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 9731 IsExplicitSpecializationAfterInstantiation = 9732 ED->getTemplateSpecializationKind() != 9733 TSK_ExplicitSpecialization; 9734 } 9735 9736 if (!IsExplicitSpecializationAfterInstantiation) { 9737 // A redeclaration in function prototype scope in C isn't 9738 // visible elsewhere, so merely issue a warning. 9739 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 9740 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 9741 else 9742 Diag(NameLoc, diag::err_redefinition) << Name; 9743 Diag(Def->getLocation(), diag::note_previous_definition); 9744 // If this is a redefinition, recover by making this 9745 // struct be anonymous, which will make any later 9746 // references get the previous definition. 9747 Name = 0; 9748 Previous.clear(); 9749 Invalid = true; 9750 } 9751 } else { 9752 // If the type is currently being defined, complain 9753 // about a nested redefinition. 9754 const TagType *Tag 9755 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 9756 if (Tag->isBeingDefined()) { 9757 Diag(NameLoc, diag::err_nested_redefinition) << Name; 9758 Diag(PrevTagDecl->getLocation(), 9759 diag::note_previous_definition); 9760 Name = 0; 9761 Previous.clear(); 9762 Invalid = true; 9763 } 9764 } 9765 9766 // Okay, this is definition of a previously declared or referenced 9767 // tag PrevDecl. We're going to create a new Decl for it. 9768 } 9769 } 9770 // If we get here we have (another) forward declaration or we 9771 // have a definition. Just create a new decl. 9772 9773 } else { 9774 // If we get here, this is a definition of a new tag type in a nested 9775 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 9776 // new decl/type. We set PrevDecl to NULL so that the entities 9777 // have distinct types. 9778 Previous.clear(); 9779 } 9780 // If we get here, we're going to create a new Decl. If PrevDecl 9781 // is non-NULL, it's a definition of the tag declared by 9782 // PrevDecl. If it's NULL, we have a new definition. 9783 9784 9785 // Otherwise, PrevDecl is not a tag, but was found with tag 9786 // lookup. This is only actually possible in C++, where a few 9787 // things like templates still live in the tag namespace. 9788 } else { 9789 // Use a better diagnostic if an elaborated-type-specifier 9790 // found the wrong kind of type on the first 9791 // (non-redeclaration) lookup. 9792 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 9793 !Previous.isForRedeclaration()) { 9794 unsigned Kind = 0; 9795 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9796 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9797 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9798 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 9799 Diag(PrevDecl->getLocation(), diag::note_declared_at); 9800 Invalid = true; 9801 9802 // Otherwise, only diagnose if the declaration is in scope. 9803 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 9804 isExplicitSpecialization)) { 9805 // do nothing 9806 9807 // Diagnose implicit declarations introduced by elaborated types. 9808 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 9809 unsigned Kind = 0; 9810 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9811 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9812 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9813 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 9814 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9815 Invalid = true; 9816 9817 // Otherwise it's a declaration. Call out a particularly common 9818 // case here. 9819 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9820 unsigned Kind = 0; 9821 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 9822 Diag(NameLoc, diag::err_tag_definition_of_typedef) 9823 << Name << Kind << TND->getUnderlyingType(); 9824 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9825 Invalid = true; 9826 9827 // Otherwise, diagnose. 9828 } else { 9829 // The tag name clashes with something else in the target scope, 9830 // issue an error and recover by making this tag be anonymous. 9831 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 9832 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9833 Name = 0; 9834 Invalid = true; 9835 } 9836 9837 // The existing declaration isn't relevant to us; we're in a 9838 // new scope, so clear out the previous declaration. 9839 Previous.clear(); 9840 } 9841 } 9842 9843CreateNewDecl: 9844 9845 TagDecl *PrevDecl = 0; 9846 if (Previous.isSingleResult()) 9847 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 9848 9849 // If there is an identifier, use the location of the identifier as the 9850 // location of the decl, otherwise use the location of the struct/union 9851 // keyword. 9852 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 9853 9854 // Otherwise, create a new declaration. If there is a previous 9855 // declaration of the same entity, the two will be linked via 9856 // PrevDecl. 9857 TagDecl *New; 9858 9859 bool IsForwardReference = false; 9860 if (Kind == TTK_Enum) { 9861 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9862 // enum X { A, B, C } D; D should chain to X. 9863 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 9864 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 9865 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 9866 // If this is an undefined enum, warn. 9867 if (TUK != TUK_Definition && !Invalid) { 9868 TagDecl *Def; 9869 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 9870 cast<EnumDecl>(New)->isFixed()) { 9871 // C++0x: 7.2p2: opaque-enum-declaration. 9872 // Conflicts are diagnosed above. Do nothing. 9873 } 9874 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 9875 Diag(Loc, diag::ext_forward_ref_enum_def) 9876 << New; 9877 Diag(Def->getLocation(), diag::note_previous_definition); 9878 } else { 9879 unsigned DiagID = diag::ext_forward_ref_enum; 9880 if (getLangOpts().MicrosoftMode) 9881 DiagID = diag::ext_ms_forward_ref_enum; 9882 else if (getLangOpts().CPlusPlus) 9883 DiagID = diag::err_forward_ref_enum; 9884 Diag(Loc, DiagID); 9885 9886 // If this is a forward-declared reference to an enumeration, make a 9887 // note of it; we won't actually be introducing the declaration into 9888 // the declaration context. 9889 if (TUK == TUK_Reference) 9890 IsForwardReference = true; 9891 } 9892 } 9893 9894 if (EnumUnderlying) { 9895 EnumDecl *ED = cast<EnumDecl>(New); 9896 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9897 ED->setIntegerTypeSourceInfo(TI); 9898 else 9899 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 9900 ED->setPromotionType(ED->getIntegerType()); 9901 } 9902 9903 } else { 9904 // struct/union/class 9905 9906 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9907 // struct X { int A; } D; D should chain to X. 9908 if (getLangOpts().CPlusPlus) { 9909 // FIXME: Look for a way to use RecordDecl for simple structs. 9910 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9911 cast_or_null<CXXRecordDecl>(PrevDecl)); 9912 9913 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 9914 StdBadAlloc = cast<CXXRecordDecl>(New); 9915 } else 9916 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9917 cast_or_null<RecordDecl>(PrevDecl)); 9918 } 9919 9920 // Maybe add qualifier info. 9921 if (SS.isNotEmpty()) { 9922 if (SS.isSet()) { 9923 // If this is either a declaration or a definition, check the 9924 // nested-name-specifier against the current context. We don't do this 9925 // for explicit specializations, because they have similar checking 9926 // (with more specific diagnostics) in the call to 9927 // CheckMemberSpecialization, below. 9928 if (!isExplicitSpecialization && 9929 (TUK == TUK_Definition || TUK == TUK_Declaration) && 9930 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 9931 Invalid = true; 9932 9933 New->setQualifierInfo(SS.getWithLocInContext(Context)); 9934 if (TemplateParameterLists.size() > 0) { 9935 New->setTemplateParameterListsInfo(Context, 9936 TemplateParameterLists.size(), 9937 TemplateParameterLists.data()); 9938 } 9939 } 9940 else 9941 Invalid = true; 9942 } 9943 9944 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 9945 // Add alignment attributes if necessary; these attributes are checked when 9946 // the ASTContext lays out the structure. 9947 // 9948 // It is important for implementing the correct semantics that this 9949 // happen here (in act on tag decl). The #pragma pack stack is 9950 // maintained as a result of parser callbacks which can occur at 9951 // many points during the parsing of a struct declaration (because 9952 // the #pragma tokens are effectively skipped over during the 9953 // parsing of the struct). 9954 if (TUK == TUK_Definition) { 9955 AddAlignmentAttributesForRecord(RD); 9956 AddMsStructLayoutForRecord(RD); 9957 } 9958 } 9959 9960 if (ModulePrivateLoc.isValid()) { 9961 if (isExplicitSpecialization) 9962 Diag(New->getLocation(), diag::err_module_private_specialization) 9963 << 2 9964 << FixItHint::CreateRemoval(ModulePrivateLoc); 9965 // __module_private__ does not apply to local classes. However, we only 9966 // diagnose this as an error when the declaration specifiers are 9967 // freestanding. Here, we just ignore the __module_private__. 9968 else if (!SearchDC->isFunctionOrMethod()) 9969 New->setModulePrivate(); 9970 } 9971 9972 // If this is a specialization of a member class (of a class template), 9973 // check the specialization. 9974 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 9975 Invalid = true; 9976 9977 if (Invalid) 9978 New->setInvalidDecl(); 9979 9980 if (Attr) 9981 ProcessDeclAttributeList(S, New, Attr); 9982 9983 // If we're declaring or defining a tag in function prototype scope 9984 // in C, note that this type can only be used within the function. 9985 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 9986 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 9987 9988 // Set the lexical context. If the tag has a C++ scope specifier, the 9989 // lexical context will be different from the semantic context. 9990 New->setLexicalDeclContext(CurContext); 9991 9992 // Mark this as a friend decl if applicable. 9993 // In Microsoft mode, a friend declaration also acts as a forward 9994 // declaration so we always pass true to setObjectOfFriendDecl to make 9995 // the tag name visible. 9996 if (TUK == TUK_Friend) 9997 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 9998 getLangOpts().MicrosoftExt); 9999 10000 // Set the access specifier. 10001 if (!Invalid && SearchDC->isRecord()) 10002 SetMemberAccessSpecifier(New, PrevDecl, AS); 10003 10004 if (TUK == TUK_Definition) 10005 New->startDefinition(); 10006 10007 // If this has an identifier, add it to the scope stack. 10008 if (TUK == TUK_Friend) { 10009 // We might be replacing an existing declaration in the lookup tables; 10010 // if so, borrow its access specifier. 10011 if (PrevDecl) 10012 New->setAccess(PrevDecl->getAccess()); 10013 10014 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 10015 DC->makeDeclVisibleInContext(New); 10016 if (Name) // can be null along some error paths 10017 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10018 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 10019 } else if (Name) { 10020 S = getNonFieldDeclScope(S); 10021 PushOnScopeChains(New, S, !IsForwardReference); 10022 if (IsForwardReference) 10023 SearchDC->makeDeclVisibleInContext(New); 10024 10025 } else { 10026 CurContext->addDecl(New); 10027 } 10028 10029 // If this is the C FILE type, notify the AST context. 10030 if (IdentifierInfo *II = New->getIdentifier()) 10031 if (!New->isInvalidDecl() && 10032 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 10033 II->isStr("FILE")) 10034 Context.setFILEDecl(New); 10035 10036 // If we were in function prototype scope (and not in C++ mode), add this 10037 // tag to the list of decls to inject into the function definition scope. 10038 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 10039 InFunctionDeclarator && Name) 10040 DeclsInPrototypeScope.push_back(New); 10041 10042 if (PrevDecl) 10043 mergeDeclAttributes(New, PrevDecl); 10044 10045 // If there's a #pragma GCC visibility in scope, set the visibility of this 10046 // record. 10047 AddPushedVisibilityAttribute(New); 10048 10049 OwnedDecl = true; 10050 // In C++, don't return an invalid declaration. We can't recover well from 10051 // the cases where we make the type anonymous. 10052 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 10053} 10054 10055void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 10056 AdjustDeclIfTemplate(TagD); 10057 TagDecl *Tag = cast<TagDecl>(TagD); 10058 10059 // Enter the tag context. 10060 PushDeclContext(S, Tag); 10061 10062 ActOnDocumentableDecl(TagD); 10063 10064 // If there's a #pragma GCC visibility in scope, set the visibility of this 10065 // record. 10066 AddPushedVisibilityAttribute(Tag); 10067} 10068 10069Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 10070 assert(isa<ObjCContainerDecl>(IDecl) && 10071 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 10072 DeclContext *OCD = cast<DeclContext>(IDecl); 10073 assert(getContainingDC(OCD) == CurContext && 10074 "The next DeclContext should be lexically contained in the current one."); 10075 CurContext = OCD; 10076 return IDecl; 10077} 10078 10079void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 10080 SourceLocation FinalLoc, 10081 SourceLocation LBraceLoc) { 10082 AdjustDeclIfTemplate(TagD); 10083 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 10084 10085 FieldCollector->StartClass(); 10086 10087 if (!Record->getIdentifier()) 10088 return; 10089 10090 if (FinalLoc.isValid()) 10091 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 10092 10093 // C++ [class]p2: 10094 // [...] The class-name is also inserted into the scope of the 10095 // class itself; this is known as the injected-class-name. For 10096 // purposes of access checking, the injected-class-name is treated 10097 // as if it were a public member name. 10098 CXXRecordDecl *InjectedClassName 10099 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 10100 Record->getLocStart(), Record->getLocation(), 10101 Record->getIdentifier(), 10102 /*PrevDecl=*/0, 10103 /*DelayTypeCreation=*/true); 10104 Context.getTypeDeclType(InjectedClassName, Record); 10105 InjectedClassName->setImplicit(); 10106 InjectedClassName->setAccess(AS_public); 10107 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 10108 InjectedClassName->setDescribedClassTemplate(Template); 10109 PushOnScopeChains(InjectedClassName, S); 10110 assert(InjectedClassName->isInjectedClassName() && 10111 "Broken injected-class-name"); 10112} 10113 10114void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 10115 SourceLocation RBraceLoc) { 10116 AdjustDeclIfTemplate(TagD); 10117 TagDecl *Tag = cast<TagDecl>(TagD); 10118 Tag->setRBraceLoc(RBraceLoc); 10119 10120 // Make sure we "complete" the definition even it is invalid. 10121 if (Tag->isBeingDefined()) { 10122 assert(Tag->isInvalidDecl() && "We should already have completed it"); 10123 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10124 RD->completeDefinition(); 10125 } 10126 10127 if (isa<CXXRecordDecl>(Tag)) 10128 FieldCollector->FinishClass(); 10129 10130 // Exit this scope of this tag's definition. 10131 PopDeclContext(); 10132 10133 if (getCurLexicalContext()->isObjCContainer() && 10134 Tag->getDeclContext()->isFileContext()) 10135 Tag->setTopLevelDeclInObjCContainer(); 10136 10137 // Notify the consumer that we've defined a tag. 10138 Consumer.HandleTagDeclDefinition(Tag); 10139} 10140 10141void Sema::ActOnObjCContainerFinishDefinition() { 10142 // Exit this scope of this interface definition. 10143 PopDeclContext(); 10144} 10145 10146void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 10147 assert(DC == CurContext && "Mismatch of container contexts"); 10148 OriginalLexicalContext = DC; 10149 ActOnObjCContainerFinishDefinition(); 10150} 10151 10152void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 10153 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 10154 OriginalLexicalContext = 0; 10155} 10156 10157void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 10158 AdjustDeclIfTemplate(TagD); 10159 TagDecl *Tag = cast<TagDecl>(TagD); 10160 Tag->setInvalidDecl(); 10161 10162 // Make sure we "complete" the definition even it is invalid. 10163 if (Tag->isBeingDefined()) { 10164 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10165 RD->completeDefinition(); 10166 } 10167 10168 // We're undoing ActOnTagStartDefinition here, not 10169 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 10170 // the FieldCollector. 10171 10172 PopDeclContext(); 10173} 10174 10175// Note that FieldName may be null for anonymous bitfields. 10176ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 10177 IdentifierInfo *FieldName, 10178 QualType FieldTy, Expr *BitWidth, 10179 bool *ZeroWidth) { 10180 // Default to true; that shouldn't confuse checks for emptiness 10181 if (ZeroWidth) 10182 *ZeroWidth = true; 10183 10184 // C99 6.7.2.1p4 - verify the field type. 10185 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 10186 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 10187 // Handle incomplete types with specific error. 10188 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 10189 return ExprError(); 10190 if (FieldName) 10191 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 10192 << FieldName << FieldTy << BitWidth->getSourceRange(); 10193 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 10194 << FieldTy << BitWidth->getSourceRange(); 10195 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 10196 UPPC_BitFieldWidth)) 10197 return ExprError(); 10198 10199 // If the bit-width is type- or value-dependent, don't try to check 10200 // it now. 10201 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 10202 return Owned(BitWidth); 10203 10204 llvm::APSInt Value; 10205 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 10206 if (ICE.isInvalid()) 10207 return ICE; 10208 BitWidth = ICE.take(); 10209 10210 if (Value != 0 && ZeroWidth) 10211 *ZeroWidth = false; 10212 10213 // Zero-width bitfield is ok for anonymous field. 10214 if (Value == 0 && FieldName) 10215 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 10216 10217 if (Value.isSigned() && Value.isNegative()) { 10218 if (FieldName) 10219 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 10220 << FieldName << Value.toString(10); 10221 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 10222 << Value.toString(10); 10223 } 10224 10225 if (!FieldTy->isDependentType()) { 10226 uint64_t TypeSize = Context.getTypeSize(FieldTy); 10227 if (Value.getZExtValue() > TypeSize) { 10228 if (!getLangOpts().CPlusPlus) { 10229 if (FieldName) 10230 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 10231 << FieldName << (unsigned)Value.getZExtValue() 10232 << (unsigned)TypeSize; 10233 10234 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 10235 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10236 } 10237 10238 if (FieldName) 10239 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 10240 << FieldName << (unsigned)Value.getZExtValue() 10241 << (unsigned)TypeSize; 10242 else 10243 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 10244 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10245 } 10246 } 10247 10248 return Owned(BitWidth); 10249} 10250 10251/// ActOnField - Each field of a C struct/union is passed into this in order 10252/// to create a FieldDecl object for it. 10253Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 10254 Declarator &D, Expr *BitfieldWidth) { 10255 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 10256 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 10257 /*InitStyle=*/ICIS_NoInit, AS_public); 10258 return Res; 10259} 10260 10261/// HandleField - Analyze a field of a C struct or a C++ data member. 10262/// 10263FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 10264 SourceLocation DeclStart, 10265 Declarator &D, Expr *BitWidth, 10266 InClassInitStyle InitStyle, 10267 AccessSpecifier AS) { 10268 IdentifierInfo *II = D.getIdentifier(); 10269 SourceLocation Loc = DeclStart; 10270 if (II) Loc = D.getIdentifierLoc(); 10271 10272 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10273 QualType T = TInfo->getType(); 10274 if (getLangOpts().CPlusPlus) { 10275 CheckExtraCXXDefaultArguments(D); 10276 10277 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10278 UPPC_DataMemberType)) { 10279 D.setInvalidType(); 10280 T = Context.IntTy; 10281 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 10282 } 10283 } 10284 10285 // TR 18037 does not allow fields to be declared with address spaces. 10286 if (T.getQualifiers().hasAddressSpace()) { 10287 Diag(Loc, diag::err_field_with_address_space); 10288 D.setInvalidType(); 10289 } 10290 10291 // OpenCL 1.2 spec, s6.9 r: 10292 // The event type cannot be used to declare a structure or union field. 10293 if (LangOpts.OpenCL && T->isEventT()) { 10294 Diag(Loc, diag::err_event_t_struct_field); 10295 D.setInvalidType(); 10296 } 10297 10298 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 10299 10300 if (D.getDeclSpec().isThreadSpecified()) 10301 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 10302 10303 // Check to see if this name was declared as a member previously 10304 NamedDecl *PrevDecl = 0; 10305 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 10306 LookupName(Previous, S); 10307 switch (Previous.getResultKind()) { 10308 case LookupResult::Found: 10309 case LookupResult::FoundUnresolvedValue: 10310 PrevDecl = Previous.getAsSingle<NamedDecl>(); 10311 break; 10312 10313 case LookupResult::FoundOverloaded: 10314 PrevDecl = Previous.getRepresentativeDecl(); 10315 break; 10316 10317 case LookupResult::NotFound: 10318 case LookupResult::NotFoundInCurrentInstantiation: 10319 case LookupResult::Ambiguous: 10320 break; 10321 } 10322 Previous.suppressDiagnostics(); 10323 10324 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10325 // Maybe we will complain about the shadowed template parameter. 10326 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10327 // Just pretend that we didn't see the previous declaration. 10328 PrevDecl = 0; 10329 } 10330 10331 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 10332 PrevDecl = 0; 10333 10334 bool Mutable 10335 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 10336 SourceLocation TSSL = D.getLocStart(); 10337 FieldDecl *NewFD 10338 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 10339 TSSL, AS, PrevDecl, &D); 10340 10341 if (NewFD->isInvalidDecl()) 10342 Record->setInvalidDecl(); 10343 10344 if (D.getDeclSpec().isModulePrivateSpecified()) 10345 NewFD->setModulePrivate(); 10346 10347 if (NewFD->isInvalidDecl() && PrevDecl) { 10348 // Don't introduce NewFD into scope; there's already something 10349 // with the same name in the same scope. 10350 } else if (II) { 10351 PushOnScopeChains(NewFD, S); 10352 } else 10353 Record->addDecl(NewFD); 10354 10355 return NewFD; 10356} 10357 10358/// \brief Build a new FieldDecl and check its well-formedness. 10359/// 10360/// This routine builds a new FieldDecl given the fields name, type, 10361/// record, etc. \p PrevDecl should refer to any previous declaration 10362/// with the same name and in the same scope as the field to be 10363/// created. 10364/// 10365/// \returns a new FieldDecl. 10366/// 10367/// \todo The Declarator argument is a hack. It will be removed once 10368FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 10369 TypeSourceInfo *TInfo, 10370 RecordDecl *Record, SourceLocation Loc, 10371 bool Mutable, Expr *BitWidth, 10372 InClassInitStyle InitStyle, 10373 SourceLocation TSSL, 10374 AccessSpecifier AS, NamedDecl *PrevDecl, 10375 Declarator *D) { 10376 IdentifierInfo *II = Name.getAsIdentifierInfo(); 10377 bool InvalidDecl = false; 10378 if (D) InvalidDecl = D->isInvalidType(); 10379 10380 // If we receive a broken type, recover by assuming 'int' and 10381 // marking this declaration as invalid. 10382 if (T.isNull()) { 10383 InvalidDecl = true; 10384 T = Context.IntTy; 10385 } 10386 10387 QualType EltTy = Context.getBaseElementType(T); 10388 if (!EltTy->isDependentType()) { 10389 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 10390 // Fields of incomplete type force their record to be invalid. 10391 Record->setInvalidDecl(); 10392 InvalidDecl = true; 10393 } else { 10394 NamedDecl *Def; 10395 EltTy->isIncompleteType(&Def); 10396 if (Def && Def->isInvalidDecl()) { 10397 Record->setInvalidDecl(); 10398 InvalidDecl = true; 10399 } 10400 } 10401 } 10402 10403 // OpenCL v1.2 s6.9.c: bitfields are not supported. 10404 if (BitWidth && getLangOpts().OpenCL) { 10405 Diag(Loc, diag::err_opencl_bitfields); 10406 InvalidDecl = true; 10407 } 10408 10409 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10410 // than a variably modified type. 10411 if (!InvalidDecl && T->isVariablyModifiedType()) { 10412 bool SizeIsNegative; 10413 llvm::APSInt Oversized; 10414 10415 TypeSourceInfo *FixedTInfo = 10416 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 10417 SizeIsNegative, 10418 Oversized); 10419 if (FixedTInfo) { 10420 Diag(Loc, diag::warn_illegal_constant_array_size); 10421 TInfo = FixedTInfo; 10422 T = FixedTInfo->getType(); 10423 } else { 10424 if (SizeIsNegative) 10425 Diag(Loc, diag::err_typecheck_negative_array_size); 10426 else if (Oversized.getBoolValue()) 10427 Diag(Loc, diag::err_array_too_large) 10428 << Oversized.toString(10); 10429 else 10430 Diag(Loc, diag::err_typecheck_field_variable_size); 10431 InvalidDecl = true; 10432 } 10433 } 10434 10435 // Fields can not have abstract class types 10436 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 10437 diag::err_abstract_type_in_decl, 10438 AbstractFieldType)) 10439 InvalidDecl = true; 10440 10441 bool ZeroWidth = false; 10442 // If this is declared as a bit-field, check the bit-field. 10443 if (!InvalidDecl && BitWidth) { 10444 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 10445 if (!BitWidth) { 10446 InvalidDecl = true; 10447 BitWidth = 0; 10448 ZeroWidth = false; 10449 } 10450 } 10451 10452 // Check that 'mutable' is consistent with the type of the declaration. 10453 if (!InvalidDecl && Mutable) { 10454 unsigned DiagID = 0; 10455 if (T->isReferenceType()) 10456 DiagID = diag::err_mutable_reference; 10457 else if (T.isConstQualified()) 10458 DiagID = diag::err_mutable_const; 10459 10460 if (DiagID) { 10461 SourceLocation ErrLoc = Loc; 10462 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 10463 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 10464 Diag(ErrLoc, DiagID); 10465 Mutable = false; 10466 InvalidDecl = true; 10467 } 10468 } 10469 10470 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 10471 BitWidth, Mutable, InitStyle); 10472 if (InvalidDecl) 10473 NewFD->setInvalidDecl(); 10474 10475 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 10476 Diag(Loc, diag::err_duplicate_member) << II; 10477 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10478 NewFD->setInvalidDecl(); 10479 } 10480 10481 if (!InvalidDecl && getLangOpts().CPlusPlus) { 10482 if (Record->isUnion()) { 10483 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10484 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10485 if (RDecl->getDefinition()) { 10486 // C++ [class.union]p1: An object of a class with a non-trivial 10487 // constructor, a non-trivial copy constructor, a non-trivial 10488 // destructor, or a non-trivial copy assignment operator 10489 // cannot be a member of a union, nor can an array of such 10490 // objects. 10491 if (CheckNontrivialField(NewFD)) 10492 NewFD->setInvalidDecl(); 10493 } 10494 } 10495 10496 // C++ [class.union]p1: If a union contains a member of reference type, 10497 // the program is ill-formed. 10498 if (EltTy->isReferenceType()) { 10499 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 10500 << NewFD->getDeclName() << EltTy; 10501 NewFD->setInvalidDecl(); 10502 } 10503 } 10504 } 10505 10506 // FIXME: We need to pass in the attributes given an AST 10507 // representation, not a parser representation. 10508 if (D) { 10509 // FIXME: What to pass instead of TUScope? 10510 ProcessDeclAttributes(TUScope, NewFD, *D); 10511 10512 if (NewFD->hasAttrs()) 10513 CheckAlignasUnderalignment(NewFD); 10514 } 10515 10516 // In auto-retain/release, infer strong retension for fields of 10517 // retainable type. 10518 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 10519 NewFD->setInvalidDecl(); 10520 10521 if (T.isObjCGCWeak()) 10522 Diag(Loc, diag::warn_attribute_weak_on_field); 10523 10524 NewFD->setAccess(AS); 10525 return NewFD; 10526} 10527 10528bool Sema::CheckNontrivialField(FieldDecl *FD) { 10529 assert(FD); 10530 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 10531 10532 if (FD->isInvalidDecl()) 10533 return true; 10534 10535 QualType EltTy = Context.getBaseElementType(FD->getType()); 10536 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10537 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10538 if (RDecl->getDefinition()) { 10539 // We check for copy constructors before constructors 10540 // because otherwise we'll never get complaints about 10541 // copy constructors. 10542 10543 CXXSpecialMember member = CXXInvalid; 10544 // We're required to check for any non-trivial constructors. Since the 10545 // implicit default constructor is suppressed if there are any 10546 // user-declared constructors, we just need to check that there is a 10547 // trivial default constructor and a trivial copy constructor. (We don't 10548 // worry about move constructors here, since this is a C++98 check.) 10549 if (RDecl->hasNonTrivialCopyConstructor()) 10550 member = CXXCopyConstructor; 10551 else if (!RDecl->hasTrivialDefaultConstructor()) 10552 member = CXXDefaultConstructor; 10553 else if (RDecl->hasNonTrivialCopyAssignment()) 10554 member = CXXCopyAssignment; 10555 else if (RDecl->hasNonTrivialDestructor()) 10556 member = CXXDestructor; 10557 10558 if (member != CXXInvalid) { 10559 if (!getLangOpts().CPlusPlus11 && 10560 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 10561 // Objective-C++ ARC: it is an error to have a non-trivial field of 10562 // a union. However, system headers in Objective-C programs 10563 // occasionally have Objective-C lifetime objects within unions, 10564 // and rather than cause the program to fail, we make those 10565 // members unavailable. 10566 SourceLocation Loc = FD->getLocation(); 10567 if (getSourceManager().isInSystemHeader(Loc)) { 10568 if (!FD->hasAttr<UnavailableAttr>()) 10569 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 10570 "this system field has retaining ownership")); 10571 return false; 10572 } 10573 } 10574 10575 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 10576 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 10577 diag::err_illegal_union_or_anon_struct_member) 10578 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 10579 DiagnoseNontrivial(RDecl, member); 10580 return !getLangOpts().CPlusPlus11; 10581 } 10582 } 10583 } 10584 10585 return false; 10586} 10587 10588/// TranslateIvarVisibility - Translate visibility from a token ID to an 10589/// AST enum value. 10590static ObjCIvarDecl::AccessControl 10591TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 10592 switch (ivarVisibility) { 10593 default: llvm_unreachable("Unknown visitibility kind"); 10594 case tok::objc_private: return ObjCIvarDecl::Private; 10595 case tok::objc_public: return ObjCIvarDecl::Public; 10596 case tok::objc_protected: return ObjCIvarDecl::Protected; 10597 case tok::objc_package: return ObjCIvarDecl::Package; 10598 } 10599} 10600 10601/// ActOnIvar - Each ivar field of an objective-c class is passed into this 10602/// in order to create an IvarDecl object for it. 10603Decl *Sema::ActOnIvar(Scope *S, 10604 SourceLocation DeclStart, 10605 Declarator &D, Expr *BitfieldWidth, 10606 tok::ObjCKeywordKind Visibility) { 10607 10608 IdentifierInfo *II = D.getIdentifier(); 10609 Expr *BitWidth = (Expr*)BitfieldWidth; 10610 SourceLocation Loc = DeclStart; 10611 if (II) Loc = D.getIdentifierLoc(); 10612 10613 // FIXME: Unnamed fields can be handled in various different ways, for 10614 // example, unnamed unions inject all members into the struct namespace! 10615 10616 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10617 QualType T = TInfo->getType(); 10618 10619 if (BitWidth) { 10620 // 6.7.2.1p3, 6.7.2.1p4 10621 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 10622 if (!BitWidth) 10623 D.setInvalidType(); 10624 } else { 10625 // Not a bitfield. 10626 10627 // validate II. 10628 10629 } 10630 if (T->isReferenceType()) { 10631 Diag(Loc, diag::err_ivar_reference_type); 10632 D.setInvalidType(); 10633 } 10634 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10635 // than a variably modified type. 10636 else if (T->isVariablyModifiedType()) { 10637 Diag(Loc, diag::err_typecheck_ivar_variable_size); 10638 D.setInvalidType(); 10639 } 10640 10641 // Get the visibility (access control) for this ivar. 10642 ObjCIvarDecl::AccessControl ac = 10643 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 10644 : ObjCIvarDecl::None; 10645 // Must set ivar's DeclContext to its enclosing interface. 10646 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 10647 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 10648 return 0; 10649 ObjCContainerDecl *EnclosingContext; 10650 if (ObjCImplementationDecl *IMPDecl = 10651 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10652 if (LangOpts.ObjCRuntime.isFragile()) { 10653 // Case of ivar declared in an implementation. Context is that of its class. 10654 EnclosingContext = IMPDecl->getClassInterface(); 10655 assert(EnclosingContext && "Implementation has no class interface!"); 10656 } 10657 else 10658 EnclosingContext = EnclosingDecl; 10659 } else { 10660 if (ObjCCategoryDecl *CDecl = 10661 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10662 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 10663 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 10664 return 0; 10665 } 10666 } 10667 EnclosingContext = EnclosingDecl; 10668 } 10669 10670 // Construct the decl. 10671 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 10672 DeclStart, Loc, II, T, 10673 TInfo, ac, (Expr *)BitfieldWidth); 10674 10675 if (II) { 10676 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 10677 ForRedeclaration); 10678 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 10679 && !isa<TagDecl>(PrevDecl)) { 10680 Diag(Loc, diag::err_duplicate_member) << II; 10681 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10682 NewID->setInvalidDecl(); 10683 } 10684 } 10685 10686 // Process attributes attached to the ivar. 10687 ProcessDeclAttributes(S, NewID, D); 10688 10689 if (D.isInvalidType()) 10690 NewID->setInvalidDecl(); 10691 10692 // In ARC, infer 'retaining' for ivars of retainable type. 10693 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 10694 NewID->setInvalidDecl(); 10695 10696 if (D.getDeclSpec().isModulePrivateSpecified()) 10697 NewID->setModulePrivate(); 10698 10699 if (II) { 10700 // FIXME: When interfaces are DeclContexts, we'll need to add 10701 // these to the interface. 10702 S->AddDecl(NewID); 10703 IdResolver.AddDecl(NewID); 10704 } 10705 10706 if (LangOpts.ObjCRuntime.isNonFragile() && 10707 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 10708 Diag(Loc, diag::warn_ivars_in_interface); 10709 10710 return NewID; 10711} 10712 10713/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 10714/// class and class extensions. For every class @interface and class 10715/// extension @interface, if the last ivar is a bitfield of any type, 10716/// then add an implicit `char :0` ivar to the end of that interface. 10717void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 10718 SmallVectorImpl<Decl *> &AllIvarDecls) { 10719 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 10720 return; 10721 10722 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 10723 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 10724 10725 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 10726 return; 10727 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 10728 if (!ID) { 10729 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 10730 if (!CD->IsClassExtension()) 10731 return; 10732 } 10733 // No need to add this to end of @implementation. 10734 else 10735 return; 10736 } 10737 // All conditions are met. Add a new bitfield to the tail end of ivars. 10738 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 10739 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 10740 10741 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 10742 DeclLoc, DeclLoc, 0, 10743 Context.CharTy, 10744 Context.getTrivialTypeSourceInfo(Context.CharTy, 10745 DeclLoc), 10746 ObjCIvarDecl::Private, BW, 10747 true); 10748 AllIvarDecls.push_back(Ivar); 10749} 10750 10751void Sema::ActOnFields(Scope* S, 10752 SourceLocation RecLoc, Decl *EnclosingDecl, 10753 llvm::ArrayRef<Decl *> Fields, 10754 SourceLocation LBrac, SourceLocation RBrac, 10755 AttributeList *Attr) { 10756 assert(EnclosingDecl && "missing record or interface decl"); 10757 10758 // If this is an Objective-C @implementation or category and we have 10759 // new fields here we should reset the layout of the interface since 10760 // it will now change. 10761 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 10762 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 10763 switch (DC->getKind()) { 10764 default: break; 10765 case Decl::ObjCCategory: 10766 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 10767 break; 10768 case Decl::ObjCImplementation: 10769 Context. 10770 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 10771 break; 10772 } 10773 } 10774 10775 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 10776 10777 // Start counting up the number of named members; make sure to include 10778 // members of anonymous structs and unions in the total. 10779 unsigned NumNamedMembers = 0; 10780 if (Record) { 10781 for (RecordDecl::decl_iterator i = Record->decls_begin(), 10782 e = Record->decls_end(); i != e; i++) { 10783 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 10784 if (IFD->getDeclName()) 10785 ++NumNamedMembers; 10786 } 10787 } 10788 10789 // Verify that all the fields are okay. 10790 SmallVector<FieldDecl*, 32> RecFields; 10791 10792 bool ARCErrReported = false; 10793 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 10794 i != end; ++i) { 10795 FieldDecl *FD = cast<FieldDecl>(*i); 10796 10797 // Get the type for the field. 10798 const Type *FDTy = FD->getType().getTypePtr(); 10799 10800 if (!FD->isAnonymousStructOrUnion()) { 10801 // Remember all fields written by the user. 10802 RecFields.push_back(FD); 10803 } 10804 10805 // If the field is already invalid for some reason, don't emit more 10806 // diagnostics about it. 10807 if (FD->isInvalidDecl()) { 10808 EnclosingDecl->setInvalidDecl(); 10809 continue; 10810 } 10811 10812 // C99 6.7.2.1p2: 10813 // A structure or union shall not contain a member with 10814 // incomplete or function type (hence, a structure shall not 10815 // contain an instance of itself, but may contain a pointer to 10816 // an instance of itself), except that the last member of a 10817 // structure with more than one named member may have incomplete 10818 // array type; such a structure (and any union containing, 10819 // possibly recursively, a member that is such a structure) 10820 // shall not be a member of a structure or an element of an 10821 // array. 10822 if (FDTy->isFunctionType()) { 10823 // Field declared as a function. 10824 Diag(FD->getLocation(), diag::err_field_declared_as_function) 10825 << FD->getDeclName(); 10826 FD->setInvalidDecl(); 10827 EnclosingDecl->setInvalidDecl(); 10828 continue; 10829 } else if (FDTy->isIncompleteArrayType() && Record && 10830 ((i + 1 == Fields.end() && !Record->isUnion()) || 10831 ((getLangOpts().MicrosoftExt || 10832 getLangOpts().CPlusPlus) && 10833 (i + 1 == Fields.end() || Record->isUnion())))) { 10834 // Flexible array member. 10835 // Microsoft and g++ is more permissive regarding flexible array. 10836 // It will accept flexible array in union and also 10837 // as the sole element of a struct/class. 10838 if (getLangOpts().MicrosoftExt) { 10839 if (Record->isUnion()) 10840 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 10841 << FD->getDeclName(); 10842 else if (Fields.size() == 1) 10843 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 10844 << FD->getDeclName() << Record->getTagKind(); 10845 } else if (getLangOpts().CPlusPlus) { 10846 if (Record->isUnion()) 10847 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10848 << FD->getDeclName(); 10849 else if (Fields.size() == 1) 10850 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 10851 << FD->getDeclName() << Record->getTagKind(); 10852 } else if (!getLangOpts().C99) { 10853 if (Record->isUnion()) 10854 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10855 << FD->getDeclName(); 10856 else 10857 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 10858 << FD->getDeclName() << Record->getTagKind(); 10859 } else if (NumNamedMembers < 1) { 10860 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 10861 << FD->getDeclName(); 10862 FD->setInvalidDecl(); 10863 EnclosingDecl->setInvalidDecl(); 10864 continue; 10865 } 10866 if (!FD->getType()->isDependentType() && 10867 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 10868 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 10869 << FD->getDeclName() << FD->getType(); 10870 FD->setInvalidDecl(); 10871 EnclosingDecl->setInvalidDecl(); 10872 continue; 10873 } 10874 // Okay, we have a legal flexible array member at the end of the struct. 10875 if (Record) 10876 Record->setHasFlexibleArrayMember(true); 10877 } else if (!FDTy->isDependentType() && 10878 RequireCompleteType(FD->getLocation(), FD->getType(), 10879 diag::err_field_incomplete)) { 10880 // Incomplete type 10881 FD->setInvalidDecl(); 10882 EnclosingDecl->setInvalidDecl(); 10883 continue; 10884 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 10885 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 10886 // If this is a member of a union, then entire union becomes "flexible". 10887 if (Record && Record->isUnion()) { 10888 Record->setHasFlexibleArrayMember(true); 10889 } else { 10890 // If this is a struct/class and this is not the last element, reject 10891 // it. Note that GCC supports variable sized arrays in the middle of 10892 // structures. 10893 if (i + 1 != Fields.end()) 10894 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 10895 << FD->getDeclName() << FD->getType(); 10896 else { 10897 // We support flexible arrays at the end of structs in 10898 // other structs as an extension. 10899 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 10900 << FD->getDeclName(); 10901 if (Record) 10902 Record->setHasFlexibleArrayMember(true); 10903 } 10904 } 10905 } 10906 if (isa<ObjCContainerDecl>(EnclosingDecl) && 10907 RequireNonAbstractType(FD->getLocation(), FD->getType(), 10908 diag::err_abstract_type_in_decl, 10909 AbstractIvarType)) { 10910 // Ivars can not have abstract class types 10911 FD->setInvalidDecl(); 10912 } 10913 if (Record && FDTTy->getDecl()->hasObjectMember()) 10914 Record->setHasObjectMember(true); 10915 if (Record && FDTTy->getDecl()->hasVolatileMember()) 10916 Record->setHasVolatileMember(true); 10917 } else if (FDTy->isObjCObjectType()) { 10918 /// A field cannot be an Objective-c object 10919 Diag(FD->getLocation(), diag::err_statically_allocated_object) 10920 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 10921 QualType T = Context.getObjCObjectPointerType(FD->getType()); 10922 FD->setType(T); 10923 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 10924 (!getLangOpts().CPlusPlus || Record->isUnion())) { 10925 // It's an error in ARC if a field has lifetime. 10926 // We don't want to report this in a system header, though, 10927 // so we just make the field unavailable. 10928 // FIXME: that's really not sufficient; we need to make the type 10929 // itself invalid to, say, initialize or copy. 10930 QualType T = FD->getType(); 10931 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 10932 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 10933 SourceLocation loc = FD->getLocation(); 10934 if (getSourceManager().isInSystemHeader(loc)) { 10935 if (!FD->hasAttr<UnavailableAttr>()) { 10936 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10937 "this system field has retaining ownership")); 10938 } 10939 } else { 10940 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 10941 << T->isBlockPointerType() << Record->getTagKind(); 10942 } 10943 ARCErrReported = true; 10944 } 10945 } else if (getLangOpts().ObjC1 && 10946 getLangOpts().getGC() != LangOptions::NonGC && 10947 Record && !Record->hasObjectMember()) { 10948 if (FD->getType()->isObjCObjectPointerType() || 10949 FD->getType().isObjCGCStrong()) 10950 Record->setHasObjectMember(true); 10951 else if (Context.getAsArrayType(FD->getType())) { 10952 QualType BaseType = Context.getBaseElementType(FD->getType()); 10953 if (BaseType->isRecordType() && 10954 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 10955 Record->setHasObjectMember(true); 10956 else if (BaseType->isObjCObjectPointerType() || 10957 BaseType.isObjCGCStrong()) 10958 Record->setHasObjectMember(true); 10959 } 10960 } 10961 if (Record && FD->getType().isVolatileQualified()) 10962 Record->setHasVolatileMember(true); 10963 // Keep track of the number of named members. 10964 if (FD->getIdentifier()) 10965 ++NumNamedMembers; 10966 } 10967 10968 // Okay, we successfully defined 'Record'. 10969 if (Record) { 10970 bool Completed = false; 10971 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 10972 if (!CXXRecord->isInvalidDecl()) { 10973 // Set access bits correctly on the directly-declared conversions. 10974 for (CXXRecordDecl::conversion_iterator 10975 I = CXXRecord->conversion_begin(), 10976 E = CXXRecord->conversion_end(); I != E; ++I) 10977 I.setAccess((*I)->getAccess()); 10978 10979 if (!CXXRecord->isDependentType()) { 10980 // Adjust user-defined destructor exception spec. 10981 if (getLangOpts().CPlusPlus11 && 10982 CXXRecord->hasUserDeclaredDestructor()) 10983 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 10984 10985 // Add any implicitly-declared members to this class. 10986 AddImplicitlyDeclaredMembersToClass(CXXRecord); 10987 10988 // If we have virtual base classes, we may end up finding multiple 10989 // final overriders for a given virtual function. Check for this 10990 // problem now. 10991 if (CXXRecord->getNumVBases()) { 10992 CXXFinalOverriderMap FinalOverriders; 10993 CXXRecord->getFinalOverriders(FinalOverriders); 10994 10995 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 10996 MEnd = FinalOverriders.end(); 10997 M != MEnd; ++M) { 10998 for (OverridingMethods::iterator SO = M->second.begin(), 10999 SOEnd = M->second.end(); 11000 SO != SOEnd; ++SO) { 11001 assert(SO->second.size() > 0 && 11002 "Virtual function without overridding functions?"); 11003 if (SO->second.size() == 1) 11004 continue; 11005 11006 // C++ [class.virtual]p2: 11007 // In a derived class, if a virtual member function of a base 11008 // class subobject has more than one final overrider the 11009 // program is ill-formed. 11010 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 11011 << (const NamedDecl *)M->first << Record; 11012 Diag(M->first->getLocation(), 11013 diag::note_overridden_virtual_function); 11014 for (OverridingMethods::overriding_iterator 11015 OM = SO->second.begin(), 11016 OMEnd = SO->second.end(); 11017 OM != OMEnd; ++OM) 11018 Diag(OM->Method->getLocation(), diag::note_final_overrider) 11019 << (const NamedDecl *)M->first << OM->Method->getParent(); 11020 11021 Record->setInvalidDecl(); 11022 } 11023 } 11024 CXXRecord->completeDefinition(&FinalOverriders); 11025 Completed = true; 11026 } 11027 } 11028 } 11029 } 11030 11031 if (!Completed) 11032 Record->completeDefinition(); 11033 11034 if (Record->hasAttrs()) 11035 CheckAlignasUnderalignment(Record); 11036 } else { 11037 ObjCIvarDecl **ClsFields = 11038 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 11039 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 11040 ID->setEndOfDefinitionLoc(RBrac); 11041 // Add ivar's to class's DeclContext. 11042 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 11043 ClsFields[i]->setLexicalDeclContext(ID); 11044 ID->addDecl(ClsFields[i]); 11045 } 11046 // Must enforce the rule that ivars in the base classes may not be 11047 // duplicates. 11048 if (ID->getSuperClass()) 11049 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 11050 } else if (ObjCImplementationDecl *IMPDecl = 11051 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11052 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 11053 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 11054 // Ivar declared in @implementation never belongs to the implementation. 11055 // Only it is in implementation's lexical context. 11056 ClsFields[I]->setLexicalDeclContext(IMPDecl); 11057 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 11058 IMPDecl->setIvarLBraceLoc(LBrac); 11059 IMPDecl->setIvarRBraceLoc(RBrac); 11060 } else if (ObjCCategoryDecl *CDecl = 11061 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11062 // case of ivars in class extension; all other cases have been 11063 // reported as errors elsewhere. 11064 // FIXME. Class extension does not have a LocEnd field. 11065 // CDecl->setLocEnd(RBrac); 11066 // Add ivar's to class extension's DeclContext. 11067 // Diagnose redeclaration of private ivars. 11068 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 11069 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 11070 if (IDecl) { 11071 if (const ObjCIvarDecl *ClsIvar = 11072 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 11073 Diag(ClsFields[i]->getLocation(), 11074 diag::err_duplicate_ivar_declaration); 11075 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 11076 continue; 11077 } 11078 for (ObjCInterfaceDecl::known_extensions_iterator 11079 Ext = IDecl->known_extensions_begin(), 11080 ExtEnd = IDecl->known_extensions_end(); 11081 Ext != ExtEnd; ++Ext) { 11082 if (const ObjCIvarDecl *ClsExtIvar 11083 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 11084 Diag(ClsFields[i]->getLocation(), 11085 diag::err_duplicate_ivar_declaration); 11086 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 11087 continue; 11088 } 11089 } 11090 } 11091 ClsFields[i]->setLexicalDeclContext(CDecl); 11092 CDecl->addDecl(ClsFields[i]); 11093 } 11094 CDecl->setIvarLBraceLoc(LBrac); 11095 CDecl->setIvarRBraceLoc(RBrac); 11096 } 11097 } 11098 11099 if (Attr) 11100 ProcessDeclAttributeList(S, Record, Attr); 11101} 11102 11103/// \brief Determine whether the given integral value is representable within 11104/// the given type T. 11105static bool isRepresentableIntegerValue(ASTContext &Context, 11106 llvm::APSInt &Value, 11107 QualType T) { 11108 assert(T->isIntegralType(Context) && "Integral type required!"); 11109 unsigned BitWidth = Context.getIntWidth(T); 11110 11111 if (Value.isUnsigned() || Value.isNonNegative()) { 11112 if (T->isSignedIntegerOrEnumerationType()) 11113 --BitWidth; 11114 return Value.getActiveBits() <= BitWidth; 11115 } 11116 return Value.getMinSignedBits() <= BitWidth; 11117} 11118 11119// \brief Given an integral type, return the next larger integral type 11120// (or a NULL type of no such type exists). 11121static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 11122 // FIXME: Int128/UInt128 support, which also needs to be introduced into 11123 // enum checking below. 11124 assert(T->isIntegralType(Context) && "Integral type required!"); 11125 const unsigned NumTypes = 4; 11126 QualType SignedIntegralTypes[NumTypes] = { 11127 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 11128 }; 11129 QualType UnsignedIntegralTypes[NumTypes] = { 11130 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 11131 Context.UnsignedLongLongTy 11132 }; 11133 11134 unsigned BitWidth = Context.getTypeSize(T); 11135 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 11136 : UnsignedIntegralTypes; 11137 for (unsigned I = 0; I != NumTypes; ++I) 11138 if (Context.getTypeSize(Types[I]) > BitWidth) 11139 return Types[I]; 11140 11141 return QualType(); 11142} 11143 11144EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 11145 EnumConstantDecl *LastEnumConst, 11146 SourceLocation IdLoc, 11147 IdentifierInfo *Id, 11148 Expr *Val) { 11149 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11150 llvm::APSInt EnumVal(IntWidth); 11151 QualType EltTy; 11152 11153 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 11154 Val = 0; 11155 11156 if (Val) 11157 Val = DefaultLvalueConversion(Val).take(); 11158 11159 if (Val) { 11160 if (Enum->isDependentType() || Val->isTypeDependent()) 11161 EltTy = Context.DependentTy; 11162 else { 11163 SourceLocation ExpLoc; 11164 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 11165 !getLangOpts().MicrosoftMode) { 11166 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 11167 // constant-expression in the enumerator-definition shall be a converted 11168 // constant expression of the underlying type. 11169 EltTy = Enum->getIntegerType(); 11170 ExprResult Converted = 11171 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 11172 CCEK_Enumerator); 11173 if (Converted.isInvalid()) 11174 Val = 0; 11175 else 11176 Val = Converted.take(); 11177 } else if (!Val->isValueDependent() && 11178 !(Val = VerifyIntegerConstantExpression(Val, 11179 &EnumVal).take())) { 11180 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 11181 } else { 11182 if (Enum->isFixed()) { 11183 EltTy = Enum->getIntegerType(); 11184 11185 // In Obj-C and Microsoft mode, require the enumeration value to be 11186 // representable in the underlying type of the enumeration. In C++11, 11187 // we perform a non-narrowing conversion as part of converted constant 11188 // expression checking. 11189 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11190 if (getLangOpts().MicrosoftMode) { 11191 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 11192 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11193 } else 11194 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 11195 } else 11196 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11197 } else if (getLangOpts().CPlusPlus) { 11198 // C++11 [dcl.enum]p5: 11199 // If the underlying type is not fixed, the type of each enumerator 11200 // is the type of its initializing value: 11201 // - If an initializer is specified for an enumerator, the 11202 // initializing value has the same type as the expression. 11203 EltTy = Val->getType(); 11204 } else { 11205 // C99 6.7.2.2p2: 11206 // The expression that defines the value of an enumeration constant 11207 // shall be an integer constant expression that has a value 11208 // representable as an int. 11209 11210 // Complain if the value is not representable in an int. 11211 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 11212 Diag(IdLoc, diag::ext_enum_value_not_int) 11213 << EnumVal.toString(10) << Val->getSourceRange() 11214 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 11215 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 11216 // Force the type of the expression to 'int'. 11217 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 11218 } 11219 EltTy = Val->getType(); 11220 } 11221 } 11222 } 11223 } 11224 11225 if (!Val) { 11226 if (Enum->isDependentType()) 11227 EltTy = Context.DependentTy; 11228 else if (!LastEnumConst) { 11229 // C++0x [dcl.enum]p5: 11230 // If the underlying type is not fixed, the type of each enumerator 11231 // is the type of its initializing value: 11232 // - If no initializer is specified for the first enumerator, the 11233 // initializing value has an unspecified integral type. 11234 // 11235 // GCC uses 'int' for its unspecified integral type, as does 11236 // C99 6.7.2.2p3. 11237 if (Enum->isFixed()) { 11238 EltTy = Enum->getIntegerType(); 11239 } 11240 else { 11241 EltTy = Context.IntTy; 11242 } 11243 } else { 11244 // Assign the last value + 1. 11245 EnumVal = LastEnumConst->getInitVal(); 11246 ++EnumVal; 11247 EltTy = LastEnumConst->getType(); 11248 11249 // Check for overflow on increment. 11250 if (EnumVal < LastEnumConst->getInitVal()) { 11251 // C++0x [dcl.enum]p5: 11252 // If the underlying type is not fixed, the type of each enumerator 11253 // is the type of its initializing value: 11254 // 11255 // - Otherwise the type of the initializing value is the same as 11256 // the type of the initializing value of the preceding enumerator 11257 // unless the incremented value is not representable in that type, 11258 // in which case the type is an unspecified integral type 11259 // sufficient to contain the incremented value. If no such type 11260 // exists, the program is ill-formed. 11261 QualType T = getNextLargerIntegralType(Context, EltTy); 11262 if (T.isNull() || Enum->isFixed()) { 11263 // There is no integral type larger enough to represent this 11264 // value. Complain, then allow the value to wrap around. 11265 EnumVal = LastEnumConst->getInitVal(); 11266 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 11267 ++EnumVal; 11268 if (Enum->isFixed()) 11269 // When the underlying type is fixed, this is ill-formed. 11270 Diag(IdLoc, diag::err_enumerator_wrapped) 11271 << EnumVal.toString(10) 11272 << EltTy; 11273 else 11274 Diag(IdLoc, diag::warn_enumerator_too_large) 11275 << EnumVal.toString(10); 11276 } else { 11277 EltTy = T; 11278 } 11279 11280 // Retrieve the last enumerator's value, extent that type to the 11281 // type that is supposed to be large enough to represent the incremented 11282 // value, then increment. 11283 EnumVal = LastEnumConst->getInitVal(); 11284 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11285 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 11286 ++EnumVal; 11287 11288 // If we're not in C++, diagnose the overflow of enumerator values, 11289 // which in C99 means that the enumerator value is not representable in 11290 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 11291 // permits enumerator values that are representable in some larger 11292 // integral type. 11293 if (!getLangOpts().CPlusPlus && !T.isNull()) 11294 Diag(IdLoc, diag::warn_enum_value_overflow); 11295 } else if (!getLangOpts().CPlusPlus && 11296 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11297 // Enforce C99 6.7.2.2p2 even when we compute the next value. 11298 Diag(IdLoc, diag::ext_enum_value_not_int) 11299 << EnumVal.toString(10) << 1; 11300 } 11301 } 11302 } 11303 11304 if (!EltTy->isDependentType()) { 11305 // Make the enumerator value match the signedness and size of the 11306 // enumerator's type. 11307 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 11308 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11309 } 11310 11311 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 11312 Val, EnumVal); 11313} 11314 11315 11316Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 11317 SourceLocation IdLoc, IdentifierInfo *Id, 11318 AttributeList *Attr, 11319 SourceLocation EqualLoc, Expr *Val) { 11320 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 11321 EnumConstantDecl *LastEnumConst = 11322 cast_or_null<EnumConstantDecl>(lastEnumConst); 11323 11324 // The scope passed in may not be a decl scope. Zip up the scope tree until 11325 // we find one that is. 11326 S = getNonFieldDeclScope(S); 11327 11328 // Verify that there isn't already something declared with this name in this 11329 // scope. 11330 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 11331 ForRedeclaration); 11332 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11333 // Maybe we will complain about the shadowed template parameter. 11334 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 11335 // Just pretend that we didn't see the previous declaration. 11336 PrevDecl = 0; 11337 } 11338 11339 if (PrevDecl) { 11340 // When in C++, we may get a TagDecl with the same name; in this case the 11341 // enum constant will 'hide' the tag. 11342 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 11343 "Received TagDecl when not in C++!"); 11344 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 11345 if (isa<EnumConstantDecl>(PrevDecl)) 11346 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 11347 else 11348 Diag(IdLoc, diag::err_redefinition) << Id; 11349 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11350 return 0; 11351 } 11352 } 11353 11354 // C++ [class.mem]p15: 11355 // If T is the name of a class, then each of the following shall have a name 11356 // different from T: 11357 // - every enumerator of every member of class T that is an unscoped 11358 // enumerated type 11359 if (CXXRecordDecl *Record 11360 = dyn_cast<CXXRecordDecl>( 11361 TheEnumDecl->getDeclContext()->getRedeclContext())) 11362 if (!TheEnumDecl->isScoped() && 11363 Record->getIdentifier() && Record->getIdentifier() == Id) 11364 Diag(IdLoc, diag::err_member_name_of_class) << Id; 11365 11366 EnumConstantDecl *New = 11367 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 11368 11369 if (New) { 11370 // Process attributes. 11371 if (Attr) ProcessDeclAttributeList(S, New, Attr); 11372 11373 // Register this decl in the current scope stack. 11374 New->setAccess(TheEnumDecl->getAccess()); 11375 PushOnScopeChains(New, S); 11376 } 11377 11378 ActOnDocumentableDecl(New); 11379 11380 return New; 11381} 11382 11383// Returns true when the enum initial expression does not trigger the 11384// duplicate enum warning. A few common cases are exempted as follows: 11385// Element2 = Element1 11386// Element2 = Element1 + 1 11387// Element2 = Element1 - 1 11388// Where Element2 and Element1 are from the same enum. 11389static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 11390 Expr *InitExpr = ECD->getInitExpr(); 11391 if (!InitExpr) 11392 return true; 11393 InitExpr = InitExpr->IgnoreImpCasts(); 11394 11395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 11396 if (!BO->isAdditiveOp()) 11397 return true; 11398 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 11399 if (!IL) 11400 return true; 11401 if (IL->getValue() != 1) 11402 return true; 11403 11404 InitExpr = BO->getLHS(); 11405 } 11406 11407 // This checks if the elements are from the same enum. 11408 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 11409 if (!DRE) 11410 return true; 11411 11412 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 11413 if (!EnumConstant) 11414 return true; 11415 11416 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 11417 Enum) 11418 return true; 11419 11420 return false; 11421} 11422 11423struct DupKey { 11424 int64_t val; 11425 bool isTombstoneOrEmptyKey; 11426 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 11427 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 11428}; 11429 11430static DupKey GetDupKey(const llvm::APSInt& Val) { 11431 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 11432 false); 11433} 11434 11435struct DenseMapInfoDupKey { 11436 static DupKey getEmptyKey() { return DupKey(0, true); } 11437 static DupKey getTombstoneKey() { return DupKey(1, true); } 11438 static unsigned getHashValue(const DupKey Key) { 11439 return (unsigned)(Key.val * 37); 11440 } 11441 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 11442 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 11443 LHS.val == RHS.val; 11444 } 11445}; 11446 11447// Emits a warning when an element is implicitly set a value that 11448// a previous element has already been set to. 11449static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements, 11450 unsigned NumElements, EnumDecl *Enum, 11451 QualType EnumType) { 11452 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 11453 Enum->getLocation()) == 11454 DiagnosticsEngine::Ignored) 11455 return; 11456 // Avoid anonymous enums 11457 if (!Enum->getIdentifier()) 11458 return; 11459 11460 // Only check for small enums. 11461 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 11462 return; 11463 11464 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 11465 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 11466 11467 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 11468 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 11469 ValueToVectorMap; 11470 11471 DuplicatesVector DupVector; 11472 ValueToVectorMap EnumMap; 11473 11474 // Populate the EnumMap with all values represented by enum constants without 11475 // an initialier. 11476 for (unsigned i = 0; i < NumElements; ++i) { 11477 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11478 11479 // Null EnumConstantDecl means a previous diagnostic has been emitted for 11480 // this constant. Skip this enum since it may be ill-formed. 11481 if (!ECD) { 11482 return; 11483 } 11484 11485 if (ECD->getInitExpr()) 11486 continue; 11487 11488 DupKey Key = GetDupKey(ECD->getInitVal()); 11489 DeclOrVector &Entry = EnumMap[Key]; 11490 11491 // First time encountering this value. 11492 if (Entry.isNull()) 11493 Entry = ECD; 11494 } 11495 11496 // Create vectors for any values that has duplicates. 11497 for (unsigned i = 0; i < NumElements; ++i) { 11498 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11499 if (!ValidDuplicateEnum(ECD, Enum)) 11500 continue; 11501 11502 DupKey Key = GetDupKey(ECD->getInitVal()); 11503 11504 DeclOrVector& Entry = EnumMap[Key]; 11505 if (Entry.isNull()) 11506 continue; 11507 11508 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 11509 // Ensure constants are different. 11510 if (D == ECD) 11511 continue; 11512 11513 // Create new vector and push values onto it. 11514 ECDVector *Vec = new ECDVector(); 11515 Vec->push_back(D); 11516 Vec->push_back(ECD); 11517 11518 // Update entry to point to the duplicates vector. 11519 Entry = Vec; 11520 11521 // Store the vector somewhere we can consult later for quick emission of 11522 // diagnostics. 11523 DupVector.push_back(Vec); 11524 continue; 11525 } 11526 11527 ECDVector *Vec = Entry.get<ECDVector*>(); 11528 // Make sure constants are not added more than once. 11529 if (*Vec->begin() == ECD) 11530 continue; 11531 11532 Vec->push_back(ECD); 11533 } 11534 11535 // Emit diagnostics. 11536 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 11537 DupVectorEnd = DupVector.end(); 11538 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 11539 ECDVector *Vec = *DupVectorIter; 11540 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 11541 11542 // Emit warning for one enum constant. 11543 ECDVector::iterator I = Vec->begin(); 11544 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 11545 << (*I)->getName() << (*I)->getInitVal().toString(10) 11546 << (*I)->getSourceRange(); 11547 ++I; 11548 11549 // Emit one note for each of the remaining enum constants with 11550 // the same value. 11551 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 11552 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 11553 << (*I)->getName() << (*I)->getInitVal().toString(10) 11554 << (*I)->getSourceRange(); 11555 delete Vec; 11556 } 11557} 11558 11559void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 11560 SourceLocation RBraceLoc, Decl *EnumDeclX, 11561 Decl **Elements, unsigned NumElements, 11562 Scope *S, AttributeList *Attr) { 11563 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 11564 QualType EnumType = Context.getTypeDeclType(Enum); 11565 11566 if (Attr) 11567 ProcessDeclAttributeList(S, Enum, Attr); 11568 11569 if (Enum->isDependentType()) { 11570 for (unsigned i = 0; i != NumElements; ++i) { 11571 EnumConstantDecl *ECD = 11572 cast_or_null<EnumConstantDecl>(Elements[i]); 11573 if (!ECD) continue; 11574 11575 ECD->setType(EnumType); 11576 } 11577 11578 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 11579 return; 11580 } 11581 11582 // TODO: If the result value doesn't fit in an int, it must be a long or long 11583 // long value. ISO C does not support this, but GCC does as an extension, 11584 // emit a warning. 11585 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11586 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 11587 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 11588 11589 // Verify that all the values are okay, compute the size of the values, and 11590 // reverse the list. 11591 unsigned NumNegativeBits = 0; 11592 unsigned NumPositiveBits = 0; 11593 11594 // Keep track of whether all elements have type int. 11595 bool AllElementsInt = true; 11596 11597 for (unsigned i = 0; i != NumElements; ++i) { 11598 EnumConstantDecl *ECD = 11599 cast_or_null<EnumConstantDecl>(Elements[i]); 11600 if (!ECD) continue; // Already issued a diagnostic. 11601 11602 const llvm::APSInt &InitVal = ECD->getInitVal(); 11603 11604 // Keep track of the size of positive and negative values. 11605 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 11606 NumPositiveBits = std::max(NumPositiveBits, 11607 (unsigned)InitVal.getActiveBits()); 11608 else 11609 NumNegativeBits = std::max(NumNegativeBits, 11610 (unsigned)InitVal.getMinSignedBits()); 11611 11612 // Keep track of whether every enum element has type int (very commmon). 11613 if (AllElementsInt) 11614 AllElementsInt = ECD->getType() == Context.IntTy; 11615 } 11616 11617 // Figure out the type that should be used for this enum. 11618 QualType BestType; 11619 unsigned BestWidth; 11620 11621 // C++0x N3000 [conv.prom]p3: 11622 // An rvalue of an unscoped enumeration type whose underlying 11623 // type is not fixed can be converted to an rvalue of the first 11624 // of the following types that can represent all the values of 11625 // the enumeration: int, unsigned int, long int, unsigned long 11626 // int, long long int, or unsigned long long int. 11627 // C99 6.4.4.3p2: 11628 // An identifier declared as an enumeration constant has type int. 11629 // The C99 rule is modified by a gcc extension 11630 QualType BestPromotionType; 11631 11632 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 11633 // -fshort-enums is the equivalent to specifying the packed attribute on all 11634 // enum definitions. 11635 if (LangOpts.ShortEnums) 11636 Packed = true; 11637 11638 if (Enum->isFixed()) { 11639 BestType = Enum->getIntegerType(); 11640 if (BestType->isPromotableIntegerType()) 11641 BestPromotionType = Context.getPromotedIntegerType(BestType); 11642 else 11643 BestPromotionType = BestType; 11644 // We don't need to set BestWidth, because BestType is going to be the type 11645 // of the enumerators, but we do anyway because otherwise some compilers 11646 // warn that it might be used uninitialized. 11647 BestWidth = CharWidth; 11648 } 11649 else if (NumNegativeBits) { 11650 // If there is a negative value, figure out the smallest integer type (of 11651 // int/long/longlong) that fits. 11652 // If it's packed, check also if it fits a char or a short. 11653 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 11654 BestType = Context.SignedCharTy; 11655 BestWidth = CharWidth; 11656 } else if (Packed && NumNegativeBits <= ShortWidth && 11657 NumPositiveBits < ShortWidth) { 11658 BestType = Context.ShortTy; 11659 BestWidth = ShortWidth; 11660 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 11661 BestType = Context.IntTy; 11662 BestWidth = IntWidth; 11663 } else { 11664 BestWidth = Context.getTargetInfo().getLongWidth(); 11665 11666 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 11667 BestType = Context.LongTy; 11668 } else { 11669 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11670 11671 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 11672 Diag(Enum->getLocation(), diag::warn_enum_too_large); 11673 BestType = Context.LongLongTy; 11674 } 11675 } 11676 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 11677 } else { 11678 // If there is no negative value, figure out the smallest type that fits 11679 // all of the enumerator values. 11680 // If it's packed, check also if it fits a char or a short. 11681 if (Packed && NumPositiveBits <= CharWidth) { 11682 BestType = Context.UnsignedCharTy; 11683 BestPromotionType = Context.IntTy; 11684 BestWidth = CharWidth; 11685 } else if (Packed && NumPositiveBits <= ShortWidth) { 11686 BestType = Context.UnsignedShortTy; 11687 BestPromotionType = Context.IntTy; 11688 BestWidth = ShortWidth; 11689 } else if (NumPositiveBits <= IntWidth) { 11690 BestType = Context.UnsignedIntTy; 11691 BestWidth = IntWidth; 11692 BestPromotionType 11693 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11694 ? Context.UnsignedIntTy : Context.IntTy; 11695 } else if (NumPositiveBits <= 11696 (BestWidth = Context.getTargetInfo().getLongWidth())) { 11697 BestType = Context.UnsignedLongTy; 11698 BestPromotionType 11699 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11700 ? Context.UnsignedLongTy : Context.LongTy; 11701 } else { 11702 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11703 assert(NumPositiveBits <= BestWidth && 11704 "How could an initializer get larger than ULL?"); 11705 BestType = Context.UnsignedLongLongTy; 11706 BestPromotionType 11707 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11708 ? Context.UnsignedLongLongTy : Context.LongLongTy; 11709 } 11710 } 11711 11712 // Loop over all of the enumerator constants, changing their types to match 11713 // the type of the enum if needed. 11714 for (unsigned i = 0; i != NumElements; ++i) { 11715 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 11716 if (!ECD) continue; // Already issued a diagnostic. 11717 11718 // Standard C says the enumerators have int type, but we allow, as an 11719 // extension, the enumerators to be larger than int size. If each 11720 // enumerator value fits in an int, type it as an int, otherwise type it the 11721 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 11722 // that X has type 'int', not 'unsigned'. 11723 11724 // Determine whether the value fits into an int. 11725 llvm::APSInt InitVal = ECD->getInitVal(); 11726 11727 // If it fits into an integer type, force it. Otherwise force it to match 11728 // the enum decl type. 11729 QualType NewTy; 11730 unsigned NewWidth; 11731 bool NewSign; 11732 if (!getLangOpts().CPlusPlus && 11733 !Enum->isFixed() && 11734 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 11735 NewTy = Context.IntTy; 11736 NewWidth = IntWidth; 11737 NewSign = true; 11738 } else if (ECD->getType() == BestType) { 11739 // Already the right type! 11740 if (getLangOpts().CPlusPlus) 11741 // C++ [dcl.enum]p4: Following the closing brace of an 11742 // enum-specifier, each enumerator has the type of its 11743 // enumeration. 11744 ECD->setType(EnumType); 11745 continue; 11746 } else { 11747 NewTy = BestType; 11748 NewWidth = BestWidth; 11749 NewSign = BestType->isSignedIntegerOrEnumerationType(); 11750 } 11751 11752 // Adjust the APSInt value. 11753 InitVal = InitVal.extOrTrunc(NewWidth); 11754 InitVal.setIsSigned(NewSign); 11755 ECD->setInitVal(InitVal); 11756 11757 // Adjust the Expr initializer and type. 11758 if (ECD->getInitExpr() && 11759 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 11760 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 11761 CK_IntegralCast, 11762 ECD->getInitExpr(), 11763 /*base paths*/ 0, 11764 VK_RValue)); 11765 if (getLangOpts().CPlusPlus) 11766 // C++ [dcl.enum]p4: Following the closing brace of an 11767 // enum-specifier, each enumerator has the type of its 11768 // enumeration. 11769 ECD->setType(EnumType); 11770 else 11771 ECD->setType(NewTy); 11772 } 11773 11774 Enum->completeDefinition(BestType, BestPromotionType, 11775 NumPositiveBits, NumNegativeBits); 11776 11777 // If we're declaring a function, ensure this decl isn't forgotten about - 11778 // it needs to go into the function scope. 11779 if (InFunctionDeclarator) 11780 DeclsInPrototypeScope.push_back(Enum); 11781 11782 CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType); 11783 11784 // Now that the enum type is defined, ensure it's not been underaligned. 11785 if (Enum->hasAttrs()) 11786 CheckAlignasUnderalignment(Enum); 11787} 11788 11789Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 11790 SourceLocation StartLoc, 11791 SourceLocation EndLoc) { 11792 StringLiteral *AsmString = cast<StringLiteral>(expr); 11793 11794 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 11795 AsmString, StartLoc, 11796 EndLoc); 11797 CurContext->addDecl(New); 11798 return New; 11799} 11800 11801DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 11802 SourceLocation ImportLoc, 11803 ModuleIdPath Path) { 11804 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 11805 Module::AllVisible, 11806 /*IsIncludeDirective=*/false); 11807 if (!Mod) 11808 return true; 11809 11810 SmallVector<SourceLocation, 2> IdentifierLocs; 11811 Module *ModCheck = Mod; 11812 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 11813 // If we've run out of module parents, just drop the remaining identifiers. 11814 // We need the length to be consistent. 11815 if (!ModCheck) 11816 break; 11817 ModCheck = ModCheck->Parent; 11818 11819 IdentifierLocs.push_back(Path[I].second); 11820 } 11821 11822 ImportDecl *Import = ImportDecl::Create(Context, 11823 Context.getTranslationUnitDecl(), 11824 AtLoc.isValid()? AtLoc : ImportLoc, 11825 Mod, IdentifierLocs); 11826 Context.getTranslationUnitDecl()->addDecl(Import); 11827 return Import; 11828} 11829 11830void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 11831 // Create the implicit import declaration. 11832 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 11833 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 11834 Loc, Mod, Loc); 11835 TU->addDecl(ImportD); 11836 Consumer.HandleImplicitImportDecl(ImportD); 11837 11838 // Make the module visible. 11839 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 11840 /*Complain=*/false); 11841} 11842 11843void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 11844 IdentifierInfo* AliasName, 11845 SourceLocation PragmaLoc, 11846 SourceLocation NameLoc, 11847 SourceLocation AliasNameLoc) { 11848 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 11849 LookupOrdinaryName); 11850 AsmLabelAttr *Attr = 11851 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 11852 11853 if (PrevDecl) 11854 PrevDecl->addAttr(Attr); 11855 else 11856 (void)ExtnameUndeclaredIdentifiers.insert( 11857 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 11858} 11859 11860void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 11861 SourceLocation PragmaLoc, 11862 SourceLocation NameLoc) { 11863 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 11864 11865 if (PrevDecl) { 11866 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 11867 } else { 11868 (void)WeakUndeclaredIdentifiers.insert( 11869 std::pair<IdentifierInfo*,WeakInfo> 11870 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 11871 } 11872} 11873 11874void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 11875 IdentifierInfo* AliasName, 11876 SourceLocation PragmaLoc, 11877 SourceLocation NameLoc, 11878 SourceLocation AliasNameLoc) { 11879 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 11880 LookupOrdinaryName); 11881 WeakInfo W = WeakInfo(Name, NameLoc); 11882 11883 if (PrevDecl) { 11884 if (!PrevDecl->hasAttr<AliasAttr>()) 11885 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 11886 DeclApplyPragmaWeak(TUScope, ND, W); 11887 } else { 11888 (void)WeakUndeclaredIdentifiers.insert( 11889 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 11890 } 11891} 11892 11893Decl *Sema::getObjCDeclContext() const { 11894 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 11895} 11896 11897AvailabilityResult Sema::getCurContextAvailability() const { 11898 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 11899 return D->getAvailability(); 11900} 11901