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