SemaDecl.cpp revision 263508
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "TypeLocBuilder.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/ASTLambda.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/CommentDiagnostic.h" 22#include "clang/AST/DeclCXX.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/DeclTemplate.h" 25#include "clang/AST/EvaluatedExprVisitor.h" 26#include "clang/AST/ExprCXX.h" 27#include "clang/AST/StmtCXX.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 32#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 33#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 34#include "clang/Parse/ParseDiagnostic.h" 35#include "clang/Sema/CXXFieldCollector.h" 36#include "clang/Sema/DeclSpec.h" 37#include "clang/Sema/DelayedDiagnostic.h" 38#include "clang/Sema/Initialization.h" 39#include "clang/Sema/Lookup.h" 40#include "clang/Sema/ParsedTemplate.h" 41#include "clang/Sema/Scope.h" 42#include "clang/Sema/ScopeInfo.h" 43#include "clang/Sema/Template.h" 44#include "llvm/ADT/SmallString.h" 45#include "llvm/ADT/Triple.h" 46#include <algorithm> 47#include <cstring> 48#include <functional> 49using namespace clang; 50using namespace sema; 51 52Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 53 if (OwnedType) { 54 Decl *Group[2] = { OwnedType, Ptr }; 55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 56 } 57 58 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 59} 60 61namespace { 62 63class TypeNameValidatorCCC : public CorrectionCandidateCallback { 64 public: 65 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 67 WantExpressionKeywords = false; 68 WantCXXNamedCasts = false; 69 WantRemainingKeywords = false; 70 } 71 72 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 73 if (NamedDecl *ND = candidate.getCorrectionDecl()) 74 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 75 (AllowInvalidDecl || !ND->isInvalidDecl()); 76 else 77 return !WantClassName && candidate.isKeyword(); 78 } 79 80 private: 81 bool AllowInvalidDecl; 82 bool WantClassName; 83}; 84 85} 86 87/// \brief Determine whether the token kind starts a simple-type-specifier. 88bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 89 switch (Kind) { 90 // FIXME: Take into account the current language when deciding whether a 91 // token kind is a valid type specifier 92 case tok::kw_short: 93 case tok::kw_long: 94 case tok::kw___int64: 95 case tok::kw___int128: 96 case tok::kw_signed: 97 case tok::kw_unsigned: 98 case tok::kw_void: 99 case tok::kw_char: 100 case tok::kw_int: 101 case tok::kw_half: 102 case tok::kw_float: 103 case tok::kw_double: 104 case tok::kw_wchar_t: 105 case tok::kw_bool: 106 case tok::kw___underlying_type: 107 return true; 108 109 case tok::annot_typename: 110 case tok::kw_char16_t: 111 case tok::kw_char32_t: 112 case tok::kw_typeof: 113 case tok::annot_decltype: 114 case tok::kw_decltype: 115 return getLangOpts().CPlusPlus; 116 117 default: 118 break; 119 } 120 121 return false; 122} 123 124/// \brief If the identifier refers to a type name within this scope, 125/// return the declaration of that type. 126/// 127/// This routine performs ordinary name lookup of the identifier II 128/// within the given scope, with optional C++ scope specifier SS, to 129/// determine whether the name refers to a type. If so, returns an 130/// opaque pointer (actually a QualType) corresponding to that 131/// type. Otherwise, returns NULL. 132ParsedType Sema::getTypeName(const 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 diagnoseTypo(Correction, 241 PDiag(diag::err_unknown_type_or_class_name_suggest) 242 << Result.getLookupName() << isClassName); 243 if (SS && NNS) 244 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 245 *CorrectedII = NewII; 246 return Ty; 247 } 248 } 249 } 250 // If typo correction failed or was not performed, fall through 251 case LookupResult::FoundOverloaded: 252 case LookupResult::FoundUnresolvedValue: 253 Result.suppressDiagnostics(); 254 return ParsedType(); 255 256 case LookupResult::Ambiguous: 257 // Recover from type-hiding ambiguities by hiding the type. We'll 258 // do the lookup again when looking for an object, and we can 259 // diagnose the error then. If we don't do this, then the error 260 // about hiding the type will be immediately followed by an error 261 // that only makes sense if the identifier was treated like a type. 262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 263 Result.suppressDiagnostics(); 264 return ParsedType(); 265 } 266 267 // Look to see if we have a type anywhere in the list of results. 268 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 269 Res != ResEnd; ++Res) { 270 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 271 if (!IIDecl || 272 (*Res)->getLocation().getRawEncoding() < 273 IIDecl->getLocation().getRawEncoding()) 274 IIDecl = *Res; 275 } 276 } 277 278 if (!IIDecl) { 279 // None of the entities we found is a type, so there is no way 280 // to even assume that the result is a type. In this case, don't 281 // complain about the ambiguity. The parser will either try to 282 // perform this lookup again (e.g., as an object name), which 283 // will produce the ambiguity, or will complain that it expected 284 // a type name. 285 Result.suppressDiagnostics(); 286 return ParsedType(); 287 } 288 289 // We found a type within the ambiguous lookup; diagnose the 290 // ambiguity and then return that type. This might be the right 291 // answer, or it might not be, but it suppresses any attempt to 292 // perform the name lookup again. 293 break; 294 295 case LookupResult::Found: 296 IIDecl = Result.getFoundDecl(); 297 break; 298 } 299 300 assert(IIDecl && "Didn't find decl"); 301 302 QualType T; 303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 304 DiagnoseUseOfDecl(IIDecl, NameLoc); 305 306 if (T.isNull()) 307 T = Context.getTypeDeclType(TD); 308 309 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 310 // constructor or destructor name (in such a case, the scope specifier 311 // will be attached to the enclosing Expr or Decl node). 312 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 313 if (WantNontrivialTypeSourceInfo) { 314 // Construct a type with type-source information. 315 TypeLocBuilder Builder; 316 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 317 318 T = getElaboratedType(ETK_None, *SS, T); 319 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 320 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 321 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 322 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 323 } else { 324 T = getElaboratedType(ETK_None, *SS, T); 325 } 326 } 327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 328 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 329 if (!HasTrailingDot) 330 T = Context.getObjCInterfaceType(IDecl); 331 } 332 333 if (T.isNull()) { 334 // If it's not plausibly a type, suppress diagnostics. 335 Result.suppressDiagnostics(); 336 return ParsedType(); 337 } 338 return ParsedType::make(T); 339} 340 341/// isTagName() - This method is called *for error recovery purposes only* 342/// to determine if the specified name is a valid tag name ("struct foo"). If 343/// so, this returns the TST for the tag corresponding to it (TST_enum, 344/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 345/// cases in C where the user forgot to specify the tag. 346DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 347 // Do a tag name lookup in this scope. 348 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 349 LookupName(R, S, false); 350 R.suppressDiagnostics(); 351 if (R.getResultKind() == LookupResult::Found) 352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 353 switch (TD->getTagKind()) { 354 case TTK_Struct: return DeclSpec::TST_struct; 355 case TTK_Interface: return DeclSpec::TST_interface; 356 case TTK_Union: return DeclSpec::TST_union; 357 case TTK_Class: return DeclSpec::TST_class; 358 case TTK_Enum: return DeclSpec::TST_enum; 359 } 360 } 361 362 return DeclSpec::TST_unspecified; 363} 364 365/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 366/// if a CXXScopeSpec's type is equal to the type of one of the base classes 367/// then downgrade the missing typename error to a warning. 368/// This is needed for MSVC compatibility; Example: 369/// @code 370/// template<class T> class A { 371/// public: 372/// typedef int TYPE; 373/// }; 374/// template<class T> class B : public A<T> { 375/// public: 376/// A<T>::TYPE a; // no typename required because A<T> is a base class. 377/// }; 378/// @endcode 379bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 380 if (CurContext->isRecord()) { 381 const Type *Ty = SS->getScopeRep()->getAsType(); 382 383 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 384 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 385 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 386 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 387 return true; 388 return S->isFunctionPrototypeScope(); 389 } 390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 391} 392 393bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 394 SourceLocation IILoc, 395 Scope *S, 396 CXXScopeSpec *SS, 397 ParsedType &SuggestedType) { 398 // We don't have anything to suggest (yet). 399 SuggestedType = ParsedType(); 400 401 // There may have been a typo in the name of the type. Look up typo 402 // results, in case we have something that we can suggest. 403 TypeNameValidatorCCC Validator(false); 404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 405 LookupOrdinaryName, S, SS, 406 Validator)) { 407 if (Corrected.isKeyword()) { 408 // We corrected to a keyword. 409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 410 II = Corrected.getCorrectionAsIdentifierInfo(); 411 } else { 412 // We found a similarly-named type or interface; suggest that. 413 if (!SS || !SS->isSet()) { 414 diagnoseTypo(Corrected, 415 PDiag(diag::err_unknown_typename_suggest) << II); 416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 417 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 419 II->getName().equals(CorrectedStr); 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_nested_typename_suggest) 422 << II << DC << DroppedSpecifier << SS->getRange()); 423 } else { 424 llvm_unreachable("could not have corrected a typo here"); 425 } 426 427 CXXScopeSpec tmpSS; 428 if (Corrected.getCorrectionSpecifier()) 429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 430 SourceRange(IILoc)); 431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 433 false, ParsedType(), 434 /*IsCtorOrDtorName=*/false, 435 /*NonTrivialTypeSourceInfo=*/true); 436 } 437 return true; 438 } 439 440 if (getLangOpts().CPlusPlus) { 441 // See if II is a class template that the user forgot to pass arguments to. 442 UnqualifiedId Name; 443 Name.setIdentifier(II, IILoc); 444 CXXScopeSpec EmptySS; 445 TemplateTy TemplateResult; 446 bool MemberOfUnknownSpecialization; 447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 448 Name, ParsedType(), true, TemplateResult, 449 MemberOfUnknownSpecialization) == TNK_Type_template) { 450 TemplateName TplName = TemplateResult.get(); 451 Diag(IILoc, diag::err_template_missing_args) << TplName; 452 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 453 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 454 << TplDecl->getTemplateParameters()->getSourceRange(); 455 } 456 return true; 457 } 458 } 459 460 // FIXME: Should we move the logic that tries to recover from a missing tag 461 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 462 463 if (!SS || (!SS->isSet() && !SS->isInvalid())) 464 Diag(IILoc, diag::err_unknown_typename) << II; 465 else if (DeclContext *DC = computeDeclContext(*SS, false)) 466 Diag(IILoc, diag::err_typename_nested_not_found) 467 << II << DC << SS->getRange(); 468 else if (isDependentScopeSpecifier(*SS)) { 469 unsigned DiagID = diag::err_typename_missing; 470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 471 DiagID = diag::warn_typename_missing; 472 473 Diag(SS->getRange().getBegin(), DiagID) 474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 475 << SourceRange(SS->getRange().getBegin(), IILoc) 476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 477 SuggestedType = ActOnTypenameType(S, SourceLocation(), 478 *SS, *II, IILoc).get(); 479 } else { 480 assert(SS && SS->isInvalid() && 481 "Invalid scope specifier has already been diagnosed"); 482 } 483 484 return true; 485} 486 487/// \brief Determine whether the given result set contains either a type name 488/// or 489static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 491 NextToken.is(tok::less); 492 493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 495 return true; 496 497 if (CheckTemplate && isa<TemplateDecl>(*I)) 498 return true; 499 } 500 501 return false; 502} 503 504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 505 Scope *S, CXXScopeSpec &SS, 506 IdentifierInfo *&Name, 507 SourceLocation NameLoc) { 508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 509 SemaRef.LookupParsedName(R, S, &SS); 510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 511 const char *TagName = 0; 512 const char *FixItTagName = 0; 513 switch (Tag->getTagKind()) { 514 case TTK_Class: 515 TagName = "class"; 516 FixItTagName = "class "; 517 break; 518 519 case TTK_Enum: 520 TagName = "enum"; 521 FixItTagName = "enum "; 522 break; 523 524 case TTK_Struct: 525 TagName = "struct"; 526 FixItTagName = "struct "; 527 break; 528 529 case TTK_Interface: 530 TagName = "__interface"; 531 FixItTagName = "__interface "; 532 break; 533 534 case TTK_Union: 535 TagName = "union"; 536 FixItTagName = "union "; 537 break; 538 } 539 540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 542 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 543 544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 545 I != IEnd; ++I) 546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 547 << Name << TagName; 548 549 // Replace lookup results with just the tag decl. 550 Result.clear(Sema::LookupTagName); 551 SemaRef.LookupParsedName(Result, S, &SS); 552 return true; 553 } 554 555 return false; 556} 557 558/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 559static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 560 QualType T, SourceLocation NameLoc) { 561 ASTContext &Context = S.Context; 562 563 TypeLocBuilder Builder; 564 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 565 566 T = S.getElaboratedType(ETK_None, SS, T); 567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 568 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 571} 572 573Sema::NameClassification Sema::ClassifyName(Scope *S, 574 CXXScopeSpec &SS, 575 IdentifierInfo *&Name, 576 SourceLocation NameLoc, 577 const Token &NextToken, 578 bool IsAddressOfOperand, 579 CorrectionCandidateCallback *CCC) { 580 DeclarationNameInfo NameInfo(Name, NameLoc); 581 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 582 583 if (NextToken.is(tok::coloncolon)) { 584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 585 QualType(), false, SS, 0, false); 586 587 } 588 589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 590 LookupParsedName(Result, S, &SS, !CurMethod); 591 592 // Perform lookup for Objective-C instance variables (including automatically 593 // synthesized instance variables), if we're in an Objective-C method. 594 // FIXME: This lookup really, really needs to be folded in to the normal 595 // unqualified lookup mechanism. 596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 597 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 598 if (E.get() || E.isInvalid()) 599 return E; 600 } 601 602 bool SecondTry = false; 603 bool IsFilteredTemplateName = false; 604 605Corrected: 606 switch (Result.getResultKind()) { 607 case LookupResult::NotFound: 608 // If an unqualified-id is followed by a '(', then we have a function 609 // call. 610 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 611 // In C++, this is an ADL-only call. 612 // FIXME: Reference? 613 if (getLangOpts().CPlusPlus) 614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 615 616 // C90 6.3.2.2: 617 // If the expression that precedes the parenthesized argument list in a 618 // function call consists solely of an identifier, and if no 619 // declaration is visible for this identifier, the identifier is 620 // implicitly declared exactly as if, in the innermost block containing 621 // the function call, the declaration 622 // 623 // extern int identifier (); 624 // 625 // appeared. 626 // 627 // We also allow this in C99 as an extension. 628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 629 Result.addDecl(D); 630 Result.resolveKind(); 631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 632 } 633 } 634 635 // In C, we first see whether there is a tag type by the same name, in 636 // which case it's likely that the user just forget to write "enum", 637 // "struct", or "union". 638 if (!getLangOpts().CPlusPlus && !SecondTry && 639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 640 break; 641 } 642 643 // Perform typo correction to determine if there is another name that is 644 // close to this name. 645 if (!SecondTry && CCC) { 646 SecondTry = true; 647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 648 Result.getLookupKind(), S, 649 &SS, *CCC)) { 650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 651 unsigned QualifiedDiag = diag::err_no_member_suggest; 652 653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 654 NamedDecl *UnderlyingFirstDecl 655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 658 UnqualifiedDiag = diag::err_no_template_suggest; 659 QualifiedDiag = diag::err_no_member_template_suggest; 660 } else if (UnderlyingFirstDecl && 661 (isa<TypeDecl>(UnderlyingFirstDecl) || 662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 664 UnqualifiedDiag = diag::err_unknown_typename_suggest; 665 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 666 } 667 668 if (SS.isEmpty()) { 669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 670 } else {// FIXME: is this even reachable? Test it. 671 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 673 Name->getName().equals(CorrectedStr); 674 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 675 << Name << computeDeclContext(SS, false) 676 << DroppedSpecifier << SS.getRange()); 677 } 678 679 // Update the name, so that the caller has the new name. 680 Name = Corrected.getCorrectionAsIdentifierInfo(); 681 682 // Typo correction corrected to a keyword. 683 if (Corrected.isKeyword()) 684 return Name; 685 686 // Also update the LookupResult... 687 // FIXME: This should probably go away at some point 688 Result.clear(); 689 Result.setLookupName(Corrected.getCorrection()); 690 if (FirstDecl) 691 Result.addDecl(FirstDecl); 692 693 // If we found an Objective-C instance variable, let 694 // LookupInObjCMethod build the appropriate expression to 695 // reference the ivar. 696 // FIXME: This is a gross hack. 697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 698 Result.clear(); 699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 700 return E; 701 } 702 703 goto Corrected; 704 } 705 } 706 707 // We failed to correct; just fall through and let the parser deal with it. 708 Result.suppressDiagnostics(); 709 return NameClassification::Unknown(); 710 711 case LookupResult::NotFoundInCurrentInstantiation: { 712 // We performed name lookup into the current instantiation, and there were 713 // dependent bases, so we treat this result the same way as any other 714 // dependent nested-name-specifier. 715 716 // C++ [temp.res]p2: 717 // A name used in a template declaration or definition and that is 718 // dependent on a template-parameter is assumed not to name a type 719 // unless the applicable name lookup finds a type name or the name is 720 // qualified by the keyword typename. 721 // 722 // FIXME: If the next token is '<', we might want to ask the parser to 723 // perform some heroics to see if we actually have a 724 // template-argument-list, which would indicate a missing 'template' 725 // keyword here. 726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 727 NameInfo, IsAddressOfOperand, 728 /*TemplateArgs=*/0); 729 } 730 731 case LookupResult::Found: 732 case LookupResult::FoundOverloaded: 733 case LookupResult::FoundUnresolvedValue: 734 break; 735 736 case LookupResult::Ambiguous: 737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 738 hasAnyAcceptableTemplateNames(Result)) { 739 // C++ [temp.local]p3: 740 // A lookup that finds an injected-class-name (10.2) can result in an 741 // ambiguity in certain cases (for example, if it is found in more than 742 // one base class). If all of the injected-class-names that are found 743 // refer to specializations of the same class template, and if the name 744 // is followed by a template-argument-list, the reference refers to the 745 // class template itself and not a specialization thereof, and is not 746 // ambiguous. 747 // 748 // This filtering can make an ambiguous result into an unambiguous one, 749 // so try again after filtering out template names. 750 FilterAcceptableTemplateNames(Result); 751 if (!Result.isAmbiguous()) { 752 IsFilteredTemplateName = true; 753 break; 754 } 755 } 756 757 // Diagnose the ambiguity and return an error. 758 return NameClassification::Error(); 759 } 760 761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 763 // C++ [temp.names]p3: 764 // After name lookup (3.4) finds that a name is a template-name or that 765 // an operator-function-id or a literal- operator-id refers to a set of 766 // overloaded functions any member of which is a function template if 767 // this is followed by a <, the < is always taken as the delimiter of a 768 // template-argument-list and never as the less-than operator. 769 if (!IsFilteredTemplateName) 770 FilterAcceptableTemplateNames(Result); 771 772 if (!Result.empty()) { 773 bool IsFunctionTemplate; 774 bool IsVarTemplate; 775 TemplateName Template; 776 if (Result.end() - Result.begin() > 1) { 777 IsFunctionTemplate = true; 778 Template = Context.getOverloadedTemplateName(Result.begin(), 779 Result.end()); 780 } else { 781 TemplateDecl *TD 782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 784 IsVarTemplate = isa<VarTemplateDecl>(TD); 785 786 if (SS.isSet() && !SS.isInvalid()) 787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 788 /*TemplateKeyword=*/false, 789 TD); 790 else 791 Template = TemplateName(TD); 792 } 793 794 if (IsFunctionTemplate) { 795 // Function templates always go through overload resolution, at which 796 // point we'll perform the various checks (e.g., accessibility) we need 797 // to based on which function we selected. 798 Result.suppressDiagnostics(); 799 800 return NameClassification::FunctionTemplate(Template); 801 } 802 803 return IsVarTemplate ? NameClassification::VarTemplate(Template) 804 : NameClassification::TypeTemplate(Template); 805 } 806 } 807 808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 810 DiagnoseUseOfDecl(Type, NameLoc); 811 QualType T = Context.getTypeDeclType(Type); 812 if (SS.isNotEmpty()) 813 return buildNestedType(*this, SS, T, NameLoc); 814 return ParsedType::make(T); 815 } 816 817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 818 if (!Class) { 819 // FIXME: It's unfortunate that we don't have a Type node for handling this. 820 if (ObjCCompatibleAliasDecl *Alias 821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 822 Class = Alias->getClassInterface(); 823 } 824 825 if (Class) { 826 DiagnoseUseOfDecl(Class, NameLoc); 827 828 if (NextToken.is(tok::period)) { 829 // Interface. <something> is parsed as a property reference expression. 830 // Just return "unknown" as a fall-through for now. 831 Result.suppressDiagnostics(); 832 return NameClassification::Unknown(); 833 } 834 835 QualType T = Context.getObjCInterfaceType(Class); 836 return ParsedType::make(T); 837 } 838 839 // We can have a type template here if we're classifying a template argument. 840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 841 return NameClassification::TypeTemplate( 842 TemplateName(cast<TemplateDecl>(FirstDecl))); 843 844 // Check for a tag type hidden by a non-type decl in a few cases where it 845 // seems likely a type is wanted instead of the non-type that was found. 846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 847 if ((NextToken.is(tok::identifier) || 848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 850 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 851 DiagnoseUseOfDecl(Type, NameLoc); 852 QualType T = Context.getTypeDeclType(Type); 853 if (SS.isNotEmpty()) 854 return buildNestedType(*this, SS, T, NameLoc); 855 return ParsedType::make(T); 856 } 857 858 if (FirstDecl->isCXXClassMember()) 859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 860 861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 862 return BuildDeclarationNameExpr(SS, Result, ADL); 863} 864 865// Determines the context to return to after temporarily entering a 866// context. This depends in an unnecessarily complicated way on the 867// exact ordering of callbacks from the parser. 868DeclContext *Sema::getContainingDC(DeclContext *DC) { 869 870 // Functions defined inline within classes aren't parsed until we've 871 // finished parsing the top-level class, so the top-level class is 872 // the context we'll need to return to. 873 // A Lambda call operator whose parent is a class must not be treated 874 // as an inline member function. A Lambda can be used legally 875 // either as an in-class member initializer or a default argument. These 876 // are parsed once the class has been marked complete and so the containing 877 // context would be the nested class (when the lambda is defined in one); 878 // If the class is not complete, then the lambda is being used in an 879 // ill-formed fashion (such as to specify the width of a bit-field, or 880 // in an array-bound) - in which case we still want to return the 881 // lexically containing DC (which could be a nested class). 882 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 883 DC = DC->getLexicalParent(); 884 885 // A function not defined within a class will always return to its 886 // lexical context. 887 if (!isa<CXXRecordDecl>(DC)) 888 return DC; 889 890 // A C++ inline method/friend is parsed *after* the topmost class 891 // it was declared in is fully parsed ("complete"); the topmost 892 // class is the context we need to return to. 893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 894 DC = RD; 895 896 // Return the declaration context of the topmost class the inline method is 897 // declared in. 898 return DC; 899 } 900 901 return DC->getLexicalParent(); 902} 903 904void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 905 assert(getContainingDC(DC) == CurContext && 906 "The next DeclContext should be lexically contained in the current one."); 907 CurContext = DC; 908 S->setEntity(DC); 909} 910 911void Sema::PopDeclContext() { 912 assert(CurContext && "DeclContext imbalance!"); 913 914 CurContext = getContainingDC(CurContext); 915 assert(CurContext && "Popped translation unit!"); 916} 917 918/// EnterDeclaratorContext - Used when we must lookup names in the context 919/// of a declarator's nested name specifier. 920/// 921void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 922 // C++0x [basic.lookup.unqual]p13: 923 // A name used in the definition of a static data member of class 924 // X (after the qualified-id of the static member) is looked up as 925 // if the name was used in a member function of X. 926 // C++0x [basic.lookup.unqual]p14: 927 // If a variable member of a namespace is defined outside of the 928 // scope of its namespace then any name used in the definition of 929 // the variable member (after the declarator-id) is looked up as 930 // if the definition of the variable member occurred in its 931 // namespace. 932 // Both of these imply that we should push a scope whose context 933 // is the semantic context of the declaration. We can't use 934 // PushDeclContext here because that context is not necessarily 935 // lexically contained in the current context. Fortunately, 936 // the containing scope should have the appropriate information. 937 938 assert(!S->getEntity() && "scope already has entity"); 939 940#ifndef NDEBUG 941 Scope *Ancestor = S->getParent(); 942 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 943 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 944#endif 945 946 CurContext = DC; 947 S->setEntity(DC); 948} 949 950void Sema::ExitDeclaratorContext(Scope *S) { 951 assert(S->getEntity() == CurContext && "Context imbalance!"); 952 953 // Switch back to the lexical context. The safety of this is 954 // enforced by an assert in EnterDeclaratorContext. 955 Scope *Ancestor = S->getParent(); 956 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 957 CurContext = Ancestor->getEntity(); 958 959 // We don't need to do anything with the scope, which is going to 960 // disappear. 961} 962 963 964void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 965 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 966 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 967 // We assume that the caller has already called 968 // ActOnReenterTemplateScope 969 FD = TFD->getTemplatedDecl(); 970 } 971 if (!FD) 972 return; 973 974 // Same implementation as PushDeclContext, but enters the context 975 // from the lexical parent, rather than the top-level class. 976 assert(CurContext == FD->getLexicalParent() && 977 "The next DeclContext should be lexically contained in the current one."); 978 CurContext = FD; 979 S->setEntity(CurContext); 980 981 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 982 ParmVarDecl *Param = FD->getParamDecl(P); 983 // If the parameter has an identifier, then add it to the scope 984 if (Param->getIdentifier()) { 985 S->AddDecl(Param); 986 IdResolver.AddDecl(Param); 987 } 988 } 989} 990 991 992void Sema::ActOnExitFunctionContext() { 993 // Same implementation as PopDeclContext, but returns to the lexical parent, 994 // rather than the top-level class. 995 assert(CurContext && "DeclContext imbalance!"); 996 CurContext = CurContext->getLexicalParent(); 997 assert(CurContext && "Popped translation unit!"); 998} 999 1000 1001/// \brief Determine whether we allow overloading of the function 1002/// PrevDecl with another declaration. 1003/// 1004/// This routine determines whether overloading is possible, not 1005/// whether some new function is actually an overload. It will return 1006/// true in C++ (where we can always provide overloads) or, as an 1007/// extension, in C when the previous function is already an 1008/// overloaded function declaration or has the "overloadable" 1009/// attribute. 1010static bool AllowOverloadingOfFunction(LookupResult &Previous, 1011 ASTContext &Context) { 1012 if (Context.getLangOpts().CPlusPlus) 1013 return true; 1014 1015 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1016 return true; 1017 1018 return (Previous.getResultKind() == LookupResult::Found 1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1020} 1021 1022/// Add this decl to the scope shadowed decl chains. 1023void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1024 // Move up the scope chain until we find the nearest enclosing 1025 // non-transparent context. The declaration will be introduced into this 1026 // scope. 1027 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1028 S = S->getParent(); 1029 1030 // Add scoped declarations into their context, so that they can be 1031 // found later. Declarations without a context won't be inserted 1032 // into any context. 1033 if (AddToContext) 1034 CurContext->addDecl(D); 1035 1036 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1037 // are function-local declarations. 1038 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1039 !D->getDeclContext()->getRedeclContext()->Equals( 1040 D->getLexicalDeclContext()->getRedeclContext()) && 1041 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1042 return; 1043 1044 // Template instantiations should also not be pushed into scope. 1045 if (isa<FunctionDecl>(D) && 1046 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1047 return; 1048 1049 // If this replaces anything in the current scope, 1050 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1051 IEnd = IdResolver.end(); 1052 for (; I != IEnd; ++I) { 1053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1054 S->RemoveDecl(*I); 1055 IdResolver.RemoveDecl(*I); 1056 1057 // Should only need to replace one decl. 1058 break; 1059 } 1060 } 1061 1062 S->AddDecl(D); 1063 1064 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1065 // Implicitly-generated labels may end up getting generated in an order that 1066 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1067 // the label at the appropriate place in the identifier chain. 1068 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1070 if (IDC == CurContext) { 1071 if (!S->isDeclScope(*I)) 1072 continue; 1073 } else if (IDC->Encloses(CurContext)) 1074 break; 1075 } 1076 1077 IdResolver.InsertDeclAfter(I, D); 1078 } else { 1079 IdResolver.AddDecl(D); 1080 } 1081} 1082 1083void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1084 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1085 TUScope->AddDecl(D); 1086} 1087 1088bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1089 bool ExplicitInstantiationOrSpecialization) { 1090 return IdResolver.isDeclInScope(D, Ctx, S, 1091 ExplicitInstantiationOrSpecialization); 1092} 1093 1094Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1095 DeclContext *TargetDC = DC->getPrimaryContext(); 1096 do { 1097 if (DeclContext *ScopeDC = S->getEntity()) 1098 if (ScopeDC->getPrimaryContext() == TargetDC) 1099 return S; 1100 } while ((S = S->getParent())); 1101 1102 return 0; 1103} 1104 1105static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1106 DeclContext*, 1107 ASTContext&); 1108 1109/// Filters out lookup results that don't fall within the given scope 1110/// as determined by isDeclInScope. 1111void Sema::FilterLookupForScope(LookupResult &R, 1112 DeclContext *Ctx, Scope *S, 1113 bool ConsiderLinkage, 1114 bool ExplicitInstantiationOrSpecialization) { 1115 LookupResult::Filter F = R.makeFilter(); 1116 while (F.hasNext()) { 1117 NamedDecl *D = F.next(); 1118 1119 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1120 continue; 1121 1122 if (ConsiderLinkage && 1123 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1124 continue; 1125 1126 F.erase(); 1127 } 1128 1129 F.done(); 1130} 1131 1132static bool isUsingDecl(NamedDecl *D) { 1133 return isa<UsingShadowDecl>(D) || 1134 isa<UnresolvedUsingTypenameDecl>(D) || 1135 isa<UnresolvedUsingValueDecl>(D); 1136} 1137 1138/// Removes using shadow declarations from the lookup results. 1139static void RemoveUsingDecls(LookupResult &R) { 1140 LookupResult::Filter F = R.makeFilter(); 1141 while (F.hasNext()) 1142 if (isUsingDecl(F.next())) 1143 F.erase(); 1144 1145 F.done(); 1146} 1147 1148/// \brief Check for this common pattern: 1149/// @code 1150/// class S { 1151/// S(const S&); // DO NOT IMPLEMENT 1152/// void operator=(const S&); // DO NOT IMPLEMENT 1153/// }; 1154/// @endcode 1155static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1156 // FIXME: Should check for private access too but access is set after we get 1157 // the decl here. 1158 if (D->doesThisDeclarationHaveABody()) 1159 return false; 1160 1161 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1162 return CD->isCopyConstructor(); 1163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1164 return Method->isCopyAssignmentOperator(); 1165 return false; 1166} 1167 1168// We need this to handle 1169// 1170// typedef struct { 1171// void *foo() { return 0; } 1172// } A; 1173// 1174// When we see foo we don't know if after the typedef we will get 'A' or '*A' 1175// for example. If 'A', foo will have external linkage. If we have '*A', 1176// foo will have no linkage. Since we can't know untill we get to the end 1177// of the typedef, this function finds out if D might have non external linkage. 1178// Callers should verify at the end of the TU if it D has external linkage or 1179// not. 1180bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1181 const DeclContext *DC = D->getDeclContext(); 1182 while (!DC->isTranslationUnit()) { 1183 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1184 if (!RD->hasNameForLinkage()) 1185 return true; 1186 } 1187 DC = DC->getParent(); 1188 } 1189 1190 return !D->isExternallyVisible(); 1191} 1192 1193// FIXME: This needs to be refactored; some other isInMainFile users want 1194// these semantics. 1195static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1196 if (S.TUKind != TU_Complete) 1197 return false; 1198 return S.SourceMgr.isInMainFile(Loc); 1199} 1200 1201bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1202 assert(D); 1203 1204 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1205 return false; 1206 1207 // Ignore class templates. 1208 if (D->getDeclContext()->isDependentContext() || 1209 D->getLexicalDeclContext()->isDependentContext()) 1210 return false; 1211 1212 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1213 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1214 return false; 1215 1216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1217 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1218 return false; 1219 } else { 1220 // 'static inline' functions are defined in headers; don't warn. 1221 if (FD->isInlineSpecified() && 1222 !isMainFileLoc(*this, FD->getLocation())) 1223 return false; 1224 } 1225 1226 if (FD->doesThisDeclarationHaveABody() && 1227 Context.DeclMustBeEmitted(FD)) 1228 return false; 1229 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1230 // Constants and utility variables are defined in headers with internal 1231 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1232 // like "inline".) 1233 if (!isMainFileLoc(*this, VD->getLocation())) 1234 return false; 1235 1236 if (Context.DeclMustBeEmitted(VD)) 1237 return false; 1238 1239 if (VD->isStaticDataMember() && 1240 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1241 return false; 1242 } else { 1243 return false; 1244 } 1245 1246 // Only warn for unused decls internal to the translation unit. 1247 return mightHaveNonExternalLinkage(D); 1248} 1249 1250void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1251 if (!D) 1252 return; 1253 1254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1255 const FunctionDecl *First = FD->getFirstDecl(); 1256 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1257 return; // First should already be in the vector. 1258 } 1259 1260 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1261 const VarDecl *First = VD->getFirstDecl(); 1262 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1263 return; // First should already be in the vector. 1264 } 1265 1266 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1267 UnusedFileScopedDecls.push_back(D); 1268} 1269 1270static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1271 if (D->isInvalidDecl()) 1272 return false; 1273 1274 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1275 return false; 1276 1277 if (isa<LabelDecl>(D)) 1278 return true; 1279 1280 // White-list anything that isn't a local variable. 1281 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1282 !D->getDeclContext()->isFunctionOrMethod()) 1283 return false; 1284 1285 // Types of valid local variables should be complete, so this should succeed. 1286 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1287 1288 // White-list anything with an __attribute__((unused)) type. 1289 QualType Ty = VD->getType(); 1290 1291 // Only look at the outermost level of typedef. 1292 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1293 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1294 return false; 1295 } 1296 1297 // If we failed to complete the type for some reason, or if the type is 1298 // dependent, don't diagnose the variable. 1299 if (Ty->isIncompleteType() || Ty->isDependentType()) 1300 return false; 1301 1302 if (const TagType *TT = Ty->getAs<TagType>()) { 1303 const TagDecl *Tag = TT->getDecl(); 1304 if (Tag->hasAttr<UnusedAttr>()) 1305 return false; 1306 1307 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1308 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1309 return false; 1310 1311 if (const Expr *Init = VD->getInit()) { 1312 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1313 Init = Cleanups->getSubExpr(); 1314 const CXXConstructExpr *Construct = 1315 dyn_cast<CXXConstructExpr>(Init); 1316 if (Construct && !Construct->isElidable()) { 1317 CXXConstructorDecl *CD = Construct->getConstructor(); 1318 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1319 return false; 1320 } 1321 } 1322 } 1323 } 1324 1325 // TODO: __attribute__((unused)) templates? 1326 } 1327 1328 return true; 1329} 1330 1331static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1332 FixItHint &Hint) { 1333 if (isa<LabelDecl>(D)) { 1334 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1335 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1336 if (AfterColon.isInvalid()) 1337 return; 1338 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1339 getCharRange(D->getLocStart(), AfterColon)); 1340 } 1341 return; 1342} 1343 1344/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1345/// unless they are marked attr(unused). 1346void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1347 FixItHint Hint; 1348 if (!ShouldDiagnoseUnusedDecl(D)) 1349 return; 1350 1351 GenerateFixForUnusedDecl(D, Context, Hint); 1352 1353 unsigned DiagID; 1354 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1355 DiagID = diag::warn_unused_exception_param; 1356 else if (isa<LabelDecl>(D)) 1357 DiagID = diag::warn_unused_label; 1358 else 1359 DiagID = diag::warn_unused_variable; 1360 1361 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1362} 1363 1364static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1365 // Verify that we have no forward references left. If so, there was a goto 1366 // or address of a label taken, but no definition of it. Label fwd 1367 // definitions are indicated with a null substmt. 1368 if (L->getStmt() == 0) 1369 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1370} 1371 1372void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1373 if (S->decl_empty()) return; 1374 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1375 "Scope shouldn't contain decls!"); 1376 1377 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1378 I != E; ++I) { 1379 Decl *TmpD = (*I); 1380 assert(TmpD && "This decl didn't get pushed??"); 1381 1382 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1383 NamedDecl *D = cast<NamedDecl>(TmpD); 1384 1385 if (!D->getDeclName()) continue; 1386 1387 // Diagnose unused variables in this scope. 1388 if (!S->hasUnrecoverableErrorOccurred()) 1389 DiagnoseUnusedDecl(D); 1390 1391 // If this was a forward reference to a label, verify it was defined. 1392 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1393 CheckPoppedLabel(LD, *this); 1394 1395 // Remove this name from our lexical scope. 1396 IdResolver.RemoveDecl(D); 1397 } 1398 DiagnoseUnusedBackingIvarInAccessor(S); 1399} 1400 1401void Sema::ActOnStartFunctionDeclarator() { 1402 ++InFunctionDeclarator; 1403} 1404 1405void Sema::ActOnEndFunctionDeclarator() { 1406 assert(InFunctionDeclarator); 1407 --InFunctionDeclarator; 1408} 1409 1410/// \brief Look for an Objective-C class in the translation unit. 1411/// 1412/// \param Id The name of the Objective-C class we're looking for. If 1413/// typo-correction fixes this name, the Id will be updated 1414/// to the fixed name. 1415/// 1416/// \param IdLoc The location of the name in the translation unit. 1417/// 1418/// \param DoTypoCorrection If true, this routine will attempt typo correction 1419/// if there is no class with the given name. 1420/// 1421/// \returns The declaration of the named Objective-C class, or NULL if the 1422/// class could not be found. 1423ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1424 SourceLocation IdLoc, 1425 bool DoTypoCorrection) { 1426 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1427 // creation from this context. 1428 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1429 1430 if (!IDecl && DoTypoCorrection) { 1431 // Perform typo correction at the given location, but only if we 1432 // find an Objective-C class name. 1433 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1434 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1435 LookupOrdinaryName, TUScope, NULL, 1436 Validator)) { 1437 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1438 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1439 Id = IDecl->getIdentifier(); 1440 } 1441 } 1442 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1443 // This routine must always return a class definition, if any. 1444 if (Def && Def->getDefinition()) 1445 Def = Def->getDefinition(); 1446 return Def; 1447} 1448 1449/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1450/// from S, where a non-field would be declared. This routine copes 1451/// with the difference between C and C++ scoping rules in structs and 1452/// unions. For example, the following code is well-formed in C but 1453/// ill-formed in C++: 1454/// @code 1455/// struct S6 { 1456/// enum { BAR } e; 1457/// }; 1458/// 1459/// void test_S6() { 1460/// struct S6 a; 1461/// a.e = BAR; 1462/// } 1463/// @endcode 1464/// For the declaration of BAR, this routine will return a different 1465/// scope. The scope S will be the scope of the unnamed enumeration 1466/// within S6. In C++, this routine will return the scope associated 1467/// with S6, because the enumeration's scope is a transparent 1468/// context but structures can contain non-field names. In C, this 1469/// routine will return the translation unit scope, since the 1470/// enumeration's scope is a transparent context and structures cannot 1471/// contain non-field names. 1472Scope *Sema::getNonFieldDeclScope(Scope *S) { 1473 while (((S->getFlags() & Scope::DeclScope) == 0) || 1474 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1475 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1476 S = S->getParent(); 1477 return S; 1478} 1479 1480/// \brief Looks up the declaration of "struct objc_super" and 1481/// saves it for later use in building builtin declaration of 1482/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1483/// pre-existing declaration exists no action takes place. 1484static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1485 IdentifierInfo *II) { 1486 if (!II->isStr("objc_msgSendSuper")) 1487 return; 1488 ASTContext &Context = ThisSema.Context; 1489 1490 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1491 SourceLocation(), Sema::LookupTagName); 1492 ThisSema.LookupName(Result, S); 1493 if (Result.getResultKind() == LookupResult::Found) 1494 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1495 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1496} 1497 1498/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1499/// file scope. lazily create a decl for it. ForRedeclaration is true 1500/// if we're creating this built-in in anticipation of redeclaring the 1501/// built-in. 1502NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1503 Scope *S, bool ForRedeclaration, 1504 SourceLocation Loc) { 1505 LookupPredefedObjCSuperType(*this, S, II); 1506 1507 Builtin::ID BID = (Builtin::ID)bid; 1508 1509 ASTContext::GetBuiltinTypeError Error; 1510 QualType R = Context.GetBuiltinType(BID, Error); 1511 switch (Error) { 1512 case ASTContext::GE_None: 1513 // Okay 1514 break; 1515 1516 case ASTContext::GE_Missing_stdio: 1517 if (ForRedeclaration) 1518 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1519 << Context.BuiltinInfo.GetName(BID); 1520 return 0; 1521 1522 case ASTContext::GE_Missing_setjmp: 1523 if (ForRedeclaration) 1524 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1525 << Context.BuiltinInfo.GetName(BID); 1526 return 0; 1527 1528 case ASTContext::GE_Missing_ucontext: 1529 if (ForRedeclaration) 1530 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1531 << Context.BuiltinInfo.GetName(BID); 1532 return 0; 1533 } 1534 1535 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1536 Diag(Loc, diag::ext_implicit_lib_function_decl) 1537 << Context.BuiltinInfo.GetName(BID) 1538 << R; 1539 if (Context.BuiltinInfo.getHeaderName(BID) && 1540 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1541 != DiagnosticsEngine::Ignored) 1542 Diag(Loc, diag::note_please_include_header) 1543 << Context.BuiltinInfo.getHeaderName(BID) 1544 << Context.BuiltinInfo.GetName(BID); 1545 } 1546 1547 DeclContext *Parent = Context.getTranslationUnitDecl(); 1548 if (getLangOpts().CPlusPlus) { 1549 LinkageSpecDecl *CLinkageDecl = 1550 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1551 LinkageSpecDecl::lang_c, false); 1552 Parent->addDecl(CLinkageDecl); 1553 Parent = CLinkageDecl; 1554 } 1555 1556 FunctionDecl *New = FunctionDecl::Create(Context, 1557 Parent, 1558 Loc, Loc, II, R, /*TInfo=*/0, 1559 SC_Extern, 1560 false, 1561 /*hasPrototype=*/true); 1562 New->setImplicit(); 1563 1564 // Create Decl objects for each parameter, adding them to the 1565 // FunctionDecl. 1566 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1567 SmallVector<ParmVarDecl*, 16> Params; 1568 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1569 ParmVarDecl *parm = 1570 ParmVarDecl::Create(Context, New, SourceLocation(), 1571 SourceLocation(), 0, 1572 FT->getArgType(i), /*TInfo=*/0, 1573 SC_None, 0); 1574 parm->setScopeInfo(0, i); 1575 Params.push_back(parm); 1576 } 1577 New->setParams(Params); 1578 } 1579 1580 AddKnownFunctionAttributes(New); 1581 RegisterLocallyScopedExternCDecl(New, S); 1582 1583 // TUScope is the translation-unit scope to insert this function into. 1584 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1585 // relate Scopes to DeclContexts, and probably eliminate CurContext 1586 // entirely, but we're not there yet. 1587 DeclContext *SavedContext = CurContext; 1588 CurContext = Parent; 1589 PushOnScopeChains(New, TUScope); 1590 CurContext = SavedContext; 1591 return New; 1592} 1593 1594/// \brief Filter out any previous declarations that the given declaration 1595/// should not consider because they are not permitted to conflict, e.g., 1596/// because they come from hidden sub-modules and do not refer to the same 1597/// entity. 1598static void filterNonConflictingPreviousDecls(ASTContext &context, 1599 NamedDecl *decl, 1600 LookupResult &previous){ 1601 // This is only interesting when modules are enabled. 1602 if (!context.getLangOpts().Modules) 1603 return; 1604 1605 // Empty sets are uninteresting. 1606 if (previous.empty()) 1607 return; 1608 1609 LookupResult::Filter filter = previous.makeFilter(); 1610 while (filter.hasNext()) { 1611 NamedDecl *old = filter.next(); 1612 1613 // Non-hidden declarations are never ignored. 1614 if (!old->isHidden()) 1615 continue; 1616 1617 if (!old->isExternallyVisible()) 1618 filter.erase(); 1619 } 1620 1621 filter.done(); 1622} 1623 1624bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1625 QualType OldType; 1626 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1627 OldType = OldTypedef->getUnderlyingType(); 1628 else 1629 OldType = Context.getTypeDeclType(Old); 1630 QualType NewType = New->getUnderlyingType(); 1631 1632 if (NewType->isVariablyModifiedType()) { 1633 // Must not redefine a typedef with a variably-modified type. 1634 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1635 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1636 << Kind << NewType; 1637 if (Old->getLocation().isValid()) 1638 Diag(Old->getLocation(), diag::note_previous_definition); 1639 New->setInvalidDecl(); 1640 return true; 1641 } 1642 1643 if (OldType != NewType && 1644 !OldType->isDependentType() && 1645 !NewType->isDependentType() && 1646 !Context.hasSameType(OldType, NewType)) { 1647 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1648 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1649 << Kind << NewType << OldType; 1650 if (Old->getLocation().isValid()) 1651 Diag(Old->getLocation(), diag::note_previous_definition); 1652 New->setInvalidDecl(); 1653 return true; 1654 } 1655 return false; 1656} 1657 1658/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1659/// same name and scope as a previous declaration 'Old'. Figure out 1660/// how to resolve this situation, merging decls or emitting 1661/// diagnostics as appropriate. If there was an error, set New to be invalid. 1662/// 1663void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1664 // If the new decl is known invalid already, don't bother doing any 1665 // merging checks. 1666 if (New->isInvalidDecl()) return; 1667 1668 // Allow multiple definitions for ObjC built-in typedefs. 1669 // FIXME: Verify the underlying types are equivalent! 1670 if (getLangOpts().ObjC1) { 1671 const IdentifierInfo *TypeID = New->getIdentifier(); 1672 switch (TypeID->getLength()) { 1673 default: break; 1674 case 2: 1675 { 1676 if (!TypeID->isStr("id")) 1677 break; 1678 QualType T = New->getUnderlyingType(); 1679 if (!T->isPointerType()) 1680 break; 1681 if (!T->isVoidPointerType()) { 1682 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1683 if (!PT->isStructureType()) 1684 break; 1685 } 1686 Context.setObjCIdRedefinitionType(T); 1687 // Install the built-in type for 'id', ignoring the current definition. 1688 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1689 return; 1690 } 1691 case 5: 1692 if (!TypeID->isStr("Class")) 1693 break; 1694 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1695 // Install the built-in type for 'Class', ignoring the current definition. 1696 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1697 return; 1698 case 3: 1699 if (!TypeID->isStr("SEL")) 1700 break; 1701 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1702 // Install the built-in type for 'SEL', ignoring the current definition. 1703 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1704 return; 1705 } 1706 // Fall through - the typedef name was not a builtin type. 1707 } 1708 1709 // Verify the old decl was also a type. 1710 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1711 if (!Old) { 1712 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1713 << New->getDeclName(); 1714 1715 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1716 if (OldD->getLocation().isValid()) 1717 Diag(OldD->getLocation(), diag::note_previous_definition); 1718 1719 return New->setInvalidDecl(); 1720 } 1721 1722 // If the old declaration is invalid, just give up here. 1723 if (Old->isInvalidDecl()) 1724 return New->setInvalidDecl(); 1725 1726 // If the typedef types are not identical, reject them in all languages and 1727 // with any extensions enabled. 1728 if (isIncompatibleTypedef(Old, New)) 1729 return; 1730 1731 // The types match. Link up the redeclaration chain and merge attributes if 1732 // the old declaration was a typedef. 1733 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1734 New->setPreviousDecl(Typedef); 1735 mergeDeclAttributes(New, Old); 1736 } 1737 1738 if (getLangOpts().MicrosoftExt) 1739 return; 1740 1741 if (getLangOpts().CPlusPlus) { 1742 // C++ [dcl.typedef]p2: 1743 // In a given non-class scope, a typedef specifier can be used to 1744 // redefine the name of any type declared in that scope to refer 1745 // to the type to which it already refers. 1746 if (!isa<CXXRecordDecl>(CurContext)) 1747 return; 1748 1749 // C++0x [dcl.typedef]p4: 1750 // In a given class scope, a typedef specifier can be used to redefine 1751 // any class-name declared in that scope that is not also a typedef-name 1752 // to refer to the type to which it already refers. 1753 // 1754 // This wording came in via DR424, which was a correction to the 1755 // wording in DR56, which accidentally banned code like: 1756 // 1757 // struct S { 1758 // typedef struct A { } A; 1759 // }; 1760 // 1761 // in the C++03 standard. We implement the C++0x semantics, which 1762 // allow the above but disallow 1763 // 1764 // struct S { 1765 // typedef int I; 1766 // typedef int I; 1767 // }; 1768 // 1769 // since that was the intent of DR56. 1770 if (!isa<TypedefNameDecl>(Old)) 1771 return; 1772 1773 Diag(New->getLocation(), diag::err_redefinition) 1774 << New->getDeclName(); 1775 Diag(Old->getLocation(), diag::note_previous_definition); 1776 return New->setInvalidDecl(); 1777 } 1778 1779 // Modules always permit redefinition of typedefs, as does C11. 1780 if (getLangOpts().Modules || getLangOpts().C11) 1781 return; 1782 1783 // If we have a redefinition of a typedef in C, emit a warning. This warning 1784 // is normally mapped to an error, but can be controlled with 1785 // -Wtypedef-redefinition. If either the original or the redefinition is 1786 // in a system header, don't emit this for compatibility with GCC. 1787 if (getDiagnostics().getSuppressSystemWarnings() && 1788 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1789 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1790 return; 1791 1792 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1793 << New->getDeclName(); 1794 Diag(Old->getLocation(), diag::note_previous_definition); 1795 return; 1796} 1797 1798/// DeclhasAttr - returns true if decl Declaration already has the target 1799/// attribute. 1800static bool 1801DeclHasAttr(const Decl *D, const Attr *A) { 1802 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1803 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1804 // responsible for making sure they are consistent. 1805 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1806 if (AA) 1807 return false; 1808 1809 // The following thread safety attributes can also be duplicated. 1810 switch (A->getKind()) { 1811 case attr::ExclusiveLocksRequired: 1812 case attr::SharedLocksRequired: 1813 case attr::LocksExcluded: 1814 case attr::ExclusiveLockFunction: 1815 case attr::SharedLockFunction: 1816 case attr::UnlockFunction: 1817 case attr::ExclusiveTrylockFunction: 1818 case attr::SharedTrylockFunction: 1819 case attr::GuardedBy: 1820 case attr::PtGuardedBy: 1821 case attr::AcquiredBefore: 1822 case attr::AcquiredAfter: 1823 return false; 1824 default: 1825 ; 1826 } 1827 1828 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1829 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1830 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1831 if ((*i)->getKind() == A->getKind()) { 1832 if (Ann) { 1833 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1834 return true; 1835 continue; 1836 } 1837 // FIXME: Don't hardcode this check 1838 if (OA && isa<OwnershipAttr>(*i)) 1839 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1840 return true; 1841 } 1842 1843 return false; 1844} 1845 1846static bool isAttributeTargetADefinition(Decl *D) { 1847 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1848 return VD->isThisDeclarationADefinition(); 1849 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1850 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1851 return true; 1852} 1853 1854/// Merge alignment attributes from \p Old to \p New, taking into account the 1855/// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1856/// 1857/// \return \c true if any attributes were added to \p New. 1858static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1859 // Look for alignas attributes on Old, and pick out whichever attribute 1860 // specifies the strictest alignment requirement. 1861 AlignedAttr *OldAlignasAttr = 0; 1862 AlignedAttr *OldStrictestAlignAttr = 0; 1863 unsigned OldAlign = 0; 1864 for (specific_attr_iterator<AlignedAttr> 1865 I = Old->specific_attr_begin<AlignedAttr>(), 1866 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1867 // FIXME: We have no way of representing inherited dependent alignments 1868 // in a case like: 1869 // template<int A, int B> struct alignas(A) X; 1870 // template<int A, int B> struct alignas(B) X {}; 1871 // For now, we just ignore any alignas attributes which are not on the 1872 // definition in such a case. 1873 if (I->isAlignmentDependent()) 1874 return false; 1875 1876 if (I->isAlignas()) 1877 OldAlignasAttr = *I; 1878 1879 unsigned Align = I->getAlignment(S.Context); 1880 if (Align > OldAlign) { 1881 OldAlign = Align; 1882 OldStrictestAlignAttr = *I; 1883 } 1884 } 1885 1886 // Look for alignas attributes on New. 1887 AlignedAttr *NewAlignasAttr = 0; 1888 unsigned NewAlign = 0; 1889 for (specific_attr_iterator<AlignedAttr> 1890 I = New->specific_attr_begin<AlignedAttr>(), 1891 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1892 if (I->isAlignmentDependent()) 1893 return false; 1894 1895 if (I->isAlignas()) 1896 NewAlignasAttr = *I; 1897 1898 unsigned Align = I->getAlignment(S.Context); 1899 if (Align > NewAlign) 1900 NewAlign = Align; 1901 } 1902 1903 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1904 // Both declarations have 'alignas' attributes. We require them to match. 1905 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1906 // fall short. (If two declarations both have alignas, they must both match 1907 // every definition, and so must match each other if there is a definition.) 1908 1909 // If either declaration only contains 'alignas(0)' specifiers, then it 1910 // specifies the natural alignment for the type. 1911 if (OldAlign == 0 || NewAlign == 0) { 1912 QualType Ty; 1913 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1914 Ty = VD->getType(); 1915 else 1916 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1917 1918 if (OldAlign == 0) 1919 OldAlign = S.Context.getTypeAlign(Ty); 1920 if (NewAlign == 0) 1921 NewAlign = S.Context.getTypeAlign(Ty); 1922 } 1923 1924 if (OldAlign != NewAlign) { 1925 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1926 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1927 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1928 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1929 } 1930 } 1931 1932 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1933 // C++11 [dcl.align]p6: 1934 // if any declaration of an entity has an alignment-specifier, 1935 // every defining declaration of that entity shall specify an 1936 // equivalent alignment. 1937 // C11 6.7.5/7: 1938 // If the definition of an object does not have an alignment 1939 // specifier, any other declaration of that object shall also 1940 // have no alignment specifier. 1941 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1942 << OldAlignasAttr->isC11(); 1943 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1944 << OldAlignasAttr->isC11(); 1945 } 1946 1947 bool AnyAdded = false; 1948 1949 // Ensure we have an attribute representing the strictest alignment. 1950 if (OldAlign > NewAlign) { 1951 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1952 Clone->setInherited(true); 1953 New->addAttr(Clone); 1954 AnyAdded = true; 1955 } 1956 1957 // Ensure we have an alignas attribute if the old declaration had one. 1958 if (OldAlignasAttr && !NewAlignasAttr && 1959 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1960 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1961 Clone->setInherited(true); 1962 New->addAttr(Clone); 1963 AnyAdded = true; 1964 } 1965 1966 return AnyAdded; 1967} 1968 1969static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1970 bool Override) { 1971 InheritableAttr *NewAttr = NULL; 1972 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1973 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1974 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1975 AA->getIntroduced(), AA->getDeprecated(), 1976 AA->getObsoleted(), AA->getUnavailable(), 1977 AA->getMessage(), Override, 1978 AttrSpellingListIndex); 1979 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1980 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1981 AttrSpellingListIndex); 1982 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1983 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1984 AttrSpellingListIndex); 1985 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1986 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1987 AttrSpellingListIndex); 1988 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1989 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1990 AttrSpellingListIndex); 1991 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1992 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1993 FA->getFormatIdx(), FA->getFirstArg(), 1994 AttrSpellingListIndex); 1995 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1996 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1997 AttrSpellingListIndex); 1998 else if (isa<AlignedAttr>(Attr)) 1999 // AlignedAttrs are handled separately, because we need to handle all 2000 // such attributes on a declaration at the same time. 2001 NewAttr = 0; 2002 else if (!DeclHasAttr(D, Attr)) 2003 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2004 2005 if (NewAttr) { 2006 NewAttr->setInherited(true); 2007 D->addAttr(NewAttr); 2008 return true; 2009 } 2010 2011 return false; 2012} 2013 2014static const Decl *getDefinition(const Decl *D) { 2015 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2016 return TD->getDefinition(); 2017 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2018 const VarDecl *Def = VD->getDefinition(); 2019 if (Def) 2020 return Def; 2021 return VD->getActingDefinition(); 2022 } 2023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2024 const FunctionDecl* Def; 2025 if (FD->isDefined(Def)) 2026 return Def; 2027 } 2028 return NULL; 2029} 2030 2031static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2032 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2033 I != E; ++I) { 2034 Attr *Attribute = *I; 2035 if (Attribute->getKind() == Kind) 2036 return true; 2037 } 2038 return false; 2039} 2040 2041/// checkNewAttributesAfterDef - If we already have a definition, check that 2042/// there are no new attributes in this declaration. 2043static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2044 if (!New->hasAttrs()) 2045 return; 2046 2047 const Decl *Def = getDefinition(Old); 2048 if (!Def || Def == New) 2049 return; 2050 2051 AttrVec &NewAttributes = New->getAttrs(); 2052 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2053 const Attr *NewAttribute = NewAttributes[I]; 2054 2055 if (isa<AliasAttr>(NewAttribute)) { 2056 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2057 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2058 else { 2059 VarDecl *VD = cast<VarDecl>(New); 2060 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2061 VarDecl::TentativeDefinition 2062 ? diag::err_alias_after_tentative 2063 : diag::err_redefinition; 2064 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2065 S.Diag(Def->getLocation(), diag::note_previous_definition); 2066 VD->setInvalidDecl(); 2067 } 2068 ++I; 2069 continue; 2070 } 2071 2072 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2073 // Tentative definitions are only interesting for the alias check above. 2074 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2075 ++I; 2076 continue; 2077 } 2078 } 2079 2080 if (hasAttribute(Def, NewAttribute->getKind())) { 2081 ++I; 2082 continue; // regular attr merging will take care of validating this. 2083 } 2084 2085 if (isa<C11NoReturnAttr>(NewAttribute)) { 2086 // C's _Noreturn is allowed to be added to a function after it is defined. 2087 ++I; 2088 continue; 2089 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2090 if (AA->isAlignas()) { 2091 // C++11 [dcl.align]p6: 2092 // if any declaration of an entity has an alignment-specifier, 2093 // every defining declaration of that entity shall specify an 2094 // equivalent alignment. 2095 // C11 6.7.5/7: 2096 // If the definition of an object does not have an alignment 2097 // specifier, any other declaration of that object shall also 2098 // have no alignment specifier. 2099 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2100 << AA->isC11(); 2101 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2102 << AA->isC11(); 2103 NewAttributes.erase(NewAttributes.begin() + I); 2104 --E; 2105 continue; 2106 } 2107 } 2108 2109 S.Diag(NewAttribute->getLocation(), 2110 diag::warn_attribute_precede_definition); 2111 S.Diag(Def->getLocation(), diag::note_previous_definition); 2112 NewAttributes.erase(NewAttributes.begin() + I); 2113 --E; 2114 } 2115} 2116 2117/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2118void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2119 AvailabilityMergeKind AMK) { 2120 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2121 UsedAttr *NewAttr = OldAttr->clone(Context); 2122 NewAttr->setInherited(true); 2123 New->addAttr(NewAttr); 2124 } 2125 2126 if (!Old->hasAttrs() && !New->hasAttrs()) 2127 return; 2128 2129 // attributes declared post-definition are currently ignored 2130 checkNewAttributesAfterDef(*this, New, Old); 2131 2132 if (!Old->hasAttrs()) 2133 return; 2134 2135 bool foundAny = New->hasAttrs(); 2136 2137 // Ensure that any moving of objects within the allocated map is done before 2138 // we process them. 2139 if (!foundAny) New->setAttrs(AttrVec()); 2140 2141 for (specific_attr_iterator<InheritableAttr> 2142 i = Old->specific_attr_begin<InheritableAttr>(), 2143 e = Old->specific_attr_end<InheritableAttr>(); 2144 i != e; ++i) { 2145 bool Override = false; 2146 // Ignore deprecated/unavailable/availability attributes if requested. 2147 if (isa<DeprecatedAttr>(*i) || 2148 isa<UnavailableAttr>(*i) || 2149 isa<AvailabilityAttr>(*i)) { 2150 switch (AMK) { 2151 case AMK_None: 2152 continue; 2153 2154 case AMK_Redeclaration: 2155 break; 2156 2157 case AMK_Override: 2158 Override = true; 2159 break; 2160 } 2161 } 2162 2163 // Already handled. 2164 if (isa<UsedAttr>(*i)) 2165 continue; 2166 2167 if (mergeDeclAttribute(*this, New, *i, Override)) 2168 foundAny = true; 2169 } 2170 2171 if (mergeAlignedAttrs(*this, New, Old)) 2172 foundAny = true; 2173 2174 if (!foundAny) New->dropAttrs(); 2175} 2176 2177/// mergeParamDeclAttributes - Copy attributes from the old parameter 2178/// to the new one. 2179static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2180 const ParmVarDecl *oldDecl, 2181 Sema &S) { 2182 // C++11 [dcl.attr.depend]p2: 2183 // The first declaration of a function shall specify the 2184 // carries_dependency attribute for its declarator-id if any declaration 2185 // of the function specifies the carries_dependency attribute. 2186 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2187 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2188 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2189 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2190 // Find the first declaration of the parameter. 2191 // FIXME: Should we build redeclaration chains for function parameters? 2192 const FunctionDecl *FirstFD = 2193 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2194 const ParmVarDecl *FirstVD = 2195 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2196 S.Diag(FirstVD->getLocation(), 2197 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2198 } 2199 2200 if (!oldDecl->hasAttrs()) 2201 return; 2202 2203 bool foundAny = newDecl->hasAttrs(); 2204 2205 // Ensure that any moving of objects within the allocated map is 2206 // done before we process them. 2207 if (!foundAny) newDecl->setAttrs(AttrVec()); 2208 2209 for (specific_attr_iterator<InheritableParamAttr> 2210 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2211 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2212 if (!DeclHasAttr(newDecl, *i)) { 2213 InheritableAttr *newAttr = 2214 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2215 newAttr->setInherited(true); 2216 newDecl->addAttr(newAttr); 2217 foundAny = true; 2218 } 2219 } 2220 2221 if (!foundAny) newDecl->dropAttrs(); 2222} 2223 2224namespace { 2225 2226/// Used in MergeFunctionDecl to keep track of function parameters in 2227/// C. 2228struct GNUCompatibleParamWarning { 2229 ParmVarDecl *OldParm; 2230 ParmVarDecl *NewParm; 2231 QualType PromotedType; 2232}; 2233 2234} 2235 2236/// getSpecialMember - get the special member enum for a method. 2237Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2238 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2239 if (Ctor->isDefaultConstructor()) 2240 return Sema::CXXDefaultConstructor; 2241 2242 if (Ctor->isCopyConstructor()) 2243 return Sema::CXXCopyConstructor; 2244 2245 if (Ctor->isMoveConstructor()) 2246 return Sema::CXXMoveConstructor; 2247 } else if (isa<CXXDestructorDecl>(MD)) { 2248 return Sema::CXXDestructor; 2249 } else if (MD->isCopyAssignmentOperator()) { 2250 return Sema::CXXCopyAssignment; 2251 } else if (MD->isMoveAssignmentOperator()) { 2252 return Sema::CXXMoveAssignment; 2253 } 2254 2255 return Sema::CXXInvalid; 2256} 2257 2258/// canRedefineFunction - checks if a function can be redefined. Currently, 2259/// only extern inline functions can be redefined, and even then only in 2260/// GNU89 mode. 2261static bool canRedefineFunction(const FunctionDecl *FD, 2262 const LangOptions& LangOpts) { 2263 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2264 !LangOpts.CPlusPlus && 2265 FD->isInlineSpecified() && 2266 FD->getStorageClass() == SC_Extern); 2267} 2268 2269const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2270 const AttributedType *AT = T->getAs<AttributedType>(); 2271 while (AT && !AT->isCallingConv()) 2272 AT = AT->getModifiedType()->getAs<AttributedType>(); 2273 return AT; 2274} 2275 2276template <typename T> 2277static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2278 const DeclContext *DC = Old->getDeclContext(); 2279 if (DC->isRecord()) 2280 return false; 2281 2282 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2283 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2284 return true; 2285 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2286 return true; 2287 return false; 2288} 2289 2290/// MergeFunctionDecl - We just parsed a function 'New' from 2291/// declarator D which has the same name and scope as a previous 2292/// declaration 'Old'. Figure out how to resolve this situation, 2293/// merging decls or emitting diagnostics as appropriate. 2294/// 2295/// In C++, New and Old must be declarations that are not 2296/// overloaded. Use IsOverload to determine whether New and Old are 2297/// overloaded, and to select the Old declaration that New should be 2298/// merged with. 2299/// 2300/// Returns true if there was an error, false otherwise. 2301bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S, 2302 bool MergeTypeWithOld) { 2303 // Verify the old decl was also a function. 2304 FunctionDecl *Old = 0; 2305 if (FunctionTemplateDecl *OldFunctionTemplate 2306 = dyn_cast<FunctionTemplateDecl>(OldD)) 2307 Old = OldFunctionTemplate->getTemplatedDecl(); 2308 else 2309 Old = dyn_cast<FunctionDecl>(OldD); 2310 if (!Old) { 2311 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2312 if (New->getFriendObjectKind()) { 2313 Diag(New->getLocation(), diag::err_using_decl_friend); 2314 Diag(Shadow->getTargetDecl()->getLocation(), 2315 diag::note_using_decl_target); 2316 Diag(Shadow->getUsingDecl()->getLocation(), 2317 diag::note_using_decl) << 0; 2318 return true; 2319 } 2320 2321 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2322 Diag(Shadow->getTargetDecl()->getLocation(), 2323 diag::note_using_decl_target); 2324 Diag(Shadow->getUsingDecl()->getLocation(), 2325 diag::note_using_decl) << 0; 2326 return true; 2327 } 2328 2329 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2330 << New->getDeclName(); 2331 Diag(OldD->getLocation(), diag::note_previous_definition); 2332 return true; 2333 } 2334 2335 // If the old declaration is invalid, just give up here. 2336 if (Old->isInvalidDecl()) 2337 return true; 2338 2339 // Determine whether the previous declaration was a definition, 2340 // implicit declaration, or a declaration. 2341 diag::kind PrevDiag; 2342 if (Old->isThisDeclarationADefinition()) 2343 PrevDiag = diag::note_previous_definition; 2344 else if (Old->isImplicit()) 2345 PrevDiag = diag::note_previous_implicit_declaration; 2346 else 2347 PrevDiag = diag::note_previous_declaration; 2348 2349 // Don't complain about this if we're in GNU89 mode and the old function 2350 // is an extern inline function. 2351 // Don't complain about specializations. They are not supposed to have 2352 // storage classes. 2353 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2354 New->getStorageClass() == SC_Static && 2355 Old->hasExternalFormalLinkage() && 2356 !New->getTemplateSpecializationInfo() && 2357 !canRedefineFunction(Old, getLangOpts())) { 2358 if (getLangOpts().MicrosoftExt) { 2359 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2360 Diag(Old->getLocation(), PrevDiag); 2361 } else { 2362 Diag(New->getLocation(), diag::err_static_non_static) << New; 2363 Diag(Old->getLocation(), PrevDiag); 2364 return true; 2365 } 2366 } 2367 2368 2369 // If a function is first declared with a calling convention, but is later 2370 // declared or defined without one, all following decls assume the calling 2371 // convention of the first. 2372 // 2373 // It's OK if a function is first declared without a calling convention, 2374 // but is later declared or defined with the default calling convention. 2375 // 2376 // To test if either decl has an explicit calling convention, we look for 2377 // AttributedType sugar nodes on the type as written. If they are missing or 2378 // were canonicalized away, we assume the calling convention was implicit. 2379 // 2380 // Note also that we DO NOT return at this point, because we still have 2381 // other tests to run. 2382 QualType OldQType = Context.getCanonicalType(Old->getType()); 2383 QualType NewQType = Context.getCanonicalType(New->getType()); 2384 const FunctionType *OldType = cast<FunctionType>(OldQType); 2385 const FunctionType *NewType = cast<FunctionType>(NewQType); 2386 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2387 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2388 bool RequiresAdjustment = false; 2389 2390 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2391 FunctionDecl *First = Old->getFirstDecl(); 2392 const FunctionType *FT = 2393 First->getType().getCanonicalType()->castAs<FunctionType>(); 2394 FunctionType::ExtInfo FI = FT->getExtInfo(); 2395 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2396 if (!NewCCExplicit) { 2397 // Inherit the CC from the previous declaration if it was specified 2398 // there but not here. 2399 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2400 RequiresAdjustment = true; 2401 } else { 2402 // Calling conventions aren't compatible, so complain. 2403 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2404 Diag(New->getLocation(), diag::err_cconv_change) 2405 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2406 << !FirstCCExplicit 2407 << (!FirstCCExplicit ? "" : 2408 FunctionType::getNameForCallConv(FI.getCC())); 2409 2410 // Put the note on the first decl, since it is the one that matters. 2411 Diag(First->getLocation(), diag::note_previous_declaration); 2412 return true; 2413 } 2414 } 2415 2416 // FIXME: diagnose the other way around? 2417 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2418 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2419 RequiresAdjustment = true; 2420 } 2421 2422 // Merge regparm attribute. 2423 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2424 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2425 if (NewTypeInfo.getHasRegParm()) { 2426 Diag(New->getLocation(), diag::err_regparm_mismatch) 2427 << NewType->getRegParmType() 2428 << OldType->getRegParmType(); 2429 Diag(Old->getLocation(), diag::note_previous_declaration); 2430 return true; 2431 } 2432 2433 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2434 RequiresAdjustment = true; 2435 } 2436 2437 // Merge ns_returns_retained attribute. 2438 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2439 if (NewTypeInfo.getProducesResult()) { 2440 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2441 Diag(Old->getLocation(), diag::note_previous_declaration); 2442 return true; 2443 } 2444 2445 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2446 RequiresAdjustment = true; 2447 } 2448 2449 if (RequiresAdjustment) { 2450 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2451 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2452 New->setType(QualType(AdjustedType, 0)); 2453 NewQType = Context.getCanonicalType(New->getType()); 2454 NewType = cast<FunctionType>(NewQType); 2455 } 2456 2457 // If this redeclaration makes the function inline, we may need to add it to 2458 // UndefinedButUsed. 2459 if (!Old->isInlined() && New->isInlined() && 2460 !New->hasAttr<GNUInlineAttr>() && 2461 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2462 Old->isUsed(false) && 2463 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2464 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2465 SourceLocation())); 2466 2467 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2468 // about it. 2469 if (New->hasAttr<GNUInlineAttr>() && 2470 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2471 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2472 } 2473 2474 if (getLangOpts().CPlusPlus) { 2475 // (C++98 13.1p2): 2476 // Certain function declarations cannot be overloaded: 2477 // -- Function declarations that differ only in the return type 2478 // cannot be overloaded. 2479 2480 // Go back to the type source info to compare the declared return types, 2481 // per C++1y [dcl.type.auto]p13: 2482 // Redeclarations or specializations of a function or function template 2483 // with a declared return type that uses a placeholder type shall also 2484 // use that placeholder, not a deduced type. 2485 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo() 2486 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2487 : OldType)->getResultType(); 2488 QualType NewDeclaredReturnType = (New->getTypeSourceInfo() 2489 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2490 : NewType)->getResultType(); 2491 QualType ResQT; 2492 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2493 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2494 New->isLocalExternDecl())) { 2495 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2496 OldDeclaredReturnType->isObjCObjectPointerType()) 2497 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2498 if (ResQT.isNull()) { 2499 if (New->isCXXClassMember() && New->isOutOfLine()) 2500 Diag(New->getLocation(), 2501 diag::err_member_def_does_not_match_ret_type) << New; 2502 else 2503 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2504 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2505 return true; 2506 } 2507 else 2508 NewQType = ResQT; 2509 } 2510 2511 QualType OldReturnType = OldType->getResultType(); 2512 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2513 if (OldReturnType != NewReturnType) { 2514 // If this function has a deduced return type and has already been 2515 // defined, copy the deduced value from the old declaration. 2516 AutoType *OldAT = Old->getResultType()->getContainedAutoType(); 2517 if (OldAT && OldAT->isDeduced()) { 2518 New->setType( 2519 SubstAutoType(New->getType(), 2520 OldAT->isDependentType() ? Context.DependentTy 2521 : OldAT->getDeducedType())); 2522 NewQType = Context.getCanonicalType( 2523 SubstAutoType(NewQType, 2524 OldAT->isDependentType() ? Context.DependentTy 2525 : OldAT->getDeducedType())); 2526 } 2527 } 2528 2529 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2530 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2531 if (OldMethod && NewMethod) { 2532 // Preserve triviality. 2533 NewMethod->setTrivial(OldMethod->isTrivial()); 2534 2535 // MSVC allows explicit template specialization at class scope: 2536 // 2 CXMethodDecls referring to the same function will be injected. 2537 // We don't want a redeclartion error. 2538 bool IsClassScopeExplicitSpecialization = 2539 OldMethod->isFunctionTemplateSpecialization() && 2540 NewMethod->isFunctionTemplateSpecialization(); 2541 bool isFriend = NewMethod->getFriendObjectKind(); 2542 2543 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2544 !IsClassScopeExplicitSpecialization) { 2545 // -- Member function declarations with the same name and the 2546 // same parameter types cannot be overloaded if any of them 2547 // is a static member function declaration. 2548 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2549 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2550 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2551 return true; 2552 } 2553 2554 // C++ [class.mem]p1: 2555 // [...] A member shall not be declared twice in the 2556 // member-specification, except that a nested class or member 2557 // class template can be declared and then later defined. 2558 if (ActiveTemplateInstantiations.empty()) { 2559 unsigned NewDiag; 2560 if (isa<CXXConstructorDecl>(OldMethod)) 2561 NewDiag = diag::err_constructor_redeclared; 2562 else if (isa<CXXDestructorDecl>(NewMethod)) 2563 NewDiag = diag::err_destructor_redeclared; 2564 else if (isa<CXXConversionDecl>(NewMethod)) 2565 NewDiag = diag::err_conv_function_redeclared; 2566 else 2567 NewDiag = diag::err_member_redeclared; 2568 2569 Diag(New->getLocation(), NewDiag); 2570 } else { 2571 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2572 << New << New->getType(); 2573 } 2574 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2575 2576 // Complain if this is an explicit declaration of a special 2577 // member that was initially declared implicitly. 2578 // 2579 // As an exception, it's okay to befriend such methods in order 2580 // to permit the implicit constructor/destructor/operator calls. 2581 } else if (OldMethod->isImplicit()) { 2582 if (isFriend) { 2583 NewMethod->setImplicit(); 2584 } else { 2585 Diag(NewMethod->getLocation(), 2586 diag::err_definition_of_implicitly_declared_member) 2587 << New << getSpecialMember(OldMethod); 2588 return true; 2589 } 2590 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2591 Diag(NewMethod->getLocation(), 2592 diag::err_definition_of_explicitly_defaulted_member) 2593 << getSpecialMember(OldMethod); 2594 return true; 2595 } 2596 } 2597 2598 // C++11 [dcl.attr.noreturn]p1: 2599 // The first declaration of a function shall specify the noreturn 2600 // attribute if any declaration of that function specifies the noreturn 2601 // attribute. 2602 if (New->hasAttr<CXX11NoReturnAttr>() && 2603 !Old->hasAttr<CXX11NoReturnAttr>()) { 2604 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2605 diag::err_noreturn_missing_on_first_decl); 2606 Diag(Old->getFirstDecl()->getLocation(), 2607 diag::note_noreturn_missing_first_decl); 2608 } 2609 2610 // C++11 [dcl.attr.depend]p2: 2611 // The first declaration of a function shall specify the 2612 // carries_dependency attribute for its declarator-id if any declaration 2613 // of the function specifies the carries_dependency attribute. 2614 if (New->hasAttr<CarriesDependencyAttr>() && 2615 !Old->hasAttr<CarriesDependencyAttr>()) { 2616 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2617 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2618 Diag(Old->getFirstDecl()->getLocation(), 2619 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2620 } 2621 2622 // (C++98 8.3.5p3): 2623 // All declarations for a function shall agree exactly in both the 2624 // return type and the parameter-type-list. 2625 // We also want to respect all the extended bits except noreturn. 2626 2627 // noreturn should now match unless the old type info didn't have it. 2628 QualType OldQTypeForComparison = OldQType; 2629 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2630 assert(OldQType == QualType(OldType, 0)); 2631 const FunctionType *OldTypeForComparison 2632 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2633 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2634 assert(OldQTypeForComparison.isCanonical()); 2635 } 2636 2637 if (haveIncompatibleLanguageLinkages(Old, New)) { 2638 // As a special case, retain the language linkage from previous 2639 // declarations of a friend function as an extension. 2640 // 2641 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2642 // and is useful because there's otherwise no way to specify language 2643 // linkage within class scope. 2644 // 2645 // Check cautiously as the friend object kind isn't yet complete. 2646 if (New->getFriendObjectKind() != Decl::FOK_None) { 2647 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2648 Diag(Old->getLocation(), PrevDiag); 2649 } else { 2650 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2651 Diag(Old->getLocation(), PrevDiag); 2652 return true; 2653 } 2654 } 2655 2656 if (OldQTypeForComparison == NewQType) 2657 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2658 2659 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2660 New->isLocalExternDecl()) { 2661 // It's OK if we couldn't merge types for a local function declaraton 2662 // if either the old or new type is dependent. We'll merge the types 2663 // when we instantiate the function. 2664 return false; 2665 } 2666 2667 // Fall through for conflicting redeclarations and redefinitions. 2668 } 2669 2670 // C: Function types need to be compatible, not identical. This handles 2671 // duplicate function decls like "void f(int); void f(enum X);" properly. 2672 if (!getLangOpts().CPlusPlus && 2673 Context.typesAreCompatible(OldQType, NewQType)) { 2674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2676 const FunctionProtoType *OldProto = 0; 2677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2679 // The old declaration provided a function prototype, but the 2680 // new declaration does not. Merge in the prototype. 2681 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2682 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2683 OldProto->arg_type_end()); 2684 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2685 ParamTypes, 2686 OldProto->getExtProtoInfo()); 2687 New->setType(NewQType); 2688 New->setHasInheritedPrototype(); 2689 2690 // Synthesize a parameter for each argument type. 2691 SmallVector<ParmVarDecl*, 16> Params; 2692 for (FunctionProtoType::arg_type_iterator 2693 ParamType = OldProto->arg_type_begin(), 2694 ParamEnd = OldProto->arg_type_end(); 2695 ParamType != ParamEnd; ++ParamType) { 2696 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2697 SourceLocation(), 2698 SourceLocation(), 0, 2699 *ParamType, /*TInfo=*/0, 2700 SC_None, 2701 0); 2702 Param->setScopeInfo(0, Params.size()); 2703 Param->setImplicit(); 2704 Params.push_back(Param); 2705 } 2706 2707 New->setParams(Params); 2708 } 2709 2710 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2711 } 2712 2713 // GNU C permits a K&R definition to follow a prototype declaration 2714 // if the declared types of the parameters in the K&R definition 2715 // match the types in the prototype declaration, even when the 2716 // promoted types of the parameters from the K&R definition differ 2717 // from the types in the prototype. GCC then keeps the types from 2718 // the prototype. 2719 // 2720 // If a variadic prototype is followed by a non-variadic K&R definition, 2721 // the K&R definition becomes variadic. This is sort of an edge case, but 2722 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2723 // C99 6.9.1p8. 2724 if (!getLangOpts().CPlusPlus && 2725 Old->hasPrototype() && !New->hasPrototype() && 2726 New->getType()->getAs<FunctionProtoType>() && 2727 Old->getNumParams() == New->getNumParams()) { 2728 SmallVector<QualType, 16> ArgTypes; 2729 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2730 const FunctionProtoType *OldProto 2731 = Old->getType()->getAs<FunctionProtoType>(); 2732 const FunctionProtoType *NewProto 2733 = New->getType()->getAs<FunctionProtoType>(); 2734 2735 // Determine whether this is the GNU C extension. 2736 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2737 NewProto->getResultType()); 2738 bool LooseCompatible = !MergedReturn.isNull(); 2739 for (unsigned Idx = 0, End = Old->getNumParams(); 2740 LooseCompatible && Idx != End; ++Idx) { 2741 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2742 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2743 if (Context.typesAreCompatible(OldParm->getType(), 2744 NewProto->getArgType(Idx))) { 2745 ArgTypes.push_back(NewParm->getType()); 2746 } else if (Context.typesAreCompatible(OldParm->getType(), 2747 NewParm->getType(), 2748 /*CompareUnqualified=*/true)) { 2749 GNUCompatibleParamWarning Warn 2750 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2751 Warnings.push_back(Warn); 2752 ArgTypes.push_back(NewParm->getType()); 2753 } else 2754 LooseCompatible = false; 2755 } 2756 2757 if (LooseCompatible) { 2758 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2759 Diag(Warnings[Warn].NewParm->getLocation(), 2760 diag::ext_param_promoted_not_compatible_with_prototype) 2761 << Warnings[Warn].PromotedType 2762 << Warnings[Warn].OldParm->getType(); 2763 if (Warnings[Warn].OldParm->getLocation().isValid()) 2764 Diag(Warnings[Warn].OldParm->getLocation(), 2765 diag::note_previous_declaration); 2766 } 2767 2768 if (MergeTypeWithOld) 2769 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2770 OldProto->getExtProtoInfo())); 2771 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2772 } 2773 2774 // Fall through to diagnose conflicting types. 2775 } 2776 2777 // A function that has already been declared has been redeclared or 2778 // defined with a different type; show an appropriate diagnostic. 2779 2780 // If the previous declaration was an implicitly-generated builtin 2781 // declaration, then at the very least we should use a specialized note. 2782 unsigned BuiltinID; 2783 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2784 // If it's actually a library-defined builtin function like 'malloc' 2785 // or 'printf', just warn about the incompatible redeclaration. 2786 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2787 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2788 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2789 << Old << Old->getType(); 2790 2791 // If this is a global redeclaration, just forget hereafter 2792 // about the "builtin-ness" of the function. 2793 // 2794 // Doing this for local extern declarations is problematic. If 2795 // the builtin declaration remains visible, a second invalid 2796 // local declaration will produce a hard error; if it doesn't 2797 // remain visible, a single bogus local redeclaration (which is 2798 // actually only a warning) could break all the downstream code. 2799 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2800 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2801 2802 return false; 2803 } 2804 2805 PrevDiag = diag::note_previous_builtin_declaration; 2806 } 2807 2808 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2809 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2810 return true; 2811} 2812 2813/// \brief Completes the merge of two function declarations that are 2814/// known to be compatible. 2815/// 2816/// This routine handles the merging of attributes and other 2817/// properties of function declarations from the old declaration to 2818/// the new declaration, once we know that New is in fact a 2819/// redeclaration of Old. 2820/// 2821/// \returns false 2822bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2823 Scope *S, bool MergeTypeWithOld) { 2824 // Merge the attributes 2825 mergeDeclAttributes(New, Old); 2826 2827 // Merge "pure" flag. 2828 if (Old->isPure()) 2829 New->setPure(); 2830 2831 // Merge "used" flag. 2832 if (Old->getMostRecentDecl()->isUsed(false)) 2833 New->setIsUsed(); 2834 2835 // Merge attributes from the parameters. These can mismatch with K&R 2836 // declarations. 2837 if (New->getNumParams() == Old->getNumParams()) 2838 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2839 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2840 *this); 2841 2842 if (getLangOpts().CPlusPlus) 2843 return MergeCXXFunctionDecl(New, Old, S); 2844 2845 // Merge the function types so the we get the composite types for the return 2846 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2847 // was visible. 2848 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2849 if (!Merged.isNull() && MergeTypeWithOld) 2850 New->setType(Merged); 2851 2852 return false; 2853} 2854 2855 2856void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2857 ObjCMethodDecl *oldMethod) { 2858 2859 // Merge the attributes, including deprecated/unavailable 2860 AvailabilityMergeKind MergeKind = 2861 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2862 : AMK_Override; 2863 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2864 2865 // Merge attributes from the parameters. 2866 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2867 oe = oldMethod->param_end(); 2868 for (ObjCMethodDecl::param_iterator 2869 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2870 ni != ne && oi != oe; ++ni, ++oi) 2871 mergeParamDeclAttributes(*ni, *oi, *this); 2872 2873 CheckObjCMethodOverride(newMethod, oldMethod); 2874} 2875 2876/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2877/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2878/// emitting diagnostics as appropriate. 2879/// 2880/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2881/// to here in AddInitializerToDecl. We can't check them before the initializer 2882/// is attached. 2883void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2884 bool MergeTypeWithOld) { 2885 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2886 return; 2887 2888 QualType MergedT; 2889 if (getLangOpts().CPlusPlus) { 2890 if (New->getType()->isUndeducedType()) { 2891 // We don't know what the new type is until the initializer is attached. 2892 return; 2893 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2894 // These could still be something that needs exception specs checked. 2895 return MergeVarDeclExceptionSpecs(New, Old); 2896 } 2897 // C++ [basic.link]p10: 2898 // [...] the types specified by all declarations referring to a given 2899 // object or function shall be identical, except that declarations for an 2900 // array object can specify array types that differ by the presence or 2901 // absence of a major array bound (8.3.4). 2902 else if (Old->getType()->isIncompleteArrayType() && 2903 New->getType()->isArrayType()) { 2904 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2905 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2906 if (Context.hasSameType(OldArray->getElementType(), 2907 NewArray->getElementType())) 2908 MergedT = New->getType(); 2909 } else if (Old->getType()->isArrayType() && 2910 New->getType()->isIncompleteArrayType()) { 2911 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2912 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2913 if (Context.hasSameType(OldArray->getElementType(), 2914 NewArray->getElementType())) 2915 MergedT = Old->getType(); 2916 } else if (New->getType()->isObjCObjectPointerType() && 2917 Old->getType()->isObjCObjectPointerType()) { 2918 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2919 Old->getType()); 2920 } 2921 } else { 2922 // C 6.2.7p2: 2923 // All declarations that refer to the same object or function shall have 2924 // compatible type. 2925 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2926 } 2927 if (MergedT.isNull()) { 2928 // It's OK if we couldn't merge types if either type is dependent, for a 2929 // block-scope variable. In other cases (static data members of class 2930 // templates, variable templates, ...), we require the types to be 2931 // equivalent. 2932 // FIXME: The C++ standard doesn't say anything about this. 2933 if ((New->getType()->isDependentType() || 2934 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2935 // If the old type was dependent, we can't merge with it, so the new type 2936 // becomes dependent for now. We'll reproduce the original type when we 2937 // instantiate the TypeSourceInfo for the variable. 2938 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2939 New->setType(Context.DependentTy); 2940 return; 2941 } 2942 2943 // FIXME: Even if this merging succeeds, some other non-visible declaration 2944 // of this variable might have an incompatible type. For instance: 2945 // 2946 // extern int arr[]; 2947 // void f() { extern int arr[2]; } 2948 // void g() { extern int arr[3]; } 2949 // 2950 // Neither C nor C++ requires a diagnostic for this, but we should still try 2951 // to diagnose it. 2952 Diag(New->getLocation(), diag::err_redefinition_different_type) 2953 << New->getDeclName() << New->getType() << Old->getType(); 2954 Diag(Old->getLocation(), diag::note_previous_definition); 2955 return New->setInvalidDecl(); 2956 } 2957 2958 // Don't actually update the type on the new declaration if the old 2959 // declaration was an extern declaration in a different scope. 2960 if (MergeTypeWithOld) 2961 New->setType(MergedT); 2962} 2963 2964static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2965 LookupResult &Previous) { 2966 // C11 6.2.7p4: 2967 // For an identifier with internal or external linkage declared 2968 // in a scope in which a prior declaration of that identifier is 2969 // visible, if the prior declaration specifies internal or 2970 // external linkage, the type of the identifier at the later 2971 // declaration becomes the composite type. 2972 // 2973 // If the variable isn't visible, we do not merge with its type. 2974 if (Previous.isShadowed()) 2975 return false; 2976 2977 if (S.getLangOpts().CPlusPlus) { 2978 // C++11 [dcl.array]p3: 2979 // If there is a preceding declaration of the entity in the same 2980 // scope in which the bound was specified, an omitted array bound 2981 // is taken to be the same as in that earlier declaration. 2982 return NewVD->isPreviousDeclInSameBlockScope() || 2983 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2984 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2985 } else { 2986 // If the old declaration was function-local, don't merge with its 2987 // type unless we're in the same function. 2988 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2989 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2990 } 2991} 2992 2993/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2994/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2995/// situation, merging decls or emitting diagnostics as appropriate. 2996/// 2997/// Tentative definition rules (C99 6.9.2p2) are checked by 2998/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2999/// definitions here, since the initializer hasn't been attached. 3000/// 3001void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3002 // If the new decl is already invalid, don't do any other checking. 3003 if (New->isInvalidDecl()) 3004 return; 3005 3006 // Verify the old decl was also a variable or variable template. 3007 VarDecl *Old = 0; 3008 if (Previous.isSingleResult() && 3009 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 3010 if (New->getDescribedVarTemplate()) 3011 Old = Old->getDescribedVarTemplate() ? Old : 0; 3012 else 3013 Old = Old->getDescribedVarTemplate() ? 0 : Old; 3014 } 3015 if (!Old) { 3016 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3017 << New->getDeclName(); 3018 Diag(Previous.getRepresentativeDecl()->getLocation(), 3019 diag::note_previous_definition); 3020 return New->setInvalidDecl(); 3021 } 3022 3023 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3024 return; 3025 3026 // C++ [class.mem]p1: 3027 // A member shall not be declared twice in the member-specification [...] 3028 // 3029 // Here, we need only consider static data members. 3030 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3031 Diag(New->getLocation(), diag::err_duplicate_member) 3032 << New->getIdentifier(); 3033 Diag(Old->getLocation(), diag::note_previous_declaration); 3034 New->setInvalidDecl(); 3035 } 3036 3037 mergeDeclAttributes(New, Old); 3038 // Warn if an already-declared variable is made a weak_import in a subsequent 3039 // declaration 3040 if (New->getAttr<WeakImportAttr>() && 3041 Old->getStorageClass() == SC_None && 3042 !Old->getAttr<WeakImportAttr>()) { 3043 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3044 Diag(Old->getLocation(), diag::note_previous_definition); 3045 // Remove weak_import attribute on new declaration. 3046 New->dropAttr<WeakImportAttr>(); 3047 } 3048 3049 // Merge the types. 3050 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3051 3052 if (New->isInvalidDecl()) 3053 return; 3054 3055 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3056 if (New->getStorageClass() == SC_Static && 3057 !New->isStaticDataMember() && 3058 Old->hasExternalFormalLinkage()) { 3059 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3060 Diag(Old->getLocation(), diag::note_previous_definition); 3061 return New->setInvalidDecl(); 3062 } 3063 // C99 6.2.2p4: 3064 // For an identifier declared with the storage-class specifier 3065 // extern in a scope in which a prior declaration of that 3066 // identifier is visible,23) if the prior declaration specifies 3067 // internal or external linkage, the linkage of the identifier at 3068 // the later declaration is the same as the linkage specified at 3069 // the prior declaration. If no prior declaration is visible, or 3070 // if the prior declaration specifies no linkage, then the 3071 // identifier has external linkage. 3072 if (New->hasExternalStorage() && Old->hasLinkage()) 3073 /* Okay */; 3074 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3075 !New->isStaticDataMember() && 3076 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3077 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3078 Diag(Old->getLocation(), diag::note_previous_definition); 3079 return New->setInvalidDecl(); 3080 } 3081 3082 // Check if extern is followed by non-extern and vice-versa. 3083 if (New->hasExternalStorage() && 3084 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3085 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3086 Diag(Old->getLocation(), diag::note_previous_definition); 3087 return New->setInvalidDecl(); 3088 } 3089 if (Old->hasLinkage() && New->isLocalVarDecl() && 3090 !New->hasExternalStorage()) { 3091 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3092 Diag(Old->getLocation(), diag::note_previous_definition); 3093 return New->setInvalidDecl(); 3094 } 3095 3096 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3097 3098 // FIXME: The test for external storage here seems wrong? We still 3099 // need to check for mismatches. 3100 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3101 // Don't complain about out-of-line definitions of static members. 3102 !(Old->getLexicalDeclContext()->isRecord() && 3103 !New->getLexicalDeclContext()->isRecord())) { 3104 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3105 Diag(Old->getLocation(), diag::note_previous_definition); 3106 return New->setInvalidDecl(); 3107 } 3108 3109 if (New->getTLSKind() != Old->getTLSKind()) { 3110 if (!Old->getTLSKind()) { 3111 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3112 Diag(Old->getLocation(), diag::note_previous_declaration); 3113 } else if (!New->getTLSKind()) { 3114 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3115 Diag(Old->getLocation(), diag::note_previous_declaration); 3116 } else { 3117 // Do not allow redeclaration to change the variable between requiring 3118 // static and dynamic initialization. 3119 // FIXME: GCC allows this, but uses the TLS keyword on the first 3120 // declaration to determine the kind. Do we need to be compatible here? 3121 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3122 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3123 Diag(Old->getLocation(), diag::note_previous_declaration); 3124 } 3125 } 3126 3127 // C++ doesn't have tentative definitions, so go right ahead and check here. 3128 const VarDecl *Def; 3129 if (getLangOpts().CPlusPlus && 3130 New->isThisDeclarationADefinition() == VarDecl::Definition && 3131 (Def = Old->getDefinition())) { 3132 Diag(New->getLocation(), diag::err_redefinition) << New; 3133 Diag(Def->getLocation(), diag::note_previous_definition); 3134 New->setInvalidDecl(); 3135 return; 3136 } 3137 3138 if (haveIncompatibleLanguageLinkages(Old, New)) { 3139 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3140 Diag(Old->getLocation(), diag::note_previous_definition); 3141 New->setInvalidDecl(); 3142 return; 3143 } 3144 3145 // Merge "used" flag. 3146 if (Old->getMostRecentDecl()->isUsed(false)) 3147 New->setIsUsed(); 3148 3149 // Keep a chain of previous declarations. 3150 New->setPreviousDecl(Old); 3151 3152 // Inherit access appropriately. 3153 New->setAccess(Old->getAccess()); 3154 3155 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) { 3156 if (New->isStaticDataMember() && New->isOutOfLine()) 3157 VTD->setAccess(New->getAccess()); 3158 } 3159} 3160 3161/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3162/// no declarator (e.g. "struct foo;") is parsed. 3163Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3164 DeclSpec &DS) { 3165 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3166} 3167 3168static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3169 if (!S.Context.getLangOpts().CPlusPlus) 3170 return; 3171 3172 if (isa<CXXRecordDecl>(Tag->getParent())) { 3173 // If this tag is the direct child of a class, number it if 3174 // it is anonymous. 3175 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3176 return; 3177 MangleNumberingContext &MCtx = 3178 S.Context.getManglingNumberContext(Tag->getParent()); 3179 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3180 return; 3181 } 3182 3183 // If this tag isn't a direct child of a class, number it if it is local. 3184 Decl *ManglingContextDecl; 3185 if (MangleNumberingContext *MCtx = 3186 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3187 ManglingContextDecl)) { 3188 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3189 } 3190} 3191 3192/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3193/// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3194/// parameters to cope with template friend declarations. 3195Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3196 DeclSpec &DS, 3197 MultiTemplateParamsArg TemplateParams, 3198 bool IsExplicitInstantiation) { 3199 Decl *TagD = 0; 3200 TagDecl *Tag = 0; 3201 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3202 DS.getTypeSpecType() == DeclSpec::TST_struct || 3203 DS.getTypeSpecType() == DeclSpec::TST_interface || 3204 DS.getTypeSpecType() == DeclSpec::TST_union || 3205 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3206 TagD = DS.getRepAsDecl(); 3207 3208 if (!TagD) // We probably had an error 3209 return 0; 3210 3211 // Note that the above type specs guarantee that the 3212 // type rep is a Decl, whereas in many of the others 3213 // it's a Type. 3214 if (isa<TagDecl>(TagD)) 3215 Tag = cast<TagDecl>(TagD); 3216 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3217 Tag = CTD->getTemplatedDecl(); 3218 } 3219 3220 if (Tag) { 3221 HandleTagNumbering(*this, Tag); 3222 Tag->setFreeStanding(); 3223 if (Tag->isInvalidDecl()) 3224 return Tag; 3225 } 3226 3227 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3228 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3229 // or incomplete types shall not be restrict-qualified." 3230 if (TypeQuals & DeclSpec::TQ_restrict) 3231 Diag(DS.getRestrictSpecLoc(), 3232 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3233 << DS.getSourceRange(); 3234 } 3235 3236 if (DS.isConstexprSpecified()) { 3237 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3238 // and definitions of functions and variables. 3239 if (Tag) 3240 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3241 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3242 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3243 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3244 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3245 else 3246 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3247 // Don't emit warnings after this error. 3248 return TagD; 3249 } 3250 3251 DiagnoseFunctionSpecifiers(DS); 3252 3253 if (DS.isFriendSpecified()) { 3254 // If we're dealing with a decl but not a TagDecl, assume that 3255 // whatever routines created it handled the friendship aspect. 3256 if (TagD && !Tag) 3257 return 0; 3258 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3259 } 3260 3261 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3262 bool IsExplicitSpecialization = 3263 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3264 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3265 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3266 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3267 // nested-name-specifier unless it is an explicit instantiation 3268 // or an explicit specialization. 3269 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3270 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3271 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3272 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3273 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3274 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3275 << SS.getRange(); 3276 return 0; 3277 } 3278 3279 // Track whether this decl-specifier declares anything. 3280 bool DeclaresAnything = true; 3281 3282 // Handle anonymous struct definitions. 3283 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3284 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3285 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3286 if (getLangOpts().CPlusPlus || 3287 Record->getDeclContext()->isRecord()) 3288 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3289 3290 DeclaresAnything = false; 3291 } 3292 } 3293 3294 // Check for Microsoft C extension: anonymous struct member. 3295 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3296 CurContext->isRecord() && 3297 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3298 // Handle 2 kinds of anonymous struct: 3299 // struct STRUCT; 3300 // and 3301 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3302 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3303 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3304 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3305 DS.getRepAsType().get()->isStructureType())) { 3306 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3307 << DS.getSourceRange(); 3308 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3309 } 3310 } 3311 3312 // Skip all the checks below if we have a type error. 3313 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3314 (TagD && TagD->isInvalidDecl())) 3315 return TagD; 3316 3317 if (getLangOpts().CPlusPlus && 3318 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3319 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3320 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3321 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3322 DeclaresAnything = false; 3323 3324 if (!DS.isMissingDeclaratorOk()) { 3325 // Customize diagnostic for a typedef missing a name. 3326 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3327 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3328 << DS.getSourceRange(); 3329 else 3330 DeclaresAnything = false; 3331 } 3332 3333 if (DS.isModulePrivateSpecified() && 3334 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3335 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3336 << Tag->getTagKind() 3337 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3338 3339 ActOnDocumentableDecl(TagD); 3340 3341 // C 6.7/2: 3342 // A declaration [...] shall declare at least a declarator [...], a tag, 3343 // or the members of an enumeration. 3344 // C++ [dcl.dcl]p3: 3345 // [If there are no declarators], and except for the declaration of an 3346 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3347 // names into the program, or shall redeclare a name introduced by a 3348 // previous declaration. 3349 if (!DeclaresAnything) { 3350 // In C, we allow this as a (popular) extension / bug. Don't bother 3351 // producing further diagnostics for redundant qualifiers after this. 3352 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3353 return TagD; 3354 } 3355 3356 // C++ [dcl.stc]p1: 3357 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3358 // init-declarator-list of the declaration shall not be empty. 3359 // C++ [dcl.fct.spec]p1: 3360 // If a cv-qualifier appears in a decl-specifier-seq, the 3361 // init-declarator-list of the declaration shall not be empty. 3362 // 3363 // Spurious qualifiers here appear to be valid in C. 3364 unsigned DiagID = diag::warn_standalone_specifier; 3365 if (getLangOpts().CPlusPlus) 3366 DiagID = diag::ext_standalone_specifier; 3367 3368 // Note that a linkage-specification sets a storage class, but 3369 // 'extern "C" struct foo;' is actually valid and not theoretically 3370 // useless. 3371 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3372 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3373 Diag(DS.getStorageClassSpecLoc(), DiagID) 3374 << DeclSpec::getSpecifierName(SCS); 3375 3376 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3377 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3378 << DeclSpec::getSpecifierName(TSCS); 3379 if (DS.getTypeQualifiers()) { 3380 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3381 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3382 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3383 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3384 // Restrict is covered above. 3385 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3386 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3387 } 3388 3389 // Warn about ignored type attributes, for example: 3390 // __attribute__((aligned)) struct A; 3391 // Attributes should be placed after tag to apply to type declaration. 3392 if (!DS.getAttributes().empty()) { 3393 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3394 if (TypeSpecType == DeclSpec::TST_class || 3395 TypeSpecType == DeclSpec::TST_struct || 3396 TypeSpecType == DeclSpec::TST_interface || 3397 TypeSpecType == DeclSpec::TST_union || 3398 TypeSpecType == DeclSpec::TST_enum) { 3399 AttributeList* attrs = DS.getAttributes().getList(); 3400 while (attrs) { 3401 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3402 << attrs->getName() 3403 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3404 TypeSpecType == DeclSpec::TST_struct ? 1 : 3405 TypeSpecType == DeclSpec::TST_union ? 2 : 3406 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3407 attrs = attrs->getNext(); 3408 } 3409 } 3410 } 3411 3412 return TagD; 3413} 3414 3415/// We are trying to inject an anonymous member into the given scope; 3416/// check if there's an existing declaration that can't be overloaded. 3417/// 3418/// \return true if this is a forbidden redeclaration 3419static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3420 Scope *S, 3421 DeclContext *Owner, 3422 DeclarationName Name, 3423 SourceLocation NameLoc, 3424 unsigned diagnostic) { 3425 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3426 Sema::ForRedeclaration); 3427 if (!SemaRef.LookupName(R, S)) return false; 3428 3429 if (R.getAsSingle<TagDecl>()) 3430 return false; 3431 3432 // Pick a representative declaration. 3433 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3434 assert(PrevDecl && "Expected a non-null Decl"); 3435 3436 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3437 return false; 3438 3439 SemaRef.Diag(NameLoc, diagnostic) << Name; 3440 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3441 3442 return true; 3443} 3444 3445/// InjectAnonymousStructOrUnionMembers - Inject the members of the 3446/// anonymous struct or union AnonRecord into the owning context Owner 3447/// and scope S. This routine will be invoked just after we realize 3448/// that an unnamed union or struct is actually an anonymous union or 3449/// struct, e.g., 3450/// 3451/// @code 3452/// union { 3453/// int i; 3454/// float f; 3455/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3456/// // f into the surrounding scope.x 3457/// @endcode 3458/// 3459/// This routine is recursive, injecting the names of nested anonymous 3460/// structs/unions into the owning context and scope as well. 3461static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3462 DeclContext *Owner, 3463 RecordDecl *AnonRecord, 3464 AccessSpecifier AS, 3465 SmallVectorImpl<NamedDecl *> &Chaining, 3466 bool MSAnonStruct) { 3467 unsigned diagKind 3468 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3469 : diag::err_anonymous_struct_member_redecl; 3470 3471 bool Invalid = false; 3472 3473 // Look every FieldDecl and IndirectFieldDecl with a name. 3474 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3475 DEnd = AnonRecord->decls_end(); 3476 D != DEnd; ++D) { 3477 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3478 cast<NamedDecl>(*D)->getDeclName()) { 3479 ValueDecl *VD = cast<ValueDecl>(*D); 3480 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3481 VD->getLocation(), diagKind)) { 3482 // C++ [class.union]p2: 3483 // The names of the members of an anonymous union shall be 3484 // distinct from the names of any other entity in the 3485 // scope in which the anonymous union is declared. 3486 Invalid = true; 3487 } else { 3488 // C++ [class.union]p2: 3489 // For the purpose of name lookup, after the anonymous union 3490 // definition, the members of the anonymous union are 3491 // considered to have been defined in the scope in which the 3492 // anonymous union is declared. 3493 unsigned OldChainingSize = Chaining.size(); 3494 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3495 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3496 PE = IF->chain_end(); PI != PE; ++PI) 3497 Chaining.push_back(*PI); 3498 else 3499 Chaining.push_back(VD); 3500 3501 assert(Chaining.size() >= 2); 3502 NamedDecl **NamedChain = 3503 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3504 for (unsigned i = 0; i < Chaining.size(); i++) 3505 NamedChain[i] = Chaining[i]; 3506 3507 IndirectFieldDecl* IndirectField = 3508 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3509 VD->getIdentifier(), VD->getType(), 3510 NamedChain, Chaining.size()); 3511 3512 IndirectField->setAccess(AS); 3513 IndirectField->setImplicit(); 3514 SemaRef.PushOnScopeChains(IndirectField, S); 3515 3516 // That includes picking up the appropriate access specifier. 3517 if (AS != AS_none) IndirectField->setAccess(AS); 3518 3519 Chaining.resize(OldChainingSize); 3520 } 3521 } 3522 } 3523 3524 return Invalid; 3525} 3526 3527/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3528/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3529/// illegal input values are mapped to SC_None. 3530static StorageClass 3531StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3532 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3533 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3534 "Parser allowed 'typedef' as storage class VarDecl."); 3535 switch (StorageClassSpec) { 3536 case DeclSpec::SCS_unspecified: return SC_None; 3537 case DeclSpec::SCS_extern: 3538 if (DS.isExternInLinkageSpec()) 3539 return SC_None; 3540 return SC_Extern; 3541 case DeclSpec::SCS_static: return SC_Static; 3542 case DeclSpec::SCS_auto: return SC_Auto; 3543 case DeclSpec::SCS_register: return SC_Register; 3544 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3545 // Illegal SCSs map to None: error reporting is up to the caller. 3546 case DeclSpec::SCS_mutable: // Fall through. 3547 case DeclSpec::SCS_typedef: return SC_None; 3548 } 3549 llvm_unreachable("unknown storage class specifier"); 3550} 3551 3552/// BuildAnonymousStructOrUnion - Handle the declaration of an 3553/// anonymous structure or union. Anonymous unions are a C++ feature 3554/// (C++ [class.union]) and a C11 feature; anonymous structures 3555/// are a C11 feature and GNU C++ extension. 3556Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3557 AccessSpecifier AS, 3558 RecordDecl *Record) { 3559 DeclContext *Owner = Record->getDeclContext(); 3560 3561 // Diagnose whether this anonymous struct/union is an extension. 3562 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3563 Diag(Record->getLocation(), diag::ext_anonymous_union); 3564 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3565 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3566 else if (!Record->isUnion() && !getLangOpts().C11) 3567 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3568 3569 // C and C++ require different kinds of checks for anonymous 3570 // structs/unions. 3571 bool Invalid = false; 3572 if (getLangOpts().CPlusPlus) { 3573 const char* PrevSpec = 0; 3574 unsigned DiagID; 3575 if (Record->isUnion()) { 3576 // C++ [class.union]p6: 3577 // Anonymous unions declared in a named namespace or in the 3578 // global namespace shall be declared static. 3579 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3580 (isa<TranslationUnitDecl>(Owner) || 3581 (isa<NamespaceDecl>(Owner) && 3582 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3583 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3584 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3585 3586 // Recover by adding 'static'. 3587 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3588 PrevSpec, DiagID); 3589 } 3590 // C++ [class.union]p6: 3591 // A storage class is not allowed in a declaration of an 3592 // anonymous union in a class scope. 3593 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3594 isa<RecordDecl>(Owner)) { 3595 Diag(DS.getStorageClassSpecLoc(), 3596 diag::err_anonymous_union_with_storage_spec) 3597 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3598 3599 // Recover by removing the storage specifier. 3600 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3601 SourceLocation(), 3602 PrevSpec, DiagID); 3603 } 3604 } 3605 3606 // Ignore const/volatile/restrict qualifiers. 3607 if (DS.getTypeQualifiers()) { 3608 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3609 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3610 << Record->isUnion() << "const" 3611 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3612 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3613 Diag(DS.getVolatileSpecLoc(), 3614 diag::ext_anonymous_struct_union_qualified) 3615 << Record->isUnion() << "volatile" 3616 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3617 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3618 Diag(DS.getRestrictSpecLoc(), 3619 diag::ext_anonymous_struct_union_qualified) 3620 << Record->isUnion() << "restrict" 3621 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3622 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3623 Diag(DS.getAtomicSpecLoc(), 3624 diag::ext_anonymous_struct_union_qualified) 3625 << Record->isUnion() << "_Atomic" 3626 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3627 3628 DS.ClearTypeQualifiers(); 3629 } 3630 3631 // C++ [class.union]p2: 3632 // The member-specification of an anonymous union shall only 3633 // define non-static data members. [Note: nested types and 3634 // functions cannot be declared within an anonymous union. ] 3635 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3636 MemEnd = Record->decls_end(); 3637 Mem != MemEnd; ++Mem) { 3638 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3639 // C++ [class.union]p3: 3640 // An anonymous union shall not have private or protected 3641 // members (clause 11). 3642 assert(FD->getAccess() != AS_none); 3643 if (FD->getAccess() != AS_public) { 3644 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3645 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3646 Invalid = true; 3647 } 3648 3649 // C++ [class.union]p1 3650 // An object of a class with a non-trivial constructor, a non-trivial 3651 // copy constructor, a non-trivial destructor, or a non-trivial copy 3652 // assignment operator cannot be a member of a union, nor can an 3653 // array of such objects. 3654 if (CheckNontrivialField(FD)) 3655 Invalid = true; 3656 } else if ((*Mem)->isImplicit()) { 3657 // Any implicit members are fine. 3658 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3659 // This is a type that showed up in an 3660 // elaborated-type-specifier inside the anonymous struct or 3661 // union, but which actually declares a type outside of the 3662 // anonymous struct or union. It's okay. 3663 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3664 if (!MemRecord->isAnonymousStructOrUnion() && 3665 MemRecord->getDeclName()) { 3666 // Visual C++ allows type definition in anonymous struct or union. 3667 if (getLangOpts().MicrosoftExt) 3668 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3669 << (int)Record->isUnion(); 3670 else { 3671 // This is a nested type declaration. 3672 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3673 << (int)Record->isUnion(); 3674 Invalid = true; 3675 } 3676 } else { 3677 // This is an anonymous type definition within another anonymous type. 3678 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3679 // not part of standard C++. 3680 Diag(MemRecord->getLocation(), 3681 diag::ext_anonymous_record_with_anonymous_type) 3682 << (int)Record->isUnion(); 3683 } 3684 } else if (isa<AccessSpecDecl>(*Mem)) { 3685 // Any access specifier is fine. 3686 } else { 3687 // We have something that isn't a non-static data 3688 // member. Complain about it. 3689 unsigned DK = diag::err_anonymous_record_bad_member; 3690 if (isa<TypeDecl>(*Mem)) 3691 DK = diag::err_anonymous_record_with_type; 3692 else if (isa<FunctionDecl>(*Mem)) 3693 DK = diag::err_anonymous_record_with_function; 3694 else if (isa<VarDecl>(*Mem)) 3695 DK = diag::err_anonymous_record_with_static; 3696 3697 // Visual C++ allows type definition in anonymous struct or union. 3698 if (getLangOpts().MicrosoftExt && 3699 DK == diag::err_anonymous_record_with_type) 3700 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3701 << (int)Record->isUnion(); 3702 else { 3703 Diag((*Mem)->getLocation(), DK) 3704 << (int)Record->isUnion(); 3705 Invalid = true; 3706 } 3707 } 3708 } 3709 } 3710 3711 if (!Record->isUnion() && !Owner->isRecord()) { 3712 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3713 << (int)getLangOpts().CPlusPlus; 3714 Invalid = true; 3715 } 3716 3717 // Mock up a declarator. 3718 Declarator Dc(DS, Declarator::MemberContext); 3719 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3720 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3721 3722 // Create a declaration for this anonymous struct/union. 3723 NamedDecl *Anon = 0; 3724 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3725 Anon = FieldDecl::Create(Context, OwningClass, 3726 DS.getLocStart(), 3727 Record->getLocation(), 3728 /*IdentifierInfo=*/0, 3729 Context.getTypeDeclType(Record), 3730 TInfo, 3731 /*BitWidth=*/0, /*Mutable=*/false, 3732 /*InitStyle=*/ICIS_NoInit); 3733 Anon->setAccess(AS); 3734 if (getLangOpts().CPlusPlus) 3735 FieldCollector->Add(cast<FieldDecl>(Anon)); 3736 } else { 3737 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3738 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3739 if (SCSpec == DeclSpec::SCS_mutable) { 3740 // mutable can only appear on non-static class members, so it's always 3741 // an error here 3742 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3743 Invalid = true; 3744 SC = SC_None; 3745 } 3746 3747 Anon = VarDecl::Create(Context, Owner, 3748 DS.getLocStart(), 3749 Record->getLocation(), /*IdentifierInfo=*/0, 3750 Context.getTypeDeclType(Record), 3751 TInfo, SC); 3752 3753 // Default-initialize the implicit variable. This initialization will be 3754 // trivial in almost all cases, except if a union member has an in-class 3755 // initializer: 3756 // union { int n = 0; }; 3757 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3758 } 3759 Anon->setImplicit(); 3760 3761 // Add the anonymous struct/union object to the current 3762 // context. We'll be referencing this object when we refer to one of 3763 // its members. 3764 Owner->addDecl(Anon); 3765 3766 // Inject the members of the anonymous struct/union into the owning 3767 // context and into the identifier resolver chain for name lookup 3768 // purposes. 3769 SmallVector<NamedDecl*, 2> Chain; 3770 Chain.push_back(Anon); 3771 3772 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3773 Chain, false)) 3774 Invalid = true; 3775 3776 // Mark this as an anonymous struct/union type. Note that we do not 3777 // do this until after we have already checked and injected the 3778 // members of this anonymous struct/union type, because otherwise 3779 // the members could be injected twice: once by DeclContext when it 3780 // builds its lookup table, and once by 3781 // InjectAnonymousStructOrUnionMembers. 3782 Record->setAnonymousStructOrUnion(true); 3783 3784 if (Invalid) 3785 Anon->setInvalidDecl(); 3786 3787 return Anon; 3788} 3789 3790/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3791/// Microsoft C anonymous structure. 3792/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3793/// Example: 3794/// 3795/// struct A { int a; }; 3796/// struct B { struct A; int b; }; 3797/// 3798/// void foo() { 3799/// B var; 3800/// var.a = 3; 3801/// } 3802/// 3803Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3804 RecordDecl *Record) { 3805 3806 // If there is no Record, get the record via the typedef. 3807 if (!Record) 3808 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3809 3810 // Mock up a declarator. 3811 Declarator Dc(DS, Declarator::TypeNameContext); 3812 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3813 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3814 3815 // Create a declaration for this anonymous struct. 3816 NamedDecl* Anon = FieldDecl::Create(Context, 3817 cast<RecordDecl>(CurContext), 3818 DS.getLocStart(), 3819 DS.getLocStart(), 3820 /*IdentifierInfo=*/0, 3821 Context.getTypeDeclType(Record), 3822 TInfo, 3823 /*BitWidth=*/0, /*Mutable=*/false, 3824 /*InitStyle=*/ICIS_NoInit); 3825 Anon->setImplicit(); 3826 3827 // Add the anonymous struct object to the current context. 3828 CurContext->addDecl(Anon); 3829 3830 // Inject the members of the anonymous struct into the current 3831 // context and into the identifier resolver chain for name lookup 3832 // purposes. 3833 SmallVector<NamedDecl*, 2> Chain; 3834 Chain.push_back(Anon); 3835 3836 RecordDecl *RecordDef = Record->getDefinition(); 3837 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3838 RecordDef, AS_none, 3839 Chain, true)) 3840 Anon->setInvalidDecl(); 3841 3842 return Anon; 3843} 3844 3845/// GetNameForDeclarator - Determine the full declaration name for the 3846/// given Declarator. 3847DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3848 return GetNameFromUnqualifiedId(D.getName()); 3849} 3850 3851/// \brief Retrieves the declaration name from a parsed unqualified-id. 3852DeclarationNameInfo 3853Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3854 DeclarationNameInfo NameInfo; 3855 NameInfo.setLoc(Name.StartLocation); 3856 3857 switch (Name.getKind()) { 3858 3859 case UnqualifiedId::IK_ImplicitSelfParam: 3860 case UnqualifiedId::IK_Identifier: 3861 NameInfo.setName(Name.Identifier); 3862 NameInfo.setLoc(Name.StartLocation); 3863 return NameInfo; 3864 3865 case UnqualifiedId::IK_OperatorFunctionId: 3866 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3867 Name.OperatorFunctionId.Operator)); 3868 NameInfo.setLoc(Name.StartLocation); 3869 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3870 = Name.OperatorFunctionId.SymbolLocations[0]; 3871 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3872 = Name.EndLocation.getRawEncoding(); 3873 return NameInfo; 3874 3875 case UnqualifiedId::IK_LiteralOperatorId: 3876 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3877 Name.Identifier)); 3878 NameInfo.setLoc(Name.StartLocation); 3879 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3880 return NameInfo; 3881 3882 case UnqualifiedId::IK_ConversionFunctionId: { 3883 TypeSourceInfo *TInfo; 3884 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3885 if (Ty.isNull()) 3886 return DeclarationNameInfo(); 3887 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3888 Context.getCanonicalType(Ty))); 3889 NameInfo.setLoc(Name.StartLocation); 3890 NameInfo.setNamedTypeInfo(TInfo); 3891 return NameInfo; 3892 } 3893 3894 case UnqualifiedId::IK_ConstructorName: { 3895 TypeSourceInfo *TInfo; 3896 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3897 if (Ty.isNull()) 3898 return DeclarationNameInfo(); 3899 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3900 Context.getCanonicalType(Ty))); 3901 NameInfo.setLoc(Name.StartLocation); 3902 NameInfo.setNamedTypeInfo(TInfo); 3903 return NameInfo; 3904 } 3905 3906 case UnqualifiedId::IK_ConstructorTemplateId: { 3907 // In well-formed code, we can only have a constructor 3908 // template-id that refers to the current context, so go there 3909 // to find the actual type being constructed. 3910 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3911 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3912 return DeclarationNameInfo(); 3913 3914 // Determine the type of the class being constructed. 3915 QualType CurClassType = Context.getTypeDeclType(CurClass); 3916 3917 // FIXME: Check two things: that the template-id names the same type as 3918 // CurClassType, and that the template-id does not occur when the name 3919 // was qualified. 3920 3921 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3922 Context.getCanonicalType(CurClassType))); 3923 NameInfo.setLoc(Name.StartLocation); 3924 // FIXME: should we retrieve TypeSourceInfo? 3925 NameInfo.setNamedTypeInfo(0); 3926 return NameInfo; 3927 } 3928 3929 case UnqualifiedId::IK_DestructorName: { 3930 TypeSourceInfo *TInfo; 3931 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3932 if (Ty.isNull()) 3933 return DeclarationNameInfo(); 3934 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3935 Context.getCanonicalType(Ty))); 3936 NameInfo.setLoc(Name.StartLocation); 3937 NameInfo.setNamedTypeInfo(TInfo); 3938 return NameInfo; 3939 } 3940 3941 case UnqualifiedId::IK_TemplateId: { 3942 TemplateName TName = Name.TemplateId->Template.get(); 3943 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3944 return Context.getNameForTemplate(TName, TNameLoc); 3945 } 3946 3947 } // switch (Name.getKind()) 3948 3949 llvm_unreachable("Unknown name kind"); 3950} 3951 3952static QualType getCoreType(QualType Ty) { 3953 do { 3954 if (Ty->isPointerType() || Ty->isReferenceType()) 3955 Ty = Ty->getPointeeType(); 3956 else if (Ty->isArrayType()) 3957 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3958 else 3959 return Ty.withoutLocalFastQualifiers(); 3960 } while (true); 3961} 3962 3963/// hasSimilarParameters - Determine whether the C++ functions Declaration 3964/// and Definition have "nearly" matching parameters. This heuristic is 3965/// used to improve diagnostics in the case where an out-of-line function 3966/// definition doesn't match any declaration within the class or namespace. 3967/// Also sets Params to the list of indices to the parameters that differ 3968/// between the declaration and the definition. If hasSimilarParameters 3969/// returns true and Params is empty, then all of the parameters match. 3970static bool hasSimilarParameters(ASTContext &Context, 3971 FunctionDecl *Declaration, 3972 FunctionDecl *Definition, 3973 SmallVectorImpl<unsigned> &Params) { 3974 Params.clear(); 3975 if (Declaration->param_size() != Definition->param_size()) 3976 return false; 3977 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3978 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3979 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3980 3981 // The parameter types are identical 3982 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3983 continue; 3984 3985 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3986 QualType DefParamBaseTy = getCoreType(DefParamTy); 3987 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3988 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3989 3990 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3991 (DeclTyName && DeclTyName == DefTyName)) 3992 Params.push_back(Idx); 3993 else // The two parameters aren't even close 3994 return false; 3995 } 3996 3997 return true; 3998} 3999 4000/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4001/// declarator needs to be rebuilt in the current instantiation. 4002/// Any bits of declarator which appear before the name are valid for 4003/// consideration here. That's specifically the type in the decl spec 4004/// and the base type in any member-pointer chunks. 4005static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4006 DeclarationName Name) { 4007 // The types we specifically need to rebuild are: 4008 // - typenames, typeofs, and decltypes 4009 // - types which will become injected class names 4010 // Of course, we also need to rebuild any type referencing such a 4011 // type. It's safest to just say "dependent", but we call out a 4012 // few cases here. 4013 4014 DeclSpec &DS = D.getMutableDeclSpec(); 4015 switch (DS.getTypeSpecType()) { 4016 case DeclSpec::TST_typename: 4017 case DeclSpec::TST_typeofType: 4018 case DeclSpec::TST_underlyingType: 4019 case DeclSpec::TST_atomic: { 4020 // Grab the type from the parser. 4021 TypeSourceInfo *TSI = 0; 4022 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4023 if (T.isNull() || !T->isDependentType()) break; 4024 4025 // Make sure there's a type source info. This isn't really much 4026 // of a waste; most dependent types should have type source info 4027 // attached already. 4028 if (!TSI) 4029 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4030 4031 // Rebuild the type in the current instantiation. 4032 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4033 if (!TSI) return true; 4034 4035 // Store the new type back in the decl spec. 4036 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4037 DS.UpdateTypeRep(LocType); 4038 break; 4039 } 4040 4041 case DeclSpec::TST_decltype: 4042 case DeclSpec::TST_typeofExpr: { 4043 Expr *E = DS.getRepAsExpr(); 4044 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4045 if (Result.isInvalid()) return true; 4046 DS.UpdateExprRep(Result.get()); 4047 break; 4048 } 4049 4050 default: 4051 // Nothing to do for these decl specs. 4052 break; 4053 } 4054 4055 // It doesn't matter what order we do this in. 4056 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4057 DeclaratorChunk &Chunk = D.getTypeObject(I); 4058 4059 // The only type information in the declarator which can come 4060 // before the declaration name is the base type of a member 4061 // pointer. 4062 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4063 continue; 4064 4065 // Rebuild the scope specifier in-place. 4066 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4067 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4068 return true; 4069 } 4070 4071 return false; 4072} 4073 4074Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4075 D.setFunctionDefinitionKind(FDK_Declaration); 4076 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4077 4078 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4079 Dcl && Dcl->getDeclContext()->isFileContext()) 4080 Dcl->setTopLevelDeclInObjCContainer(); 4081 4082 return Dcl; 4083} 4084 4085/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4086/// If T is the name of a class, then each of the following shall have a 4087/// name different from T: 4088/// - every static data member of class T; 4089/// - every member function of class T 4090/// - every member of class T that is itself a type; 4091/// \returns true if the declaration name violates these rules. 4092bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4093 DeclarationNameInfo NameInfo) { 4094 DeclarationName Name = NameInfo.getName(); 4095 4096 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4097 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4098 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4099 return true; 4100 } 4101 4102 return false; 4103} 4104 4105/// \brief Diagnose a declaration whose declarator-id has the given 4106/// nested-name-specifier. 4107/// 4108/// \param SS The nested-name-specifier of the declarator-id. 4109/// 4110/// \param DC The declaration context to which the nested-name-specifier 4111/// resolves. 4112/// 4113/// \param Name The name of the entity being declared. 4114/// 4115/// \param Loc The location of the name of the entity being declared. 4116/// 4117/// \returns true if we cannot safely recover from this error, false otherwise. 4118bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4119 DeclarationName Name, 4120 SourceLocation Loc) { 4121 DeclContext *Cur = CurContext; 4122 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4123 Cur = Cur->getParent(); 4124 4125 // C++ [dcl.meaning]p1: 4126 // A declarator-id shall not be qualified except for the definition 4127 // of a member function (9.3) or static data member (9.4) outside of 4128 // its class, the definition or explicit instantiation of a function 4129 // or variable member of a namespace outside of its namespace, or the 4130 // definition of an explicit specialization outside of its namespace, 4131 // or the declaration of a friend function that is a member of 4132 // another class or namespace (11.3). [...] 4133 4134 // The user provided a superfluous scope specifier that refers back to the 4135 // class or namespaces in which the entity is already declared. 4136 // 4137 // class X { 4138 // void X::f(); 4139 // }; 4140 if (Cur->Equals(DC)) { 4141 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 4142 : diag::err_member_extra_qualification) 4143 << Name << FixItHint::CreateRemoval(SS.getRange()); 4144 SS.clear(); 4145 return false; 4146 } 4147 4148 // Check whether the qualifying scope encloses the scope of the original 4149 // declaration. 4150 if (!Cur->Encloses(DC)) { 4151 if (Cur->isRecord()) 4152 Diag(Loc, diag::err_member_qualification) 4153 << Name << SS.getRange(); 4154 else if (isa<TranslationUnitDecl>(DC)) 4155 Diag(Loc, diag::err_invalid_declarator_global_scope) 4156 << Name << SS.getRange(); 4157 else if (isa<FunctionDecl>(Cur)) 4158 Diag(Loc, diag::err_invalid_declarator_in_function) 4159 << Name << SS.getRange(); 4160 else if (isa<BlockDecl>(Cur)) 4161 Diag(Loc, diag::err_invalid_declarator_in_block) 4162 << Name << SS.getRange(); 4163 else 4164 Diag(Loc, diag::err_invalid_declarator_scope) 4165 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4166 4167 return true; 4168 } 4169 4170 if (Cur->isRecord()) { 4171 // Cannot qualify members within a class. 4172 Diag(Loc, diag::err_member_qualification) 4173 << Name << SS.getRange(); 4174 SS.clear(); 4175 4176 // C++ constructors and destructors with incorrect scopes can break 4177 // our AST invariants by having the wrong underlying types. If 4178 // that's the case, then drop this declaration entirely. 4179 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4180 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4181 !Context.hasSameType(Name.getCXXNameType(), 4182 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4183 return true; 4184 4185 return false; 4186 } 4187 4188 // C++11 [dcl.meaning]p1: 4189 // [...] "The nested-name-specifier of the qualified declarator-id shall 4190 // not begin with a decltype-specifer" 4191 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4192 while (SpecLoc.getPrefix()) 4193 SpecLoc = SpecLoc.getPrefix(); 4194 if (dyn_cast_or_null<DecltypeType>( 4195 SpecLoc.getNestedNameSpecifier()->getAsType())) 4196 Diag(Loc, diag::err_decltype_in_declarator) 4197 << SpecLoc.getTypeLoc().getSourceRange(); 4198 4199 return false; 4200} 4201 4202NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4203 MultiTemplateParamsArg TemplateParamLists) { 4204 // TODO: consider using NameInfo for diagnostic. 4205 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4206 DeclarationName Name = NameInfo.getName(); 4207 4208 // All of these full declarators require an identifier. If it doesn't have 4209 // one, the ParsedFreeStandingDeclSpec action should be used. 4210 if (!Name) { 4211 if (!D.isInvalidType()) // Reject this if we think it is valid. 4212 Diag(D.getDeclSpec().getLocStart(), 4213 diag::err_declarator_need_ident) 4214 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4215 return 0; 4216 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4217 return 0; 4218 4219 // The scope passed in may not be a decl scope. Zip up the scope tree until 4220 // we find one that is. 4221 while ((S->getFlags() & Scope::DeclScope) == 0 || 4222 (S->getFlags() & Scope::TemplateParamScope) != 0) 4223 S = S->getParent(); 4224 4225 DeclContext *DC = CurContext; 4226 if (D.getCXXScopeSpec().isInvalid()) 4227 D.setInvalidType(); 4228 else if (D.getCXXScopeSpec().isSet()) { 4229 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4230 UPPC_DeclarationQualifier)) 4231 return 0; 4232 4233 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4234 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4235 if (!DC || isa<EnumDecl>(DC)) { 4236 // If we could not compute the declaration context, it's because the 4237 // declaration context is dependent but does not refer to a class, 4238 // class template, or class template partial specialization. Complain 4239 // and return early, to avoid the coming semantic disaster. 4240 Diag(D.getIdentifierLoc(), 4241 diag::err_template_qualified_declarator_no_match) 4242 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4243 << D.getCXXScopeSpec().getRange(); 4244 return 0; 4245 } 4246 bool IsDependentContext = DC->isDependentContext(); 4247 4248 if (!IsDependentContext && 4249 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4250 return 0; 4251 4252 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4253 Diag(D.getIdentifierLoc(), 4254 diag::err_member_def_undefined_record) 4255 << Name << DC << D.getCXXScopeSpec().getRange(); 4256 D.setInvalidType(); 4257 } else if (!D.getDeclSpec().isFriendSpecified()) { 4258 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4259 Name, D.getIdentifierLoc())) { 4260 if (DC->isRecord()) 4261 return 0; 4262 4263 D.setInvalidType(); 4264 } 4265 } 4266 4267 // Check whether we need to rebuild the type of the given 4268 // declaration in the current instantiation. 4269 if (EnteringContext && IsDependentContext && 4270 TemplateParamLists.size() != 0) { 4271 ContextRAII SavedContext(*this, DC); 4272 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4273 D.setInvalidType(); 4274 } 4275 } 4276 4277 if (DiagnoseClassNameShadow(DC, NameInfo)) 4278 // If this is a typedef, we'll end up spewing multiple diagnostics. 4279 // Just return early; it's safer. 4280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4281 return 0; 4282 4283 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4284 QualType R = TInfo->getType(); 4285 4286 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4287 UPPC_DeclarationType)) 4288 D.setInvalidType(); 4289 4290 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4291 ForRedeclaration); 4292 4293 // See if this is a redefinition of a variable in the same scope. 4294 if (!D.getCXXScopeSpec().isSet()) { 4295 bool IsLinkageLookup = false; 4296 bool CreateBuiltins = false; 4297 4298 // If the declaration we're planning to build will be a function 4299 // or object with linkage, then look for another declaration with 4300 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4301 // 4302 // If the declaration we're planning to build will be declared with 4303 // external linkage in the translation unit, create any builtin with 4304 // the same name. 4305 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4306 /* Do nothing*/; 4307 else if (CurContext->isFunctionOrMethod() && 4308 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4309 R->isFunctionType())) { 4310 IsLinkageLookup = true; 4311 CreateBuiltins = 4312 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4313 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4314 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4315 CreateBuiltins = true; 4316 4317 if (IsLinkageLookup) 4318 Previous.clear(LookupRedeclarationWithLinkage); 4319 4320 LookupName(Previous, S, CreateBuiltins); 4321 } else { // Something like "int foo::x;" 4322 LookupQualifiedName(Previous, DC); 4323 4324 // C++ [dcl.meaning]p1: 4325 // When the declarator-id is qualified, the declaration shall refer to a 4326 // previously declared member of the class or namespace to which the 4327 // qualifier refers (or, in the case of a namespace, of an element of the 4328 // inline namespace set of that namespace (7.3.1)) or to a specialization 4329 // thereof; [...] 4330 // 4331 // Note that we already checked the context above, and that we do not have 4332 // enough information to make sure that Previous contains the declaration 4333 // we want to match. For example, given: 4334 // 4335 // class X { 4336 // void f(); 4337 // void f(float); 4338 // }; 4339 // 4340 // void X::f(int) { } // ill-formed 4341 // 4342 // In this case, Previous will point to the overload set 4343 // containing the two f's declared in X, but neither of them 4344 // matches. 4345 4346 // C++ [dcl.meaning]p1: 4347 // [...] the member shall not merely have been introduced by a 4348 // using-declaration in the scope of the class or namespace nominated by 4349 // the nested-name-specifier of the declarator-id. 4350 RemoveUsingDecls(Previous); 4351 } 4352 4353 if (Previous.isSingleResult() && 4354 Previous.getFoundDecl()->isTemplateParameter()) { 4355 // Maybe we will complain about the shadowed template parameter. 4356 if (!D.isInvalidType()) 4357 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4358 Previous.getFoundDecl()); 4359 4360 // Just pretend that we didn't see the previous declaration. 4361 Previous.clear(); 4362 } 4363 4364 // In C++, the previous declaration we find might be a tag type 4365 // (class or enum). In this case, the new declaration will hide the 4366 // tag type. Note that this does does not apply if we're declaring a 4367 // typedef (C++ [dcl.typedef]p4). 4368 if (Previous.isSingleTagDecl() && 4369 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4370 Previous.clear(); 4371 4372 // Check that there are no default arguments other than in the parameters 4373 // of a function declaration (C++ only). 4374 if (getLangOpts().CPlusPlus) 4375 CheckExtraCXXDefaultArguments(D); 4376 4377 NamedDecl *New; 4378 4379 bool AddToScope = true; 4380 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4381 if (TemplateParamLists.size()) { 4382 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4383 return 0; 4384 } 4385 4386 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4387 } else if (R->isFunctionType()) { 4388 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4389 TemplateParamLists, 4390 AddToScope); 4391 } else { 4392 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4393 AddToScope); 4394 } 4395 4396 if (New == 0) 4397 return 0; 4398 4399 // If this has an identifier and is not an invalid redeclaration or 4400 // function template specialization, add it to the scope stack. 4401 if (New->getDeclName() && AddToScope && 4402 !(D.isRedeclaration() && New->isInvalidDecl())) { 4403 // Only make a locally-scoped extern declaration visible if it is the first 4404 // declaration of this entity. Qualified lookup for such an entity should 4405 // only find this declaration if there is no visible declaration of it. 4406 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4407 PushOnScopeChains(New, S, AddToContext); 4408 if (!AddToContext) 4409 CurContext->addHiddenDecl(New); 4410 } 4411 4412 return New; 4413} 4414 4415/// Helper method to turn variable array types into constant array 4416/// types in certain situations which would otherwise be errors (for 4417/// GCC compatibility). 4418static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4419 ASTContext &Context, 4420 bool &SizeIsNegative, 4421 llvm::APSInt &Oversized) { 4422 // This method tries to turn a variable array into a constant 4423 // array even when the size isn't an ICE. This is necessary 4424 // for compatibility with code that depends on gcc's buggy 4425 // constant expression folding, like struct {char x[(int)(char*)2];} 4426 SizeIsNegative = false; 4427 Oversized = 0; 4428 4429 if (T->isDependentType()) 4430 return QualType(); 4431 4432 QualifierCollector Qs; 4433 const Type *Ty = Qs.strip(T); 4434 4435 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4436 QualType Pointee = PTy->getPointeeType(); 4437 QualType FixedType = 4438 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4439 Oversized); 4440 if (FixedType.isNull()) return FixedType; 4441 FixedType = Context.getPointerType(FixedType); 4442 return Qs.apply(Context, FixedType); 4443 } 4444 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4445 QualType Inner = PTy->getInnerType(); 4446 QualType FixedType = 4447 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4448 Oversized); 4449 if (FixedType.isNull()) return FixedType; 4450 FixedType = Context.getParenType(FixedType); 4451 return Qs.apply(Context, FixedType); 4452 } 4453 4454 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4455 if (!VLATy) 4456 return QualType(); 4457 // FIXME: We should probably handle this case 4458 if (VLATy->getElementType()->isVariablyModifiedType()) 4459 return QualType(); 4460 4461 llvm::APSInt Res; 4462 if (!VLATy->getSizeExpr() || 4463 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4464 return QualType(); 4465 4466 // Check whether the array size is negative. 4467 if (Res.isSigned() && Res.isNegative()) { 4468 SizeIsNegative = true; 4469 return QualType(); 4470 } 4471 4472 // Check whether the array is too large to be addressed. 4473 unsigned ActiveSizeBits 4474 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4475 Res); 4476 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4477 Oversized = Res; 4478 return QualType(); 4479 } 4480 4481 return Context.getConstantArrayType(VLATy->getElementType(), 4482 Res, ArrayType::Normal, 0); 4483} 4484 4485static void 4486FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4487 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4488 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4489 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4490 DstPTL.getPointeeLoc()); 4491 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4492 return; 4493 } 4494 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4495 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4496 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4497 DstPTL.getInnerLoc()); 4498 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4499 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4500 return; 4501 } 4502 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4503 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4504 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4505 TypeLoc DstElemTL = DstATL.getElementLoc(); 4506 DstElemTL.initializeFullCopy(SrcElemTL); 4507 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4508 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4509 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4510} 4511 4512/// Helper method to turn variable array types into constant array 4513/// types in certain situations which would otherwise be errors (for 4514/// GCC compatibility). 4515static TypeSourceInfo* 4516TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4517 ASTContext &Context, 4518 bool &SizeIsNegative, 4519 llvm::APSInt &Oversized) { 4520 QualType FixedTy 4521 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4522 SizeIsNegative, Oversized); 4523 if (FixedTy.isNull()) 4524 return 0; 4525 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4526 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4527 FixedTInfo->getTypeLoc()); 4528 return FixedTInfo; 4529} 4530 4531/// \brief Register the given locally-scoped extern "C" declaration so 4532/// that it can be found later for redeclarations. We include any extern "C" 4533/// declaration that is not visible in the translation unit here, not just 4534/// function-scope declarations. 4535void 4536Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4537 if (!getLangOpts().CPlusPlus && 4538 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4539 // Don't need to track declarations in the TU in C. 4540 return; 4541 4542 // Note that we have a locally-scoped external with this name. 4543 // FIXME: There can be multiple such declarations if they are functions marked 4544 // __attribute__((overloadable)) declared in function scope in C. 4545 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4546} 4547 4548NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4549 if (ExternalSource) { 4550 // Load locally-scoped external decls from the external source. 4551 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4552 SmallVector<NamedDecl *, 4> Decls; 4553 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4554 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4555 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4556 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4557 if (Pos == LocallyScopedExternCDecls.end()) 4558 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4559 } 4560 } 4561 4562 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4563 return D ? D->getMostRecentDecl() : 0; 4564} 4565 4566/// \brief Diagnose function specifiers on a declaration of an identifier that 4567/// does not identify a function. 4568void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4569 // FIXME: We should probably indicate the identifier in question to avoid 4570 // confusion for constructs like "inline int a(), b;" 4571 if (DS.isInlineSpecified()) 4572 Diag(DS.getInlineSpecLoc(), 4573 diag::err_inline_non_function); 4574 4575 if (DS.isVirtualSpecified()) 4576 Diag(DS.getVirtualSpecLoc(), 4577 diag::err_virtual_non_function); 4578 4579 if (DS.isExplicitSpecified()) 4580 Diag(DS.getExplicitSpecLoc(), 4581 diag::err_explicit_non_function); 4582 4583 if (DS.isNoreturnSpecified()) 4584 Diag(DS.getNoreturnSpecLoc(), 4585 diag::err_noreturn_non_function); 4586} 4587 4588NamedDecl* 4589Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4590 TypeSourceInfo *TInfo, LookupResult &Previous) { 4591 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4592 if (D.getCXXScopeSpec().isSet()) { 4593 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4594 << D.getCXXScopeSpec().getRange(); 4595 D.setInvalidType(); 4596 // Pretend we didn't see the scope specifier. 4597 DC = CurContext; 4598 Previous.clear(); 4599 } 4600 4601 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4602 4603 if (D.getDeclSpec().isConstexprSpecified()) 4604 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4605 << 1; 4606 4607 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4608 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4609 << D.getName().getSourceRange(); 4610 return 0; 4611 } 4612 4613 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4614 if (!NewTD) return 0; 4615 4616 // Handle attributes prior to checking for duplicates in MergeVarDecl 4617 ProcessDeclAttributes(S, NewTD, D); 4618 4619 CheckTypedefForVariablyModifiedType(S, NewTD); 4620 4621 bool Redeclaration = D.isRedeclaration(); 4622 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4623 D.setRedeclaration(Redeclaration); 4624 return ND; 4625} 4626 4627void 4628Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4629 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4630 // then it shall have block scope. 4631 // Note that variably modified types must be fixed before merging the decl so 4632 // that redeclarations will match. 4633 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4634 QualType T = TInfo->getType(); 4635 if (T->isVariablyModifiedType()) { 4636 getCurFunction()->setHasBranchProtectedScope(); 4637 4638 if (S->getFnParent() == 0) { 4639 bool SizeIsNegative; 4640 llvm::APSInt Oversized; 4641 TypeSourceInfo *FixedTInfo = 4642 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4643 SizeIsNegative, 4644 Oversized); 4645 if (FixedTInfo) { 4646 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4647 NewTD->setTypeSourceInfo(FixedTInfo); 4648 } else { 4649 if (SizeIsNegative) 4650 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4651 else if (T->isVariableArrayType()) 4652 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4653 else if (Oversized.getBoolValue()) 4654 Diag(NewTD->getLocation(), diag::err_array_too_large) 4655 << Oversized.toString(10); 4656 else 4657 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4658 NewTD->setInvalidDecl(); 4659 } 4660 } 4661 } 4662} 4663 4664 4665/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4666/// declares a typedef-name, either using the 'typedef' type specifier or via 4667/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4668NamedDecl* 4669Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4670 LookupResult &Previous, bool &Redeclaration) { 4671 // Merge the decl with the existing one if appropriate. If the decl is 4672 // in an outer scope, it isn't the same thing. 4673 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4674 /*ExplicitInstantiationOrSpecialization=*/false); 4675 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4676 if (!Previous.empty()) { 4677 Redeclaration = true; 4678 MergeTypedefNameDecl(NewTD, Previous); 4679 } 4680 4681 // If this is the C FILE type, notify the AST context. 4682 if (IdentifierInfo *II = NewTD->getIdentifier()) 4683 if (!NewTD->isInvalidDecl() && 4684 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4685 if (II->isStr("FILE")) 4686 Context.setFILEDecl(NewTD); 4687 else if (II->isStr("jmp_buf")) 4688 Context.setjmp_bufDecl(NewTD); 4689 else if (II->isStr("sigjmp_buf")) 4690 Context.setsigjmp_bufDecl(NewTD); 4691 else if (II->isStr("ucontext_t")) 4692 Context.setucontext_tDecl(NewTD); 4693 } 4694 4695 return NewTD; 4696} 4697 4698/// \brief Determines whether the given declaration is an out-of-scope 4699/// previous declaration. 4700/// 4701/// This routine should be invoked when name lookup has found a 4702/// previous declaration (PrevDecl) that is not in the scope where a 4703/// new declaration by the same name is being introduced. If the new 4704/// declaration occurs in a local scope, previous declarations with 4705/// linkage may still be considered previous declarations (C99 4706/// 6.2.2p4-5, C++ [basic.link]p6). 4707/// 4708/// \param PrevDecl the previous declaration found by name 4709/// lookup 4710/// 4711/// \param DC the context in which the new declaration is being 4712/// declared. 4713/// 4714/// \returns true if PrevDecl is an out-of-scope previous declaration 4715/// for a new delcaration with the same name. 4716static bool 4717isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4718 ASTContext &Context) { 4719 if (!PrevDecl) 4720 return false; 4721 4722 if (!PrevDecl->hasLinkage()) 4723 return false; 4724 4725 if (Context.getLangOpts().CPlusPlus) { 4726 // C++ [basic.link]p6: 4727 // If there is a visible declaration of an entity with linkage 4728 // having the same name and type, ignoring entities declared 4729 // outside the innermost enclosing namespace scope, the block 4730 // scope declaration declares that same entity and receives the 4731 // linkage of the previous declaration. 4732 DeclContext *OuterContext = DC->getRedeclContext(); 4733 if (!OuterContext->isFunctionOrMethod()) 4734 // This rule only applies to block-scope declarations. 4735 return false; 4736 4737 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4738 if (PrevOuterContext->isRecord()) 4739 // We found a member function: ignore it. 4740 return false; 4741 4742 // Find the innermost enclosing namespace for the new and 4743 // previous declarations. 4744 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4745 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4746 4747 // The previous declaration is in a different namespace, so it 4748 // isn't the same function. 4749 if (!OuterContext->Equals(PrevOuterContext)) 4750 return false; 4751 } 4752 4753 return true; 4754} 4755 4756static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4757 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4758 if (!SS.isSet()) return; 4759 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4760} 4761 4762bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4763 QualType type = decl->getType(); 4764 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4765 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4766 // Various kinds of declaration aren't allowed to be __autoreleasing. 4767 unsigned kind = -1U; 4768 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4769 if (var->hasAttr<BlocksAttr>()) 4770 kind = 0; // __block 4771 else if (!var->hasLocalStorage()) 4772 kind = 1; // global 4773 } else if (isa<ObjCIvarDecl>(decl)) { 4774 kind = 3; // ivar 4775 } else if (isa<FieldDecl>(decl)) { 4776 kind = 2; // field 4777 } 4778 4779 if (kind != -1U) { 4780 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4781 << kind; 4782 } 4783 } else if (lifetime == Qualifiers::OCL_None) { 4784 // Try to infer lifetime. 4785 if (!type->isObjCLifetimeType()) 4786 return false; 4787 4788 lifetime = type->getObjCARCImplicitLifetime(); 4789 type = Context.getLifetimeQualifiedType(type, lifetime); 4790 decl->setType(type); 4791 } 4792 4793 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4794 // Thread-local variables cannot have lifetime. 4795 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4796 var->getTLSKind()) { 4797 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4798 << var->getType(); 4799 return true; 4800 } 4801 } 4802 4803 return false; 4804} 4805 4806static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4807 // 'weak' only applies to declarations with external linkage. 4808 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4809 if (!ND.isExternallyVisible()) { 4810 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4811 ND.dropAttr<WeakAttr>(); 4812 } 4813 } 4814 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4815 if (ND.isExternallyVisible()) { 4816 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4817 ND.dropAttr<WeakRefAttr>(); 4818 } 4819 } 4820 4821 // 'selectany' only applies to externally visible varable declarations. 4822 // It does not apply to functions. 4823 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4824 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4825 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4826 ND.dropAttr<SelectAnyAttr>(); 4827 } 4828 } 4829} 4830 4831/// Given that we are within the definition of the given function, 4832/// will that definition behave like C99's 'inline', where the 4833/// definition is discarded except for optimization purposes? 4834static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4835 // Try to avoid calling GetGVALinkageForFunction. 4836 4837 // All cases of this require the 'inline' keyword. 4838 if (!FD->isInlined()) return false; 4839 4840 // This is only possible in C++ with the gnu_inline attribute. 4841 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4842 return false; 4843 4844 // Okay, go ahead and call the relatively-more-expensive function. 4845 4846#ifndef NDEBUG 4847 // AST quite reasonably asserts that it's working on a function 4848 // definition. We don't really have a way to tell it that we're 4849 // currently defining the function, so just lie to it in +Asserts 4850 // builds. This is an awful hack. 4851 FD->setLazyBody(1); 4852#endif 4853 4854 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4855 4856#ifndef NDEBUG 4857 FD->setLazyBody(0); 4858#endif 4859 4860 return isC99Inline; 4861} 4862 4863/// Determine whether a variable is extern "C" prior to attaching 4864/// an initializer. We can't just call isExternC() here, because that 4865/// will also compute and cache whether the declaration is externally 4866/// visible, which might change when we attach the initializer. 4867/// 4868/// This can only be used if the declaration is known to not be a 4869/// redeclaration of an internal linkage declaration. 4870/// 4871/// For instance: 4872/// 4873/// auto x = []{}; 4874/// 4875/// Attaching the initializer here makes this declaration not externally 4876/// visible, because its type has internal linkage. 4877/// 4878/// FIXME: This is a hack. 4879template<typename T> 4880static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4881 if (S.getLangOpts().CPlusPlus) { 4882 // In C++, the overloadable attribute negates the effects of extern "C". 4883 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4884 return false; 4885 } 4886 return D->isExternC(); 4887} 4888 4889static bool shouldConsiderLinkage(const VarDecl *VD) { 4890 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4891 if (DC->isFunctionOrMethod()) 4892 return VD->hasExternalStorage(); 4893 if (DC->isFileContext()) 4894 return true; 4895 if (DC->isRecord()) 4896 return false; 4897 llvm_unreachable("Unexpected context"); 4898} 4899 4900static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4901 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4902 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4903 return true; 4904 if (DC->isRecord()) 4905 return false; 4906 llvm_unreachable("Unexpected context"); 4907} 4908 4909/// Adjust the \c DeclContext for a function or variable that might be a 4910/// function-local external declaration. 4911bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4912 if (!DC->isFunctionOrMethod()) 4913 return false; 4914 4915 // If this is a local extern function or variable declared within a function 4916 // template, don't add it into the enclosing namespace scope until it is 4917 // instantiated; it might have a dependent type right now. 4918 if (DC->isDependentContext()) 4919 return true; 4920 4921 // C++11 [basic.link]p7: 4922 // When a block scope declaration of an entity with linkage is not found to 4923 // refer to some other declaration, then that entity is a member of the 4924 // innermost enclosing namespace. 4925 // 4926 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4927 // semantically-enclosing namespace, not a lexically-enclosing one. 4928 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4929 DC = DC->getParent(); 4930 return true; 4931} 4932 4933NamedDecl * 4934Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4935 TypeSourceInfo *TInfo, LookupResult &Previous, 4936 MultiTemplateParamsArg TemplateParamLists, 4937 bool &AddToScope) { 4938 QualType R = TInfo->getType(); 4939 DeclarationName Name = GetNameForDeclarator(D).getName(); 4940 4941 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4942 VarDecl::StorageClass SC = 4943 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4944 4945 DeclContext *OriginalDC = DC; 4946 bool IsLocalExternDecl = SC == SC_Extern && 4947 adjustContextForLocalExternDecl(DC); 4948 4949 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4950 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4951 // half array type (unless the cl_khr_fp16 extension is enabled). 4952 if (Context.getBaseElementType(R)->isHalfType()) { 4953 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4954 D.setInvalidType(); 4955 } 4956 } 4957 4958 if (SCSpec == DeclSpec::SCS_mutable) { 4959 // mutable can only appear on non-static class members, so it's always 4960 // an error here 4961 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4962 D.setInvalidType(); 4963 SC = SC_None; 4964 } 4965 4966 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 4967 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 4968 D.getDeclSpec().getStorageClassSpecLoc())) { 4969 // In C++11, the 'register' storage class specifier is deprecated. 4970 // Suppress the warning in system macros, it's used in macros in some 4971 // popular C system headers, such as in glibc's htonl() macro. 4972 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4973 diag::warn_deprecated_register) 4974 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4975 } 4976 4977 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4978 if (!II) { 4979 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4980 << Name; 4981 return 0; 4982 } 4983 4984 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4985 4986 if (!DC->isRecord() && S->getFnParent() == 0) { 4987 // C99 6.9p2: The storage-class specifiers auto and register shall not 4988 // appear in the declaration specifiers in an external declaration. 4989 if (SC == SC_Auto || SC == SC_Register) { 4990 // If this is a register variable with an asm label specified, then this 4991 // is a GNU extension. 4992 if (SC == SC_Register && D.getAsmLabel()) 4993 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4994 else 4995 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4996 D.setInvalidType(); 4997 } 4998 } 4999 5000 if (getLangOpts().OpenCL) { 5001 // Set up the special work-group-local storage class for variables in the 5002 // OpenCL __local address space. 5003 if (R.getAddressSpace() == LangAS::opencl_local) { 5004 SC = SC_OpenCLWorkGroupLocal; 5005 } 5006 5007 // OpenCL v1.2 s6.9.b p4: 5008 // The sampler type cannot be used with the __local and __global address 5009 // space qualifiers. 5010 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5011 R.getAddressSpace() == LangAS::opencl_global)) { 5012 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5013 } 5014 5015 // OpenCL 1.2 spec, p6.9 r: 5016 // The event type cannot be used to declare a program scope variable. 5017 // The event type cannot be used with the __local, __constant and __global 5018 // address space qualifiers. 5019 if (R->isEventT()) { 5020 if (S->getParent() == 0) { 5021 Diag(D.getLocStart(), diag::err_event_t_global_var); 5022 D.setInvalidType(); 5023 } 5024 5025 if (R.getAddressSpace()) { 5026 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5027 D.setInvalidType(); 5028 } 5029 } 5030 } 5031 5032 bool IsExplicitSpecialization = false; 5033 bool IsVariableTemplateSpecialization = false; 5034 bool IsPartialSpecialization = false; 5035 bool IsVariableTemplate = false; 5036 VarTemplateDecl *PrevVarTemplate = 0; 5037 VarDecl *NewVD = 0; 5038 VarTemplateDecl *NewTemplate = 0; 5039 if (!getLangOpts().CPlusPlus) { 5040 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5041 D.getIdentifierLoc(), II, 5042 R, TInfo, SC); 5043 5044 if (D.isInvalidType()) 5045 NewVD->setInvalidDecl(); 5046 } else { 5047 bool Invalid = false; 5048 5049 if (DC->isRecord() && !CurContext->isRecord()) { 5050 // This is an out-of-line definition of a static data member. 5051 switch (SC) { 5052 case SC_None: 5053 break; 5054 case SC_Static: 5055 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5056 diag::err_static_out_of_line) 5057 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5058 break; 5059 case SC_Auto: 5060 case SC_Register: 5061 case SC_Extern: 5062 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5063 // to names of variables declared in a block or to function parameters. 5064 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5065 // of class members 5066 5067 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5068 diag::err_storage_class_for_static_member) 5069 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5070 break; 5071 case SC_PrivateExtern: 5072 llvm_unreachable("C storage class in c++!"); 5073 case SC_OpenCLWorkGroupLocal: 5074 llvm_unreachable("OpenCL storage class in c++!"); 5075 } 5076 } 5077 5078 if (SC == SC_Static && CurContext->isRecord()) { 5079 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5080 if (RD->isLocalClass()) 5081 Diag(D.getIdentifierLoc(), 5082 diag::err_static_data_member_not_allowed_in_local_class) 5083 << Name << RD->getDeclName(); 5084 5085 // C++98 [class.union]p1: If a union contains a static data member, 5086 // the program is ill-formed. C++11 drops this restriction. 5087 if (RD->isUnion()) 5088 Diag(D.getIdentifierLoc(), 5089 getLangOpts().CPlusPlus11 5090 ? diag::warn_cxx98_compat_static_data_member_in_union 5091 : diag::ext_static_data_member_in_union) << Name; 5092 // We conservatively disallow static data members in anonymous structs. 5093 else if (!RD->getDeclName()) 5094 Diag(D.getIdentifierLoc(), 5095 diag::err_static_data_member_not_allowed_in_anon_struct) 5096 << Name << RD->isUnion(); 5097 } 5098 } 5099 5100 NamedDecl *PrevDecl = 0; 5101 if (Previous.begin() != Previous.end()) 5102 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5103 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl); 5104 5105 // Match up the template parameter lists with the scope specifier, then 5106 // determine whether we have a template or a template specialization. 5107 TemplateParameterList *TemplateParams = 5108 MatchTemplateParametersToScopeSpecifier( 5109 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5110 D.getCXXScopeSpec(), TemplateParamLists, 5111 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5112 if (TemplateParams) { 5113 if (!TemplateParams->size() && 5114 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5115 // There is an extraneous 'template<>' for this variable. Complain 5116 // about it, but allow the declaration of the variable. 5117 Diag(TemplateParams->getTemplateLoc(), 5118 diag::err_template_variable_noparams) 5119 << II 5120 << SourceRange(TemplateParams->getTemplateLoc(), 5121 TemplateParams->getRAngleLoc()); 5122 } else { 5123 // Only C++1y supports variable templates (N3651). 5124 Diag(D.getIdentifierLoc(), 5125 getLangOpts().CPlusPlus1y 5126 ? diag::warn_cxx11_compat_variable_template 5127 : diag::ext_variable_template); 5128 5129 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5130 // This is an explicit specialization or a partial specialization. 5131 // Check that we can declare a specialization here 5132 5133 IsVariableTemplateSpecialization = true; 5134 IsPartialSpecialization = TemplateParams->size() > 0; 5135 5136 } else { // if (TemplateParams->size() > 0) 5137 // This is a template declaration. 5138 IsVariableTemplate = true; 5139 5140 // Check that we can declare a template here. 5141 if (CheckTemplateDeclScope(S, TemplateParams)) 5142 return 0; 5143 5144 // If there is a previous declaration with the same name, check 5145 // whether this is a valid redeclaration. 5146 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S)) 5147 PrevDecl = PrevVarTemplate = 0; 5148 5149 if (PrevVarTemplate) { 5150 // Ensure that the template parameter lists are compatible. 5151 if (!TemplateParameterListsAreEqual( 5152 TemplateParams, PrevVarTemplate->getTemplateParameters(), 5153 /*Complain=*/true, TPL_TemplateMatch)) 5154 return 0; 5155 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 5156 // Maybe we will complain about the shadowed template parameter. 5157 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5158 5159 // Just pretend that we didn't see the previous declaration. 5160 PrevDecl = 0; 5161 } else if (PrevDecl) { 5162 // C++ [temp]p5: 5163 // ... a template name declared in namespace scope or in class 5164 // scope shall be unique in that scope. 5165 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind) 5166 << Name; 5167 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5168 return 0; 5169 } 5170 5171 // Check the template parameter list of this declaration, possibly 5172 // merging in the template parameter list from the previous variable 5173 // template declaration. 5174 if (CheckTemplateParameterList( 5175 TemplateParams, 5176 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5177 : 0, 5178 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5179 DC->isDependentContext()) 5180 ? TPC_ClassTemplateMember 5181 : TPC_VarTemplate)) 5182 Invalid = true; 5183 5184 if (D.getCXXScopeSpec().isSet()) { 5185 // If the name of the template was qualified, we must be defining 5186 // the template out-of-line. 5187 if (!D.getCXXScopeSpec().isInvalid() && !Invalid && 5188 !PrevVarTemplate) { 5189 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match) 5190 << Name << DC << /*IsDefinition*/true 5191 << D.getCXXScopeSpec().getRange(); 5192 Invalid = true; 5193 } 5194 } 5195 } 5196 } 5197 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5198 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5199 5200 // We have encountered something that the user meant to be a 5201 // specialization (because it has explicitly-specified template 5202 // arguments) but that was not introduced with a "template<>" (or had 5203 // too few of them). 5204 // FIXME: Differentiate between attempts for explicit instantiations 5205 // (starting with "template") and the rest. 5206 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5207 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5208 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5209 "template<> "); 5210 IsVariableTemplateSpecialization = true; 5211 } 5212 5213 if (IsVariableTemplateSpecialization) { 5214 if (!PrevVarTemplate) { 5215 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 5216 << IsPartialSpecialization; 5217 return 0; 5218 } 5219 5220 SourceLocation TemplateKWLoc = 5221 TemplateParamLists.size() > 0 5222 ? TemplateParamLists[0]->getTemplateLoc() 5223 : SourceLocation(); 5224 DeclResult Res = ActOnVarTemplateSpecialization( 5225 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5226 IsPartialSpecialization); 5227 if (Res.isInvalid()) 5228 return 0; 5229 NewVD = cast<VarDecl>(Res.get()); 5230 AddToScope = false; 5231 } else 5232 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5233 D.getIdentifierLoc(), II, R, TInfo, SC); 5234 5235 // If this is supposed to be a variable template, create it as such. 5236 if (IsVariableTemplate) { 5237 NewTemplate = 5238 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5239 TemplateParams, NewVD, PrevVarTemplate); 5240 NewVD->setDescribedVarTemplate(NewTemplate); 5241 } 5242 5243 // If this decl has an auto type in need of deduction, make a note of the 5244 // Decl so we can diagnose uses of it in its own initializer. 5245 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5246 ParsingInitForAutoVars.insert(NewVD); 5247 5248 if (D.isInvalidType() || Invalid) { 5249 NewVD->setInvalidDecl(); 5250 if (NewTemplate) 5251 NewTemplate->setInvalidDecl(); 5252 } 5253 5254 SetNestedNameSpecifier(NewVD, D); 5255 5256 // FIXME: Do we need D.getCXXScopeSpec().isSet()? 5257 if (TemplateParams && TemplateParamLists.size() > 1 && 5258 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) { 5259 NewVD->setTemplateParameterListsInfo( 5260 Context, TemplateParamLists.size() - 1, TemplateParamLists.data()); 5261 } else if (IsVariableTemplateSpecialization || 5262 (!TemplateParams && TemplateParamLists.size() > 0 && 5263 (D.getCXXScopeSpec().isSet()))) { 5264 NewVD->setTemplateParameterListsInfo(Context, 5265 TemplateParamLists.size(), 5266 TemplateParamLists.data()); 5267 } 5268 5269 if (D.getDeclSpec().isConstexprSpecified()) 5270 NewVD->setConstexpr(true); 5271 } 5272 5273 // Set the lexical context. If the declarator has a C++ scope specifier, the 5274 // lexical context will be different from the semantic context. 5275 NewVD->setLexicalDeclContext(CurContext); 5276 if (NewTemplate) 5277 NewTemplate->setLexicalDeclContext(CurContext); 5278 5279 if (IsLocalExternDecl) 5280 NewVD->setLocalExternDecl(); 5281 5282 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5283 if (NewVD->hasLocalStorage()) { 5284 // C++11 [dcl.stc]p4: 5285 // When thread_local is applied to a variable of block scope the 5286 // storage-class-specifier static is implied if it does not appear 5287 // explicitly. 5288 // Core issue: 'static' is not implied if the variable is declared 5289 // 'extern'. 5290 if (SCSpec == DeclSpec::SCS_unspecified && 5291 TSCS == DeclSpec::TSCS_thread_local && 5292 DC->isFunctionOrMethod()) 5293 NewVD->setTSCSpec(TSCS); 5294 else 5295 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5296 diag::err_thread_non_global) 5297 << DeclSpec::getSpecifierName(TSCS); 5298 } else if (!Context.getTargetInfo().isTLSSupported()) 5299 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5300 diag::err_thread_unsupported); 5301 else 5302 NewVD->setTSCSpec(TSCS); 5303 } 5304 5305 // C99 6.7.4p3 5306 // An inline definition of a function with external linkage shall 5307 // not contain a definition of a modifiable object with static or 5308 // thread storage duration... 5309 // We only apply this when the function is required to be defined 5310 // elsewhere, i.e. when the function is not 'extern inline'. Note 5311 // that a local variable with thread storage duration still has to 5312 // be marked 'static'. Also note that it's possible to get these 5313 // semantics in C++ using __attribute__((gnu_inline)). 5314 if (SC == SC_Static && S->getFnParent() != 0 && 5315 !NewVD->getType().isConstQualified()) { 5316 FunctionDecl *CurFD = getCurFunctionDecl(); 5317 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5318 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5319 diag::warn_static_local_in_extern_inline); 5320 MaybeSuggestAddingStaticToDecl(CurFD); 5321 } 5322 } 5323 5324 if (D.getDeclSpec().isModulePrivateSpecified()) { 5325 if (IsVariableTemplateSpecialization) 5326 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5327 << (IsPartialSpecialization ? 1 : 0) 5328 << FixItHint::CreateRemoval( 5329 D.getDeclSpec().getModulePrivateSpecLoc()); 5330 else if (IsExplicitSpecialization) 5331 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5332 << 2 5333 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5334 else if (NewVD->hasLocalStorage()) 5335 Diag(NewVD->getLocation(), diag::err_module_private_local) 5336 << 0 << NewVD->getDeclName() 5337 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5338 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5339 else { 5340 NewVD->setModulePrivate(); 5341 if (NewTemplate) 5342 NewTemplate->setModulePrivate(); 5343 } 5344 } 5345 5346 // Handle attributes prior to checking for duplicates in MergeVarDecl 5347 ProcessDeclAttributes(S, NewVD, D); 5348 5349 if (NewVD->hasAttrs()) 5350 CheckAlignasUnderalignment(NewVD); 5351 5352 if (getLangOpts().CUDA) { 5353 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5354 // storage [duration]." 5355 if (SC == SC_None && S->getFnParent() != 0 && 5356 (NewVD->hasAttr<CUDASharedAttr>() || 5357 NewVD->hasAttr<CUDAConstantAttr>())) { 5358 NewVD->setStorageClass(SC_Static); 5359 } 5360 } 5361 5362 // In auto-retain/release, infer strong retension for variables of 5363 // retainable type. 5364 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5365 NewVD->setInvalidDecl(); 5366 5367 // Handle GNU asm-label extension (encoded as an attribute). 5368 if (Expr *E = (Expr*)D.getAsmLabel()) { 5369 // The parser guarantees this is a string. 5370 StringLiteral *SE = cast<StringLiteral>(E); 5371 StringRef Label = SE->getString(); 5372 if (S->getFnParent() != 0) { 5373 switch (SC) { 5374 case SC_None: 5375 case SC_Auto: 5376 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5377 break; 5378 case SC_Register: 5379 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5380 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5381 break; 5382 case SC_Static: 5383 case SC_Extern: 5384 case SC_PrivateExtern: 5385 case SC_OpenCLWorkGroupLocal: 5386 break; 5387 } 5388 } 5389 5390 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5391 Context, Label)); 5392 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5393 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5394 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5395 if (I != ExtnameUndeclaredIdentifiers.end()) { 5396 NewVD->addAttr(I->second); 5397 ExtnameUndeclaredIdentifiers.erase(I); 5398 } 5399 } 5400 5401 // Diagnose shadowed variables before filtering for scope. 5402 if (!D.getCXXScopeSpec().isSet()) 5403 CheckShadow(S, NewVD, Previous); 5404 5405 // Don't consider existing declarations that are in a different 5406 // scope and are out-of-semantic-context declarations (if the new 5407 // declaration has linkage). 5408 FilterLookupForScope( 5409 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5410 IsExplicitSpecialization || IsVariableTemplateSpecialization); 5411 5412 // Check whether the previous declaration is in the same block scope. This 5413 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5414 if (getLangOpts().CPlusPlus && 5415 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5416 NewVD->setPreviousDeclInSameBlockScope( 5417 Previous.isSingleResult() && !Previous.isShadowed() && 5418 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5419 5420 if (!getLangOpts().CPlusPlus) { 5421 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5422 } else { 5423 // Merge the decl with the existing one if appropriate. 5424 if (!Previous.empty()) { 5425 if (Previous.isSingleResult() && 5426 isa<FieldDecl>(Previous.getFoundDecl()) && 5427 D.getCXXScopeSpec().isSet()) { 5428 // The user tried to define a non-static data member 5429 // out-of-line (C++ [dcl.meaning]p1). 5430 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5431 << D.getCXXScopeSpec().getRange(); 5432 Previous.clear(); 5433 NewVD->setInvalidDecl(); 5434 } 5435 } else if (D.getCXXScopeSpec().isSet()) { 5436 // No previous declaration in the qualifying scope. 5437 Diag(D.getIdentifierLoc(), diag::err_no_member) 5438 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5439 << D.getCXXScopeSpec().getRange(); 5440 NewVD->setInvalidDecl(); 5441 } 5442 5443 if (!IsVariableTemplateSpecialization) { 5444 if (PrevVarTemplate) { 5445 LookupResult PrevDecl(*this, GetNameForDeclarator(D), 5446 LookupOrdinaryName, ForRedeclaration); 5447 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl()); 5448 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl)); 5449 } else 5450 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5451 } 5452 5453 // This is an explicit specialization of a static data member. Check it. 5454 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5455 CheckMemberSpecialization(NewVD, Previous)) 5456 NewVD->setInvalidDecl(); 5457 } 5458 5459 ProcessPragmaWeak(S, NewVD); 5460 checkAttributesAfterMerging(*this, *NewVD); 5461 5462 // If this is the first declaration of an extern C variable, update 5463 // the map of such variables. 5464 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5465 isIncompleteDeclExternC(*this, NewVD)) 5466 RegisterLocallyScopedExternCDecl(NewVD, S); 5467 5468 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5469 Decl *ManglingContextDecl; 5470 if (MangleNumberingContext *MCtx = 5471 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5472 ManglingContextDecl)) { 5473 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5474 } 5475 } 5476 5477 // If we are providing an explicit specialization of a static variable 5478 // template, make a note of that. 5479 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5480 PrevVarTemplate->setMemberSpecialization(); 5481 5482 if (NewTemplate) { 5483 ActOnDocumentableDecl(NewTemplate); 5484 return NewTemplate; 5485 } 5486 5487 return NewVD; 5488} 5489 5490/// \brief Diagnose variable or built-in function shadowing. Implements 5491/// -Wshadow. 5492/// 5493/// This method is called whenever a VarDecl is added to a "useful" 5494/// scope. 5495/// 5496/// \param S the scope in which the shadowing name is being declared 5497/// \param R the lookup of the name 5498/// 5499void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5500 // Return if warning is ignored. 5501 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5502 DiagnosticsEngine::Ignored) 5503 return; 5504 5505 // Don't diagnose declarations at file scope. 5506 if (D->hasGlobalStorage()) 5507 return; 5508 5509 DeclContext *NewDC = D->getDeclContext(); 5510 5511 // Only diagnose if we're shadowing an unambiguous field or variable. 5512 if (R.getResultKind() != LookupResult::Found) 5513 return; 5514 5515 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5516 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5517 return; 5518 5519 // Fields are not shadowed by variables in C++ static methods. 5520 if (isa<FieldDecl>(ShadowedDecl)) 5521 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5522 if (MD->isStatic()) 5523 return; 5524 5525 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5526 if (shadowedVar->isExternC()) { 5527 // For shadowing external vars, make sure that we point to the global 5528 // declaration, not a locally scoped extern declaration. 5529 for (VarDecl::redecl_iterator 5530 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5531 I != E; ++I) 5532 if (I->isFileVarDecl()) { 5533 ShadowedDecl = *I; 5534 break; 5535 } 5536 } 5537 5538 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5539 5540 // Only warn about certain kinds of shadowing for class members. 5541 if (NewDC && NewDC->isRecord()) { 5542 // In particular, don't warn about shadowing non-class members. 5543 if (!OldDC->isRecord()) 5544 return; 5545 5546 // TODO: should we warn about static data members shadowing 5547 // static data members from base classes? 5548 5549 // TODO: don't diagnose for inaccessible shadowed members. 5550 // This is hard to do perfectly because we might friend the 5551 // shadowing context, but that's just a false negative. 5552 } 5553 5554 // Determine what kind of declaration we're shadowing. 5555 unsigned Kind; 5556 if (isa<RecordDecl>(OldDC)) { 5557 if (isa<FieldDecl>(ShadowedDecl)) 5558 Kind = 3; // field 5559 else 5560 Kind = 2; // static data member 5561 } else if (OldDC->isFileContext()) 5562 Kind = 1; // global 5563 else 5564 Kind = 0; // local 5565 5566 DeclarationName Name = R.getLookupName(); 5567 5568 // Emit warning and note. 5569 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5570 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5571} 5572 5573/// \brief Check -Wshadow without the advantage of a previous lookup. 5574void Sema::CheckShadow(Scope *S, VarDecl *D) { 5575 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5576 DiagnosticsEngine::Ignored) 5577 return; 5578 5579 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5580 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5581 LookupName(R, S); 5582 CheckShadow(S, D, R); 5583} 5584 5585/// Check for conflict between this global or extern "C" declaration and 5586/// previous global or extern "C" declarations. This is only used in C++. 5587template<typename T> 5588static bool checkGlobalOrExternCConflict( 5589 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5590 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5591 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5592 5593 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5594 // The common case: this global doesn't conflict with any extern "C" 5595 // declaration. 5596 return false; 5597 } 5598 5599 if (Prev) { 5600 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5601 // Both the old and new declarations have C language linkage. This is a 5602 // redeclaration. 5603 Previous.clear(); 5604 Previous.addDecl(Prev); 5605 return true; 5606 } 5607 5608 // This is a global, non-extern "C" declaration, and there is a previous 5609 // non-global extern "C" declaration. Diagnose if this is a variable 5610 // declaration. 5611 if (!isa<VarDecl>(ND)) 5612 return false; 5613 } else { 5614 // The declaration is extern "C". Check for any declaration in the 5615 // translation unit which might conflict. 5616 if (IsGlobal) { 5617 // We have already performed the lookup into the translation unit. 5618 IsGlobal = false; 5619 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5620 I != E; ++I) { 5621 if (isa<VarDecl>(*I)) { 5622 Prev = *I; 5623 break; 5624 } 5625 } 5626 } else { 5627 DeclContext::lookup_result R = 5628 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5629 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5630 I != E; ++I) { 5631 if (isa<VarDecl>(*I)) { 5632 Prev = *I; 5633 break; 5634 } 5635 // FIXME: If we have any other entity with this name in global scope, 5636 // the declaration is ill-formed, but that is a defect: it breaks the 5637 // 'stat' hack, for instance. Only variables can have mangled name 5638 // clashes with extern "C" declarations, so only they deserve a 5639 // diagnostic. 5640 } 5641 } 5642 5643 if (!Prev) 5644 return false; 5645 } 5646 5647 // Use the first declaration's location to ensure we point at something which 5648 // is lexically inside an extern "C" linkage-spec. 5649 assert(Prev && "should have found a previous declaration to diagnose"); 5650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5651 Prev = FD->getFirstDecl(); 5652 else 5653 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5654 5655 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5656 << IsGlobal << ND; 5657 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5658 << IsGlobal; 5659 return false; 5660} 5661 5662/// Apply special rules for handling extern "C" declarations. Returns \c true 5663/// if we have found that this is a redeclaration of some prior entity. 5664/// 5665/// Per C++ [dcl.link]p6: 5666/// Two declarations [for a function or variable] with C language linkage 5667/// with the same name that appear in different scopes refer to the same 5668/// [entity]. An entity with C language linkage shall not be declared with 5669/// the same name as an entity in global scope. 5670template<typename T> 5671static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5672 LookupResult &Previous) { 5673 if (!S.getLangOpts().CPlusPlus) { 5674 // In C, when declaring a global variable, look for a corresponding 'extern' 5675 // variable declared in function scope. We don't need this in C++, because 5676 // we find local extern decls in the surrounding file-scope DeclContext. 5677 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5678 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5679 Previous.clear(); 5680 Previous.addDecl(Prev); 5681 return true; 5682 } 5683 } 5684 return false; 5685 } 5686 5687 // A declaration in the translation unit can conflict with an extern "C" 5688 // declaration. 5689 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5690 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5691 5692 // An extern "C" declaration can conflict with a declaration in the 5693 // translation unit or can be a redeclaration of an extern "C" declaration 5694 // in another scope. 5695 if (isIncompleteDeclExternC(S,ND)) 5696 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5697 5698 // Neither global nor extern "C": nothing to do. 5699 return false; 5700} 5701 5702void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5703 // If the decl is already known invalid, don't check it. 5704 if (NewVD->isInvalidDecl()) 5705 return; 5706 5707 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5708 QualType T = TInfo->getType(); 5709 5710 // Defer checking an 'auto' type until its initializer is attached. 5711 if (T->isUndeducedType()) 5712 return; 5713 5714 if (T->isObjCObjectType()) { 5715 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5716 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5717 T = Context.getObjCObjectPointerType(T); 5718 NewVD->setType(T); 5719 } 5720 5721 // Emit an error if an address space was applied to decl with local storage. 5722 // This includes arrays of objects with address space qualifiers, but not 5723 // automatic variables that point to other address spaces. 5724 // ISO/IEC TR 18037 S5.1.2 5725 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5726 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5727 NewVD->setInvalidDecl(); 5728 return; 5729 } 5730 5731 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5732 // __constant address space. 5733 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5734 && T.getAddressSpace() != LangAS::opencl_constant 5735 && !T->isSamplerT()){ 5736 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5737 NewVD->setInvalidDecl(); 5738 return; 5739 } 5740 5741 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5742 // scope. 5743 if ((getLangOpts().OpenCLVersion >= 120) 5744 && NewVD->isStaticLocal()) { 5745 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5746 NewVD->setInvalidDecl(); 5747 return; 5748 } 5749 5750 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5751 && !NewVD->hasAttr<BlocksAttr>()) { 5752 if (getLangOpts().getGC() != LangOptions::NonGC) 5753 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5754 else { 5755 assert(!getLangOpts().ObjCAutoRefCount); 5756 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5757 } 5758 } 5759 5760 bool isVM = T->isVariablyModifiedType(); 5761 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5762 NewVD->hasAttr<BlocksAttr>()) 5763 getCurFunction()->setHasBranchProtectedScope(); 5764 5765 if ((isVM && NewVD->hasLinkage()) || 5766 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5767 bool SizeIsNegative; 5768 llvm::APSInt Oversized; 5769 TypeSourceInfo *FixedTInfo = 5770 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5771 SizeIsNegative, Oversized); 5772 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5773 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5774 // FIXME: This won't give the correct result for 5775 // int a[10][n]; 5776 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5777 5778 if (NewVD->isFileVarDecl()) 5779 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5780 << SizeRange; 5781 else if (NewVD->isStaticLocal()) 5782 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5783 << SizeRange; 5784 else 5785 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5786 << SizeRange; 5787 NewVD->setInvalidDecl(); 5788 return; 5789 } 5790 5791 if (FixedTInfo == 0) { 5792 if (NewVD->isFileVarDecl()) 5793 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5794 else 5795 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5796 NewVD->setInvalidDecl(); 5797 return; 5798 } 5799 5800 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5801 NewVD->setType(FixedTInfo->getType()); 5802 NewVD->setTypeSourceInfo(FixedTInfo); 5803 } 5804 5805 if (T->isVoidType()) { 5806 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5807 // of objects and functions. 5808 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5809 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5810 << T; 5811 NewVD->setInvalidDecl(); 5812 return; 5813 } 5814 } 5815 5816 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5817 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5818 NewVD->setInvalidDecl(); 5819 return; 5820 } 5821 5822 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5823 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5824 NewVD->setInvalidDecl(); 5825 return; 5826 } 5827 5828 if (NewVD->isConstexpr() && !T->isDependentType() && 5829 RequireLiteralType(NewVD->getLocation(), T, 5830 diag::err_constexpr_var_non_literal)) { 5831 // Can't perform this check until the type is deduced. 5832 NewVD->setInvalidDecl(); 5833 return; 5834 } 5835} 5836 5837/// \brief Perform semantic checking on a newly-created variable 5838/// declaration. 5839/// 5840/// This routine performs all of the type-checking required for a 5841/// variable declaration once it has been built. It is used both to 5842/// check variables after they have been parsed and their declarators 5843/// have been translated into a declaration, and to check variables 5844/// that have been instantiated from a template. 5845/// 5846/// Sets NewVD->isInvalidDecl() if an error was encountered. 5847/// 5848/// Returns true if the variable declaration is a redeclaration. 5849bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5850 CheckVariableDeclarationType(NewVD); 5851 5852 // If the decl is already known invalid, don't check it. 5853 if (NewVD->isInvalidDecl()) 5854 return false; 5855 5856 // If we did not find anything by this name, look for a non-visible 5857 // extern "C" declaration with the same name. 5858 if (Previous.empty() && 5859 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5860 Previous.setShadowed(); 5861 5862 // Filter out any non-conflicting previous declarations. 5863 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5864 5865 if (!Previous.empty()) { 5866 MergeVarDecl(NewVD, Previous); 5867 return true; 5868 } 5869 return false; 5870} 5871 5872/// \brief Data used with FindOverriddenMethod 5873struct FindOverriddenMethodData { 5874 Sema *S; 5875 CXXMethodDecl *Method; 5876}; 5877 5878/// \brief Member lookup function that determines whether a given C++ 5879/// method overrides a method in a base class, to be used with 5880/// CXXRecordDecl::lookupInBases(). 5881static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5882 CXXBasePath &Path, 5883 void *UserData) { 5884 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5885 5886 FindOverriddenMethodData *Data 5887 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5888 5889 DeclarationName Name = Data->Method->getDeclName(); 5890 5891 // FIXME: Do we care about other names here too? 5892 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5893 // We really want to find the base class destructor here. 5894 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5895 CanQualType CT = Data->S->Context.getCanonicalType(T); 5896 5897 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5898 } 5899 5900 for (Path.Decls = BaseRecord->lookup(Name); 5901 !Path.Decls.empty(); 5902 Path.Decls = Path.Decls.slice(1)) { 5903 NamedDecl *D = Path.Decls.front(); 5904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5905 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5906 return true; 5907 } 5908 } 5909 5910 return false; 5911} 5912 5913namespace { 5914 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5915} 5916/// \brief Report an error regarding overriding, along with any relevant 5917/// overriden methods. 5918/// 5919/// \param DiagID the primary error to report. 5920/// \param MD the overriding method. 5921/// \param OEK which overrides to include as notes. 5922static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5923 OverrideErrorKind OEK = OEK_All) { 5924 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5925 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5926 E = MD->end_overridden_methods(); 5927 I != E; ++I) { 5928 // This check (& the OEK parameter) could be replaced by a predicate, but 5929 // without lambdas that would be overkill. This is still nicer than writing 5930 // out the diag loop 3 times. 5931 if ((OEK == OEK_All) || 5932 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5933 (OEK == OEK_Deleted && (*I)->isDeleted())) 5934 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5935 } 5936} 5937 5938/// AddOverriddenMethods - See if a method overrides any in the base classes, 5939/// and if so, check that it's a valid override and remember it. 5940bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5941 // Look for virtual methods in base classes that this method might override. 5942 CXXBasePaths Paths; 5943 FindOverriddenMethodData Data; 5944 Data.Method = MD; 5945 Data.S = this; 5946 bool hasDeletedOverridenMethods = false; 5947 bool hasNonDeletedOverridenMethods = false; 5948 bool AddedAny = false; 5949 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5950 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5951 E = Paths.found_decls_end(); I != E; ++I) { 5952 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5953 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5954 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5955 !CheckOverridingFunctionAttributes(MD, OldMD) && 5956 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5957 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5958 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5959 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5960 AddedAny = true; 5961 } 5962 } 5963 } 5964 } 5965 5966 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5967 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5968 } 5969 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5970 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5971 } 5972 5973 return AddedAny; 5974} 5975 5976namespace { 5977 // Struct for holding all of the extra arguments needed by 5978 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5979 struct ActOnFDArgs { 5980 Scope *S; 5981 Declarator &D; 5982 MultiTemplateParamsArg TemplateParamLists; 5983 bool AddToScope; 5984 }; 5985} 5986 5987namespace { 5988 5989// Callback to only accept typo corrections that have a non-zero edit distance. 5990// Also only accept corrections that have the same parent decl. 5991class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5992 public: 5993 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5994 CXXRecordDecl *Parent) 5995 : Context(Context), OriginalFD(TypoFD), 5996 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5997 5998 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5999 if (candidate.getEditDistance() == 0) 6000 return false; 6001 6002 SmallVector<unsigned, 1> MismatchedParams; 6003 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6004 CDeclEnd = candidate.end(); 6005 CDecl != CDeclEnd; ++CDecl) { 6006 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6007 6008 if (FD && !FD->hasBody() && 6009 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6010 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6011 CXXRecordDecl *Parent = MD->getParent(); 6012 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6013 return true; 6014 } else if (!ExpectedParent) { 6015 return true; 6016 } 6017 } 6018 } 6019 6020 return false; 6021 } 6022 6023 private: 6024 ASTContext &Context; 6025 FunctionDecl *OriginalFD; 6026 CXXRecordDecl *ExpectedParent; 6027}; 6028 6029} 6030 6031/// \brief Generate diagnostics for an invalid function redeclaration. 6032/// 6033/// This routine handles generating the diagnostic messages for an invalid 6034/// function redeclaration, including finding possible similar declarations 6035/// or performing typo correction if there are no previous declarations with 6036/// the same name. 6037/// 6038/// Returns a NamedDecl iff typo correction was performed and substituting in 6039/// the new declaration name does not cause new errors. 6040static NamedDecl *DiagnoseInvalidRedeclaration( 6041 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6042 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6043 DeclarationName Name = NewFD->getDeclName(); 6044 DeclContext *NewDC = NewFD->getDeclContext(); 6045 SmallVector<unsigned, 1> MismatchedParams; 6046 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6047 TypoCorrection Correction; 6048 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6049 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6050 : diag::err_member_decl_does_not_match; 6051 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6052 IsLocalFriend ? Sema::LookupLocalFriendName 6053 : Sema::LookupOrdinaryName, 6054 Sema::ForRedeclaration); 6055 6056 NewFD->setInvalidDecl(); 6057 if (IsLocalFriend) 6058 SemaRef.LookupName(Prev, S); 6059 else 6060 SemaRef.LookupQualifiedName(Prev, NewDC); 6061 assert(!Prev.isAmbiguous() && 6062 "Cannot have an ambiguity in previous-declaration lookup"); 6063 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6064 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6065 MD ? MD->getParent() : 0); 6066 if (!Prev.empty()) { 6067 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6068 Func != FuncEnd; ++Func) { 6069 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6070 if (FD && 6071 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6072 // Add 1 to the index so that 0 can mean the mismatch didn't 6073 // involve a parameter 6074 unsigned ParamNum = 6075 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6076 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6077 } 6078 } 6079 // If the qualified name lookup yielded nothing, try typo correction 6080 } else if ((Correction = SemaRef.CorrectTypo( 6081 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6082 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6083 IsLocalFriend ? 0 : NewDC))) { 6084 // Set up everything for the call to ActOnFunctionDeclarator 6085 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6086 ExtraArgs.D.getIdentifierLoc()); 6087 Previous.clear(); 6088 Previous.setLookupName(Correction.getCorrection()); 6089 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6090 CDeclEnd = Correction.end(); 6091 CDecl != CDeclEnd; ++CDecl) { 6092 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6093 if (FD && !FD->hasBody() && 6094 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6095 Previous.addDecl(FD); 6096 } 6097 } 6098 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6099 6100 NamedDecl *Result; 6101 // Retry building the function declaration with the new previous 6102 // declarations, and with errors suppressed. 6103 { 6104 // Trap errors. 6105 Sema::SFINAETrap Trap(SemaRef); 6106 6107 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6108 // pieces need to verify the typo-corrected C++ declaration and hopefully 6109 // eliminate the need for the parameter pack ExtraArgs. 6110 Result = SemaRef.ActOnFunctionDeclarator( 6111 ExtraArgs.S, ExtraArgs.D, 6112 Correction.getCorrectionDecl()->getDeclContext(), 6113 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6114 ExtraArgs.AddToScope); 6115 6116 if (Trap.hasErrorOccurred()) 6117 Result = 0; 6118 } 6119 6120 if (Result) { 6121 // Determine which correction we picked. 6122 Decl *Canonical = Result->getCanonicalDecl(); 6123 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6124 I != E; ++I) 6125 if ((*I)->getCanonicalDecl() == Canonical) 6126 Correction.setCorrectionDecl(*I); 6127 6128 SemaRef.diagnoseTypo( 6129 Correction, 6130 SemaRef.PDiag(IsLocalFriend 6131 ? diag::err_no_matching_local_friend_suggest 6132 : diag::err_member_decl_does_not_match_suggest) 6133 << Name << NewDC << IsDefinition); 6134 return Result; 6135 } 6136 6137 // Pretend the typo correction never occurred 6138 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6139 ExtraArgs.D.getIdentifierLoc()); 6140 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6141 Previous.clear(); 6142 Previous.setLookupName(Name); 6143 } 6144 6145 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6146 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6147 6148 bool NewFDisConst = false; 6149 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6150 NewFDisConst = NewMD->isConst(); 6151 6152 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6153 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6154 NearMatch != NearMatchEnd; ++NearMatch) { 6155 FunctionDecl *FD = NearMatch->first; 6156 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6157 bool FDisConst = MD && MD->isConst(); 6158 bool IsMember = MD || !IsLocalFriend; 6159 6160 // FIXME: These notes are poorly worded for the local friend case. 6161 if (unsigned Idx = NearMatch->second) { 6162 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6163 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6164 if (Loc.isInvalid()) Loc = FD->getLocation(); 6165 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6166 : diag::note_local_decl_close_param_match) 6167 << Idx << FDParam->getType() 6168 << NewFD->getParamDecl(Idx - 1)->getType(); 6169 } else if (FDisConst != NewFDisConst) { 6170 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6171 << NewFDisConst << FD->getSourceRange().getEnd(); 6172 } else 6173 SemaRef.Diag(FD->getLocation(), 6174 IsMember ? diag::note_member_def_close_match 6175 : diag::note_local_decl_close_match); 6176 } 6177 return 0; 6178} 6179 6180static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6181 Declarator &D) { 6182 switch (D.getDeclSpec().getStorageClassSpec()) { 6183 default: llvm_unreachable("Unknown storage class!"); 6184 case DeclSpec::SCS_auto: 6185 case DeclSpec::SCS_register: 6186 case DeclSpec::SCS_mutable: 6187 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6188 diag::err_typecheck_sclass_func); 6189 D.setInvalidType(); 6190 break; 6191 case DeclSpec::SCS_unspecified: break; 6192 case DeclSpec::SCS_extern: 6193 if (D.getDeclSpec().isExternInLinkageSpec()) 6194 return SC_None; 6195 return SC_Extern; 6196 case DeclSpec::SCS_static: { 6197 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6198 // C99 6.7.1p5: 6199 // The declaration of an identifier for a function that has 6200 // block scope shall have no explicit storage-class specifier 6201 // other than extern 6202 // See also (C++ [dcl.stc]p4). 6203 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6204 diag::err_static_block_func); 6205 break; 6206 } else 6207 return SC_Static; 6208 } 6209 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6210 } 6211 6212 // No explicit storage class has already been returned 6213 return SC_None; 6214} 6215 6216static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6217 DeclContext *DC, QualType &R, 6218 TypeSourceInfo *TInfo, 6219 FunctionDecl::StorageClass SC, 6220 bool &IsVirtualOkay) { 6221 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6222 DeclarationName Name = NameInfo.getName(); 6223 6224 FunctionDecl *NewFD = 0; 6225 bool isInline = D.getDeclSpec().isInlineSpecified(); 6226 6227 if (!SemaRef.getLangOpts().CPlusPlus) { 6228 // Determine whether the function was written with a 6229 // prototype. This true when: 6230 // - there is a prototype in the declarator, or 6231 // - the type R of the function is some kind of typedef or other reference 6232 // to a type name (which eventually refers to a function type). 6233 bool HasPrototype = 6234 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6235 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6236 6237 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6238 D.getLocStart(), NameInfo, R, 6239 TInfo, SC, isInline, 6240 HasPrototype, false); 6241 if (D.isInvalidType()) 6242 NewFD->setInvalidDecl(); 6243 6244 // Set the lexical context. 6245 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6246 6247 return NewFD; 6248 } 6249 6250 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6251 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6252 6253 // Check that the return type is not an abstract class type. 6254 // For record types, this is done by the AbstractClassUsageDiagnoser once 6255 // the class has been completely parsed. 6256 if (!DC->isRecord() && 6257 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 6258 R->getAs<FunctionType>()->getResultType(), 6259 diag::err_abstract_type_in_decl, 6260 SemaRef.AbstractReturnType)) 6261 D.setInvalidType(); 6262 6263 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6264 // This is a C++ constructor declaration. 6265 assert(DC->isRecord() && 6266 "Constructors can only be declared in a member context"); 6267 6268 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6269 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6270 D.getLocStart(), NameInfo, 6271 R, TInfo, isExplicit, isInline, 6272 /*isImplicitlyDeclared=*/false, 6273 isConstexpr); 6274 6275 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6276 // This is a C++ destructor declaration. 6277 if (DC->isRecord()) { 6278 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6279 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6280 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6281 SemaRef.Context, Record, 6282 D.getLocStart(), 6283 NameInfo, R, TInfo, isInline, 6284 /*isImplicitlyDeclared=*/false); 6285 6286 // If the class is complete, then we now create the implicit exception 6287 // specification. If the class is incomplete or dependent, we can't do 6288 // it yet. 6289 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6290 Record->getDefinition() && !Record->isBeingDefined() && 6291 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6292 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6293 } 6294 6295 // The Microsoft ABI requires that we perform the destructor body 6296 // checks (i.e. operator delete() lookup) at every declaration, as 6297 // any translation unit may need to emit a deleting destructor. 6298 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6299 !Record->isDependentType() && Record->getDefinition() && 6300 !Record->isBeingDefined()) { 6301 SemaRef.CheckDestructor(NewDD); 6302 } 6303 6304 IsVirtualOkay = true; 6305 return NewDD; 6306 6307 } else { 6308 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6309 D.setInvalidType(); 6310 6311 // Create a FunctionDecl to satisfy the function definition parsing 6312 // code path. 6313 return FunctionDecl::Create(SemaRef.Context, DC, 6314 D.getLocStart(), 6315 D.getIdentifierLoc(), Name, R, TInfo, 6316 SC, isInline, 6317 /*hasPrototype=*/true, isConstexpr); 6318 } 6319 6320 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6321 if (!DC->isRecord()) { 6322 SemaRef.Diag(D.getIdentifierLoc(), 6323 diag::err_conv_function_not_member); 6324 return 0; 6325 } 6326 6327 SemaRef.CheckConversionDeclarator(D, R, SC); 6328 IsVirtualOkay = true; 6329 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6330 D.getLocStart(), NameInfo, 6331 R, TInfo, isInline, isExplicit, 6332 isConstexpr, SourceLocation()); 6333 6334 } else if (DC->isRecord()) { 6335 // If the name of the function is the same as the name of the record, 6336 // then this must be an invalid constructor that has a return type. 6337 // (The parser checks for a return type and makes the declarator a 6338 // constructor if it has no return type). 6339 if (Name.getAsIdentifierInfo() && 6340 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6341 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6342 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6343 << SourceRange(D.getIdentifierLoc()); 6344 return 0; 6345 } 6346 6347 // This is a C++ method declaration. 6348 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6349 cast<CXXRecordDecl>(DC), 6350 D.getLocStart(), NameInfo, R, 6351 TInfo, SC, isInline, 6352 isConstexpr, SourceLocation()); 6353 IsVirtualOkay = !Ret->isStatic(); 6354 return Ret; 6355 } else { 6356 // Determine whether the function was written with a 6357 // prototype. This true when: 6358 // - we're in C++ (where every function has a prototype), 6359 return FunctionDecl::Create(SemaRef.Context, DC, 6360 D.getLocStart(), 6361 NameInfo, R, TInfo, SC, isInline, 6362 true/*HasPrototype*/, isConstexpr); 6363 } 6364} 6365 6366void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6367 // In C++, the empty parameter-type-list must be spelled "void"; a 6368 // typedef of void is not permitted. 6369 if (getLangOpts().CPlusPlus && 6370 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6371 bool IsTypeAlias = false; 6372 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6373 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6374 else if (const TemplateSpecializationType *TST = 6375 Param->getType()->getAs<TemplateSpecializationType>()) 6376 IsTypeAlias = TST->isTypeAlias(); 6377 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6378 << IsTypeAlias; 6379 } 6380} 6381 6382enum OpenCLParamType { 6383 ValidKernelParam, 6384 PtrPtrKernelParam, 6385 PtrKernelParam, 6386 InvalidKernelParam, 6387 RecordKernelParam 6388}; 6389 6390static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6391 if (PT->isPointerType()) { 6392 QualType PointeeType = PT->getPointeeType(); 6393 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6394 } 6395 6396 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6397 // be used as builtin types. 6398 6399 if (PT->isImageType()) 6400 return PtrKernelParam; 6401 6402 if (PT->isBooleanType()) 6403 return InvalidKernelParam; 6404 6405 if (PT->isEventT()) 6406 return InvalidKernelParam; 6407 6408 if (PT->isHalfType()) 6409 return InvalidKernelParam; 6410 6411 if (PT->isRecordType()) 6412 return RecordKernelParam; 6413 6414 return ValidKernelParam; 6415} 6416 6417static void checkIsValidOpenCLKernelParameter( 6418 Sema &S, 6419 Declarator &D, 6420 ParmVarDecl *Param, 6421 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6422 QualType PT = Param->getType(); 6423 6424 // Cache the valid types we encounter to avoid rechecking structs that are 6425 // used again 6426 if (ValidTypes.count(PT.getTypePtr())) 6427 return; 6428 6429 switch (getOpenCLKernelParameterType(PT)) { 6430 case PtrPtrKernelParam: 6431 // OpenCL v1.2 s6.9.a: 6432 // A kernel function argument cannot be declared as a 6433 // pointer to a pointer type. 6434 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6435 D.setInvalidType(); 6436 return; 6437 6438 // OpenCL v1.2 s6.9.k: 6439 // Arguments to kernel functions in a program cannot be declared with the 6440 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6441 // uintptr_t or a struct and/or union that contain fields declared to be 6442 // one of these built-in scalar types. 6443 6444 case InvalidKernelParam: 6445 // OpenCL v1.2 s6.8 n: 6446 // A kernel function argument cannot be declared 6447 // of event_t type. 6448 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6449 D.setInvalidType(); 6450 return; 6451 6452 case PtrKernelParam: 6453 case ValidKernelParam: 6454 ValidTypes.insert(PT.getTypePtr()); 6455 return; 6456 6457 case RecordKernelParam: 6458 break; 6459 } 6460 6461 // Track nested structs we will inspect 6462 SmallVector<const Decl *, 4> VisitStack; 6463 6464 // Track where we are in the nested structs. Items will migrate from 6465 // VisitStack to HistoryStack as we do the DFS for bad field. 6466 SmallVector<const FieldDecl *, 4> HistoryStack; 6467 HistoryStack.push_back((const FieldDecl *) 0); 6468 6469 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6470 VisitStack.push_back(PD); 6471 6472 assert(VisitStack.back() && "First decl null?"); 6473 6474 do { 6475 const Decl *Next = VisitStack.pop_back_val(); 6476 if (!Next) { 6477 assert(!HistoryStack.empty()); 6478 // Found a marker, we have gone up a level 6479 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6480 ValidTypes.insert(Hist->getType().getTypePtr()); 6481 6482 continue; 6483 } 6484 6485 // Adds everything except the original parameter declaration (which is not a 6486 // field itself) to the history stack. 6487 const RecordDecl *RD; 6488 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6489 HistoryStack.push_back(Field); 6490 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6491 } else { 6492 RD = cast<RecordDecl>(Next); 6493 } 6494 6495 // Add a null marker so we know when we've gone back up a level 6496 VisitStack.push_back((const Decl *) 0); 6497 6498 for (RecordDecl::field_iterator I = RD->field_begin(), 6499 E = RD->field_end(); I != E; ++I) { 6500 const FieldDecl *FD = *I; 6501 QualType QT = FD->getType(); 6502 6503 if (ValidTypes.count(QT.getTypePtr())) 6504 continue; 6505 6506 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6507 if (ParamType == ValidKernelParam) 6508 continue; 6509 6510 if (ParamType == RecordKernelParam) { 6511 VisitStack.push_back(FD); 6512 continue; 6513 } 6514 6515 // OpenCL v1.2 s6.9.p: 6516 // Arguments to kernel functions that are declared to be a struct or union 6517 // do not allow OpenCL objects to be passed as elements of the struct or 6518 // union. 6519 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6520 S.Diag(Param->getLocation(), 6521 diag::err_record_with_pointers_kernel_param) 6522 << PT->isUnionType() 6523 << PT; 6524 } else { 6525 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6526 } 6527 6528 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6529 << PD->getDeclName(); 6530 6531 // We have an error, now let's go back up through history and show where 6532 // the offending field came from 6533 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6534 E = HistoryStack.end(); I != E; ++I) { 6535 const FieldDecl *OuterField = *I; 6536 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6537 << OuterField->getType(); 6538 } 6539 6540 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6541 << QT->isPointerType() 6542 << QT; 6543 D.setInvalidType(); 6544 return; 6545 } 6546 } while (!VisitStack.empty()); 6547} 6548 6549NamedDecl* 6550Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6551 TypeSourceInfo *TInfo, LookupResult &Previous, 6552 MultiTemplateParamsArg TemplateParamLists, 6553 bool &AddToScope) { 6554 QualType R = TInfo->getType(); 6555 6556 assert(R.getTypePtr()->isFunctionType()); 6557 6558 // TODO: consider using NameInfo for diagnostic. 6559 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6560 DeclarationName Name = NameInfo.getName(); 6561 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6562 6563 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6564 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6565 diag::err_invalid_thread) 6566 << DeclSpec::getSpecifierName(TSCS); 6567 6568 if (D.isFirstDeclarationOfMember()) 6569 adjustMemberFunctionCC(R, D.isStaticMember()); 6570 6571 bool isFriend = false; 6572 FunctionTemplateDecl *FunctionTemplate = 0; 6573 bool isExplicitSpecialization = false; 6574 bool isFunctionTemplateSpecialization = false; 6575 6576 bool isDependentClassScopeExplicitSpecialization = false; 6577 bool HasExplicitTemplateArgs = false; 6578 TemplateArgumentListInfo TemplateArgs; 6579 6580 bool isVirtualOkay = false; 6581 6582 DeclContext *OriginalDC = DC; 6583 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6584 6585 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6586 isVirtualOkay); 6587 if (!NewFD) return 0; 6588 6589 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6590 NewFD->setTopLevelDeclInObjCContainer(); 6591 6592 // Set the lexical context. If this is a function-scope declaration, or has a 6593 // C++ scope specifier, or is the object of a friend declaration, the lexical 6594 // context will be different from the semantic context. 6595 NewFD->setLexicalDeclContext(CurContext); 6596 6597 if (IsLocalExternDecl) 6598 NewFD->setLocalExternDecl(); 6599 6600 if (getLangOpts().CPlusPlus) { 6601 bool isInline = D.getDeclSpec().isInlineSpecified(); 6602 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6603 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6604 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6605 isFriend = D.getDeclSpec().isFriendSpecified(); 6606 if (isFriend && !isInline && D.isFunctionDefinition()) { 6607 // C++ [class.friend]p5 6608 // A function can be defined in a friend declaration of a 6609 // class . . . . Such a function is implicitly inline. 6610 NewFD->setImplicitlyInline(); 6611 } 6612 6613 // If this is a method defined in an __interface, and is not a constructor 6614 // or an overloaded operator, then set the pure flag (isVirtual will already 6615 // return true). 6616 if (const CXXRecordDecl *Parent = 6617 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6618 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6619 NewFD->setPure(true); 6620 } 6621 6622 SetNestedNameSpecifier(NewFD, D); 6623 isExplicitSpecialization = false; 6624 isFunctionTemplateSpecialization = false; 6625 if (D.isInvalidType()) 6626 NewFD->setInvalidDecl(); 6627 6628 // Match up the template parameter lists with the scope specifier, then 6629 // determine whether we have a template or a template specialization. 6630 bool Invalid = false; 6631 if (TemplateParameterList *TemplateParams = 6632 MatchTemplateParametersToScopeSpecifier( 6633 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6634 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6635 isExplicitSpecialization, Invalid)) { 6636 if (TemplateParams->size() > 0) { 6637 // This is a function template 6638 6639 // Check that we can declare a template here. 6640 if (CheckTemplateDeclScope(S, TemplateParams)) 6641 return 0; 6642 6643 // A destructor cannot be a template. 6644 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6645 Diag(NewFD->getLocation(), diag::err_destructor_template); 6646 return 0; 6647 } 6648 6649 // If we're adding a template to a dependent context, we may need to 6650 // rebuilding some of the types used within the template parameter list, 6651 // now that we know what the current instantiation is. 6652 if (DC->isDependentContext()) { 6653 ContextRAII SavedContext(*this, DC); 6654 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6655 Invalid = true; 6656 } 6657 6658 6659 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6660 NewFD->getLocation(), 6661 Name, TemplateParams, 6662 NewFD); 6663 FunctionTemplate->setLexicalDeclContext(CurContext); 6664 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6665 6666 // For source fidelity, store the other template param lists. 6667 if (TemplateParamLists.size() > 1) { 6668 NewFD->setTemplateParameterListsInfo(Context, 6669 TemplateParamLists.size() - 1, 6670 TemplateParamLists.data()); 6671 } 6672 } else { 6673 // This is a function template specialization. 6674 isFunctionTemplateSpecialization = true; 6675 // For source fidelity, store all the template param lists. 6676 NewFD->setTemplateParameterListsInfo(Context, 6677 TemplateParamLists.size(), 6678 TemplateParamLists.data()); 6679 6680 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6681 if (isFriend) { 6682 // We want to remove the "template<>", found here. 6683 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6684 6685 // If we remove the template<> and the name is not a 6686 // template-id, we're actually silently creating a problem: 6687 // the friend declaration will refer to an untemplated decl, 6688 // and clearly the user wants a template specialization. So 6689 // we need to insert '<>' after the name. 6690 SourceLocation InsertLoc; 6691 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6692 InsertLoc = D.getName().getSourceRange().getEnd(); 6693 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6694 } 6695 6696 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6697 << Name << RemoveRange 6698 << FixItHint::CreateRemoval(RemoveRange) 6699 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6700 } 6701 } 6702 } 6703 else { 6704 // All template param lists were matched against the scope specifier: 6705 // this is NOT (an explicit specialization of) a template. 6706 if (TemplateParamLists.size() > 0) 6707 // For source fidelity, store all the template param lists. 6708 NewFD->setTemplateParameterListsInfo(Context, 6709 TemplateParamLists.size(), 6710 TemplateParamLists.data()); 6711 } 6712 6713 if (Invalid) { 6714 NewFD->setInvalidDecl(); 6715 if (FunctionTemplate) 6716 FunctionTemplate->setInvalidDecl(); 6717 } 6718 6719 // C++ [dcl.fct.spec]p5: 6720 // The virtual specifier shall only be used in declarations of 6721 // nonstatic class member functions that appear within a 6722 // member-specification of a class declaration; see 10.3. 6723 // 6724 if (isVirtual && !NewFD->isInvalidDecl()) { 6725 if (!isVirtualOkay) { 6726 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6727 diag::err_virtual_non_function); 6728 } else if (!CurContext->isRecord()) { 6729 // 'virtual' was specified outside of the class. 6730 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6731 diag::err_virtual_out_of_class) 6732 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6733 } else if (NewFD->getDescribedFunctionTemplate()) { 6734 // C++ [temp.mem]p3: 6735 // A member function template shall not be virtual. 6736 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6737 diag::err_virtual_member_function_template) 6738 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6739 } else { 6740 // Okay: Add virtual to the method. 6741 NewFD->setVirtualAsWritten(true); 6742 } 6743 6744 if (getLangOpts().CPlusPlus1y && 6745 NewFD->getResultType()->isUndeducedType()) 6746 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6747 } 6748 6749 if (getLangOpts().CPlusPlus1y && 6750 (NewFD->isDependentContext() || 6751 (isFriend && CurContext->isDependentContext())) && 6752 NewFD->getResultType()->isUndeducedType()) { 6753 // If the function template is referenced directly (for instance, as a 6754 // member of the current instantiation), pretend it has a dependent type. 6755 // This is not really justified by the standard, but is the only sane 6756 // thing to do. 6757 // FIXME: For a friend function, we have not marked the function as being 6758 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6759 const FunctionProtoType *FPT = 6760 NewFD->getType()->castAs<FunctionProtoType>(); 6761 QualType Result = SubstAutoType(FPT->getResultType(), 6762 Context.DependentTy); 6763 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(), 6764 FPT->getExtProtoInfo())); 6765 } 6766 6767 // C++ [dcl.fct.spec]p3: 6768 // The inline specifier shall not appear on a block scope function 6769 // declaration. 6770 if (isInline && !NewFD->isInvalidDecl()) { 6771 if (CurContext->isFunctionOrMethod()) { 6772 // 'inline' is not allowed on block scope function declaration. 6773 Diag(D.getDeclSpec().getInlineSpecLoc(), 6774 diag::err_inline_declaration_block_scope) << Name 6775 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6776 } 6777 } 6778 6779 // C++ [dcl.fct.spec]p6: 6780 // The explicit specifier shall be used only in the declaration of a 6781 // constructor or conversion function within its class definition; 6782 // see 12.3.1 and 12.3.2. 6783 if (isExplicit && !NewFD->isInvalidDecl()) { 6784 if (!CurContext->isRecord()) { 6785 // 'explicit' was specified outside of the class. 6786 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6787 diag::err_explicit_out_of_class) 6788 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6789 } else if (!isa<CXXConstructorDecl>(NewFD) && 6790 !isa<CXXConversionDecl>(NewFD)) { 6791 // 'explicit' was specified on a function that wasn't a constructor 6792 // or conversion function. 6793 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6794 diag::err_explicit_non_ctor_or_conv_function) 6795 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6796 } 6797 } 6798 6799 if (isConstexpr) { 6800 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6801 // are implicitly inline. 6802 NewFD->setImplicitlyInline(); 6803 6804 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6805 // be either constructors or to return a literal type. Therefore, 6806 // destructors cannot be declared constexpr. 6807 if (isa<CXXDestructorDecl>(NewFD)) 6808 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6809 } 6810 6811 // If __module_private__ was specified, mark the function accordingly. 6812 if (D.getDeclSpec().isModulePrivateSpecified()) { 6813 if (isFunctionTemplateSpecialization) { 6814 SourceLocation ModulePrivateLoc 6815 = D.getDeclSpec().getModulePrivateSpecLoc(); 6816 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6817 << 0 6818 << FixItHint::CreateRemoval(ModulePrivateLoc); 6819 } else { 6820 NewFD->setModulePrivate(); 6821 if (FunctionTemplate) 6822 FunctionTemplate->setModulePrivate(); 6823 } 6824 } 6825 6826 if (isFriend) { 6827 if (FunctionTemplate) { 6828 FunctionTemplate->setObjectOfFriendDecl(); 6829 FunctionTemplate->setAccess(AS_public); 6830 } 6831 NewFD->setObjectOfFriendDecl(); 6832 NewFD->setAccess(AS_public); 6833 } 6834 6835 // If a function is defined as defaulted or deleted, mark it as such now. 6836 switch (D.getFunctionDefinitionKind()) { 6837 case FDK_Declaration: 6838 case FDK_Definition: 6839 break; 6840 6841 case FDK_Defaulted: 6842 NewFD->setDefaulted(); 6843 break; 6844 6845 case FDK_Deleted: 6846 NewFD->setDeletedAsWritten(); 6847 break; 6848 } 6849 6850 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6851 D.isFunctionDefinition()) { 6852 // C++ [class.mfct]p2: 6853 // A member function may be defined (8.4) in its class definition, in 6854 // which case it is an inline member function (7.1.2) 6855 NewFD->setImplicitlyInline(); 6856 } 6857 6858 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6859 !CurContext->isRecord()) { 6860 // C++ [class.static]p1: 6861 // A data or function member of a class may be declared static 6862 // in a class definition, in which case it is a static member of 6863 // the class. 6864 6865 // Complain about the 'static' specifier if it's on an out-of-line 6866 // member function definition. 6867 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6868 diag::err_static_out_of_line) 6869 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6870 } 6871 6872 // C++11 [except.spec]p15: 6873 // A deallocation function with no exception-specification is treated 6874 // as if it were specified with noexcept(true). 6875 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6876 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6877 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6878 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6879 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6880 EPI.ExceptionSpecType = EST_BasicNoexcept; 6881 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6882 FPT->getArgTypes(), EPI)); 6883 } 6884 } 6885 6886 // Filter out previous declarations that don't match the scope. 6887 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6888 isExplicitSpecialization || 6889 isFunctionTemplateSpecialization); 6890 6891 // Handle GNU asm-label extension (encoded as an attribute). 6892 if (Expr *E = (Expr*) D.getAsmLabel()) { 6893 // The parser guarantees this is a string. 6894 StringLiteral *SE = cast<StringLiteral>(E); 6895 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6896 SE->getString())); 6897 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6898 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6899 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6900 if (I != ExtnameUndeclaredIdentifiers.end()) { 6901 NewFD->addAttr(I->second); 6902 ExtnameUndeclaredIdentifiers.erase(I); 6903 } 6904 } 6905 6906 // Copy the parameter declarations from the declarator D to the function 6907 // declaration NewFD, if they are available. First scavenge them into Params. 6908 SmallVector<ParmVarDecl*, 16> Params; 6909 if (D.isFunctionDeclarator()) { 6910 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6911 6912 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6913 // function that takes no arguments, not a function that takes a 6914 // single void argument. 6915 // We let through "const void" here because Sema::GetTypeForDeclarator 6916 // already checks for that case. 6917 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6918 FTI.ArgInfo[0].Param && 6919 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6920 // Empty arg list, don't push any params. 6921 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6922 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6923 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6924 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6925 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6926 Param->setDeclContext(NewFD); 6927 Params.push_back(Param); 6928 6929 if (Param->isInvalidDecl()) 6930 NewFD->setInvalidDecl(); 6931 } 6932 } 6933 6934 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6935 // When we're declaring a function with a typedef, typeof, etc as in the 6936 // following example, we'll need to synthesize (unnamed) 6937 // parameters for use in the declaration. 6938 // 6939 // @code 6940 // typedef void fn(int); 6941 // fn f; 6942 // @endcode 6943 6944 // Synthesize a parameter for each argument type. 6945 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6946 AE = FT->arg_type_end(); AI != AE; ++AI) { 6947 ParmVarDecl *Param = 6948 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6949 Param->setScopeInfo(0, Params.size()); 6950 Params.push_back(Param); 6951 } 6952 } else { 6953 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6954 "Should not need args for typedef of non-prototype fn"); 6955 } 6956 6957 // Finally, we know we have the right number of parameters, install them. 6958 NewFD->setParams(Params); 6959 6960 // Find all anonymous symbols defined during the declaration of this function 6961 // and add to NewFD. This lets us track decls such 'enum Y' in: 6962 // 6963 // void f(enum Y {AA} x) {} 6964 // 6965 // which would otherwise incorrectly end up in the translation unit scope. 6966 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6967 DeclsInPrototypeScope.clear(); 6968 6969 if (D.getDeclSpec().isNoreturnSpecified()) 6970 NewFD->addAttr( 6971 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6972 Context)); 6973 6974 // Functions returning a variably modified type violate C99 6.7.5.2p2 6975 // because all functions have linkage. 6976 if (!NewFD->isInvalidDecl() && 6977 NewFD->getResultType()->isVariablyModifiedType()) { 6978 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6979 NewFD->setInvalidDecl(); 6980 } 6981 6982 // Handle attributes. 6983 ProcessDeclAttributes(S, NewFD, D); 6984 6985 QualType RetType = NewFD->getResultType(); 6986 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6987 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6988 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6989 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6990 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6991 // Attach the attribute to the new decl. Don't apply the attribute if it 6992 // returns an instance of the class (e.g. assignment operators). 6993 if (!MD || MD->getParent() != Ret) { 6994 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6995 Context)); 6996 } 6997 } 6998 6999 if (!getLangOpts().CPlusPlus) { 7000 // Perform semantic checking on the function declaration. 7001 bool isExplicitSpecialization=false; 7002 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7003 CheckMain(NewFD, D.getDeclSpec()); 7004 7005 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7006 CheckMSVCRTEntryPoint(NewFD); 7007 7008 if (!NewFD->isInvalidDecl()) 7009 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7010 isExplicitSpecialization)); 7011 else if (!Previous.empty()) 7012 // Make graceful recovery from an invalid redeclaration. 7013 D.setRedeclaration(true); 7014 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7015 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7016 "previous declaration set still overloaded"); 7017 } else { 7018 // C++11 [replacement.functions]p3: 7019 // The program's definitions shall not be specified as inline. 7020 // 7021 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7022 // 7023 // Suppress the diagnostic if the function is __attribute__((used)), since 7024 // that forces an external definition to be emitted. 7025 if (D.getDeclSpec().isInlineSpecified() && 7026 NewFD->isReplaceableGlobalAllocationFunction() && 7027 !NewFD->hasAttr<UsedAttr>()) 7028 Diag(D.getDeclSpec().getInlineSpecLoc(), 7029 diag::ext_operator_new_delete_declared_inline) 7030 << NewFD->getDeclName(); 7031 7032 // If the declarator is a template-id, translate the parser's template 7033 // argument list into our AST format. 7034 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7035 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7036 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7037 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7038 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7039 TemplateId->NumArgs); 7040 translateTemplateArguments(TemplateArgsPtr, 7041 TemplateArgs); 7042 7043 HasExplicitTemplateArgs = true; 7044 7045 if (NewFD->isInvalidDecl()) { 7046 HasExplicitTemplateArgs = false; 7047 } else if (FunctionTemplate) { 7048 // Function template with explicit template arguments. 7049 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7050 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7051 7052 HasExplicitTemplateArgs = false; 7053 } else if (!isFunctionTemplateSpecialization && 7054 !D.getDeclSpec().isFriendSpecified()) { 7055 // We have encountered something that the user meant to be a 7056 // specialization (because it has explicitly-specified template 7057 // arguments) but that was not introduced with a "template<>" (or had 7058 // too few of them). 7059 // FIXME: Differentiate between attempts for explicit instantiations 7060 // (starting with "template") and the rest. 7061 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7062 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7063 << FixItHint::CreateInsertion( 7064 D.getDeclSpec().getLocStart(), 7065 "template<> "); 7066 isFunctionTemplateSpecialization = true; 7067 } else { 7068 // "friend void foo<>(int);" is an implicit specialization decl. 7069 isFunctionTemplateSpecialization = true; 7070 } 7071 } else if (isFriend && isFunctionTemplateSpecialization) { 7072 // This combination is only possible in a recovery case; the user 7073 // wrote something like: 7074 // template <> friend void foo(int); 7075 // which we're recovering from as if the user had written: 7076 // friend void foo<>(int); 7077 // Go ahead and fake up a template id. 7078 HasExplicitTemplateArgs = true; 7079 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7080 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7081 } 7082 7083 // If it's a friend (and only if it's a friend), it's possible 7084 // that either the specialized function type or the specialized 7085 // template is dependent, and therefore matching will fail. In 7086 // this case, don't check the specialization yet. 7087 bool InstantiationDependent = false; 7088 if (isFunctionTemplateSpecialization && isFriend && 7089 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7090 TemplateSpecializationType::anyDependentTemplateArguments( 7091 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7092 InstantiationDependent))) { 7093 assert(HasExplicitTemplateArgs && 7094 "friend function specialization without template args"); 7095 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7096 Previous)) 7097 NewFD->setInvalidDecl(); 7098 } else if (isFunctionTemplateSpecialization) { 7099 if (CurContext->isDependentContext() && CurContext->isRecord() 7100 && !isFriend) { 7101 isDependentClassScopeExplicitSpecialization = true; 7102 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7103 diag::ext_function_specialization_in_class : 7104 diag::err_function_specialization_in_class) 7105 << NewFD->getDeclName(); 7106 } else if (CheckFunctionTemplateSpecialization(NewFD, 7107 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7108 Previous)) 7109 NewFD->setInvalidDecl(); 7110 7111 // C++ [dcl.stc]p1: 7112 // A storage-class-specifier shall not be specified in an explicit 7113 // specialization (14.7.3) 7114 FunctionTemplateSpecializationInfo *Info = 7115 NewFD->getTemplateSpecializationInfo(); 7116 if (Info && SC != SC_None) { 7117 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7118 Diag(NewFD->getLocation(), 7119 diag::err_explicit_specialization_inconsistent_storage_class) 7120 << SC 7121 << FixItHint::CreateRemoval( 7122 D.getDeclSpec().getStorageClassSpecLoc()); 7123 7124 else 7125 Diag(NewFD->getLocation(), 7126 diag::ext_explicit_specialization_storage_class) 7127 << FixItHint::CreateRemoval( 7128 D.getDeclSpec().getStorageClassSpecLoc()); 7129 } 7130 7131 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7132 if (CheckMemberSpecialization(NewFD, Previous)) 7133 NewFD->setInvalidDecl(); 7134 } 7135 7136 // Perform semantic checking on the function declaration. 7137 if (!isDependentClassScopeExplicitSpecialization) { 7138 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7139 CheckMain(NewFD, D.getDeclSpec()); 7140 7141 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7142 CheckMSVCRTEntryPoint(NewFD); 7143 7144 if (NewFD->isInvalidDecl()) { 7145 // If this is a class member, mark the class invalid immediately. 7146 // This avoids some consistency errors later. 7147 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 7148 methodDecl->getParent()->setInvalidDecl(); 7149 } else 7150 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7151 isExplicitSpecialization)); 7152 } 7153 7154 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7155 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7156 "previous declaration set still overloaded"); 7157 7158 NamedDecl *PrincipalDecl = (FunctionTemplate 7159 ? cast<NamedDecl>(FunctionTemplate) 7160 : NewFD); 7161 7162 if (isFriend && D.isRedeclaration()) { 7163 AccessSpecifier Access = AS_public; 7164 if (!NewFD->isInvalidDecl()) 7165 Access = NewFD->getPreviousDecl()->getAccess(); 7166 7167 NewFD->setAccess(Access); 7168 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7169 } 7170 7171 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7172 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7173 PrincipalDecl->setNonMemberOperator(); 7174 7175 // If we have a function template, check the template parameter 7176 // list. This will check and merge default template arguments. 7177 if (FunctionTemplate) { 7178 FunctionTemplateDecl *PrevTemplate = 7179 FunctionTemplate->getPreviousDecl(); 7180 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7181 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7182 D.getDeclSpec().isFriendSpecified() 7183 ? (D.isFunctionDefinition() 7184 ? TPC_FriendFunctionTemplateDefinition 7185 : TPC_FriendFunctionTemplate) 7186 : (D.getCXXScopeSpec().isSet() && 7187 DC && DC->isRecord() && 7188 DC->isDependentContext()) 7189 ? TPC_ClassTemplateMember 7190 : TPC_FunctionTemplate); 7191 } 7192 7193 if (NewFD->isInvalidDecl()) { 7194 // Ignore all the rest of this. 7195 } else if (!D.isRedeclaration()) { 7196 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7197 AddToScope }; 7198 // Fake up an access specifier if it's supposed to be a class member. 7199 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7200 NewFD->setAccess(AS_public); 7201 7202 // Qualified decls generally require a previous declaration. 7203 if (D.getCXXScopeSpec().isSet()) { 7204 // ...with the major exception of templated-scope or 7205 // dependent-scope friend declarations. 7206 7207 // TODO: we currently also suppress this check in dependent 7208 // contexts because (1) the parameter depth will be off when 7209 // matching friend templates and (2) we might actually be 7210 // selecting a friend based on a dependent factor. But there 7211 // are situations where these conditions don't apply and we 7212 // can actually do this check immediately. 7213 if (isFriend && 7214 (TemplateParamLists.size() || 7215 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7216 CurContext->isDependentContext())) { 7217 // ignore these 7218 } else { 7219 // The user tried to provide an out-of-line definition for a 7220 // function that is a member of a class or namespace, but there 7221 // was no such member function declared (C++ [class.mfct]p2, 7222 // C++ [namespace.memdef]p2). For example: 7223 // 7224 // class X { 7225 // void f() const; 7226 // }; 7227 // 7228 // void X::f() { } // ill-formed 7229 // 7230 // Complain about this problem, and attempt to suggest close 7231 // matches (e.g., those that differ only in cv-qualifiers and 7232 // whether the parameter types are references). 7233 7234 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7235 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7236 AddToScope = ExtraArgs.AddToScope; 7237 return Result; 7238 } 7239 } 7240 7241 // Unqualified local friend declarations are required to resolve 7242 // to something. 7243 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7244 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7245 *this, Previous, NewFD, ExtraArgs, true, S)) { 7246 AddToScope = ExtraArgs.AddToScope; 7247 return Result; 7248 } 7249 } 7250 7251 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 7252 !isFriend && !isFunctionTemplateSpecialization && 7253 !isExplicitSpecialization) { 7254 // An out-of-line member function declaration must also be a 7255 // definition (C++ [dcl.meaning]p1). 7256 // Note that this is not the case for explicit specializations of 7257 // function templates or member functions of class templates, per 7258 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7259 // extension for compatibility with old SWIG code which likes to 7260 // generate them. 7261 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7262 << D.getCXXScopeSpec().getRange(); 7263 } 7264 } 7265 7266 ProcessPragmaWeak(S, NewFD); 7267 checkAttributesAfterMerging(*this, *NewFD); 7268 7269 AddKnownFunctionAttributes(NewFD); 7270 7271 if (NewFD->hasAttr<OverloadableAttr>() && 7272 !NewFD->getType()->getAs<FunctionProtoType>()) { 7273 Diag(NewFD->getLocation(), 7274 diag::err_attribute_overloadable_no_prototype) 7275 << NewFD; 7276 7277 // Turn this into a variadic function with no parameters. 7278 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7279 FunctionProtoType::ExtProtoInfo EPI( 7280 Context.getDefaultCallingConvention(true, false)); 7281 EPI.Variadic = true; 7282 EPI.ExtInfo = FT->getExtInfo(); 7283 7284 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI); 7285 NewFD->setType(R); 7286 } 7287 7288 // If there's a #pragma GCC visibility in scope, and this isn't a class 7289 // member, set the visibility of this function. 7290 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7291 AddPushedVisibilityAttribute(NewFD); 7292 7293 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7294 // marking the function. 7295 AddCFAuditedAttribute(NewFD); 7296 7297 // If this is the first declaration of an extern C variable, update 7298 // the map of such variables. 7299 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7300 isIncompleteDeclExternC(*this, NewFD)) 7301 RegisterLocallyScopedExternCDecl(NewFD, S); 7302 7303 // Set this FunctionDecl's range up to the right paren. 7304 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7305 7306 if (getLangOpts().CPlusPlus) { 7307 if (FunctionTemplate) { 7308 if (NewFD->isInvalidDecl()) 7309 FunctionTemplate->setInvalidDecl(); 7310 return FunctionTemplate; 7311 } 7312 } 7313 7314 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7315 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7316 if ((getLangOpts().OpenCLVersion >= 120) 7317 && (SC == SC_Static)) { 7318 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7319 D.setInvalidType(); 7320 } 7321 7322 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7323 if (!NewFD->getResultType()->isVoidType()) { 7324 Diag(D.getIdentifierLoc(), 7325 diag::err_expected_kernel_void_return_type); 7326 D.setInvalidType(); 7327 } 7328 7329 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7330 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7331 PE = NewFD->param_end(); PI != PE; ++PI) { 7332 ParmVarDecl *Param = *PI; 7333 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7334 } 7335 } 7336 7337 MarkUnusedFileScopedDecl(NewFD); 7338 7339 if (getLangOpts().CUDA) 7340 if (IdentifierInfo *II = NewFD->getIdentifier()) 7341 if (!NewFD->isInvalidDecl() && 7342 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7343 if (II->isStr("cudaConfigureCall")) { 7344 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 7345 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7346 7347 Context.setcudaConfigureCallDecl(NewFD); 7348 } 7349 } 7350 7351 // Here we have an function template explicit specialization at class scope. 7352 // The actually specialization will be postponed to template instatiation 7353 // time via the ClassScopeFunctionSpecializationDecl node. 7354 if (isDependentClassScopeExplicitSpecialization) { 7355 ClassScopeFunctionSpecializationDecl *NewSpec = 7356 ClassScopeFunctionSpecializationDecl::Create( 7357 Context, CurContext, SourceLocation(), 7358 cast<CXXMethodDecl>(NewFD), 7359 HasExplicitTemplateArgs, TemplateArgs); 7360 CurContext->addDecl(NewSpec); 7361 AddToScope = false; 7362 } 7363 7364 return NewFD; 7365} 7366 7367/// \brief Perform semantic checking of a new function declaration. 7368/// 7369/// Performs semantic analysis of the new function declaration 7370/// NewFD. This routine performs all semantic checking that does not 7371/// require the actual declarator involved in the declaration, and is 7372/// used both for the declaration of functions as they are parsed 7373/// (called via ActOnDeclarator) and for the declaration of functions 7374/// that have been instantiated via C++ template instantiation (called 7375/// via InstantiateDecl). 7376/// 7377/// \param IsExplicitSpecialization whether this new function declaration is 7378/// an explicit specialization of the previous declaration. 7379/// 7380/// This sets NewFD->isInvalidDecl() to true if there was an error. 7381/// 7382/// \returns true if the function declaration is a redeclaration. 7383bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7384 LookupResult &Previous, 7385 bool IsExplicitSpecialization) { 7386 assert(!NewFD->getResultType()->isVariablyModifiedType() 7387 && "Variably modified return types are not handled here"); 7388 7389 // Determine whether the type of this function should be merged with 7390 // a previous visible declaration. This never happens for functions in C++, 7391 // and always happens in C if the previous declaration was visible. 7392 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7393 !Previous.isShadowed(); 7394 7395 // Filter out any non-conflicting previous declarations. 7396 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7397 7398 bool Redeclaration = false; 7399 NamedDecl *OldDecl = 0; 7400 7401 // Merge or overload the declaration with an existing declaration of 7402 // the same name, if appropriate. 7403 if (!Previous.empty()) { 7404 // Determine whether NewFD is an overload of PrevDecl or 7405 // a declaration that requires merging. If it's an overload, 7406 // there's no more work to do here; we'll just add the new 7407 // function to the scope. 7408 if (!AllowOverloadingOfFunction(Previous, Context)) { 7409 NamedDecl *Candidate = Previous.getFoundDecl(); 7410 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7411 Redeclaration = true; 7412 OldDecl = Candidate; 7413 } 7414 } else { 7415 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7416 /*NewIsUsingDecl*/ false)) { 7417 case Ovl_Match: 7418 Redeclaration = true; 7419 break; 7420 7421 case Ovl_NonFunction: 7422 Redeclaration = true; 7423 break; 7424 7425 case Ovl_Overload: 7426 Redeclaration = false; 7427 break; 7428 } 7429 7430 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7431 // If a function name is overloadable in C, then every function 7432 // with that name must be marked "overloadable". 7433 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7434 << Redeclaration << NewFD; 7435 NamedDecl *OverloadedDecl = 0; 7436 if (Redeclaration) 7437 OverloadedDecl = OldDecl; 7438 else if (!Previous.empty()) 7439 OverloadedDecl = Previous.getRepresentativeDecl(); 7440 if (OverloadedDecl) 7441 Diag(OverloadedDecl->getLocation(), 7442 diag::note_attribute_overloadable_prev_overload); 7443 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7444 Context)); 7445 } 7446 } 7447 } 7448 7449 // Check for a previous extern "C" declaration with this name. 7450 if (!Redeclaration && 7451 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7452 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7453 if (!Previous.empty()) { 7454 // This is an extern "C" declaration with the same name as a previous 7455 // declaration, and thus redeclares that entity... 7456 Redeclaration = true; 7457 OldDecl = Previous.getFoundDecl(); 7458 MergeTypeWithPrevious = false; 7459 7460 // ... except in the presence of __attribute__((overloadable)). 7461 if (OldDecl->hasAttr<OverloadableAttr>()) { 7462 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7463 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7464 << Redeclaration << NewFD; 7465 Diag(Previous.getFoundDecl()->getLocation(), 7466 diag::note_attribute_overloadable_prev_overload); 7467 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7468 Context)); 7469 } 7470 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7471 Redeclaration = false; 7472 OldDecl = 0; 7473 } 7474 } 7475 } 7476 } 7477 7478 // C++11 [dcl.constexpr]p8: 7479 // A constexpr specifier for a non-static member function that is not 7480 // a constructor declares that member function to be const. 7481 // 7482 // This needs to be delayed until we know whether this is an out-of-line 7483 // definition of a static member function. 7484 // 7485 // This rule is not present in C++1y, so we produce a backwards 7486 // compatibility warning whenever it happens in C++11. 7487 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7488 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7489 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7490 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7491 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 7492 if (FunctionTemplateDecl *OldTD = 7493 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 7494 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 7495 if (!OldMD || !OldMD->isStatic()) { 7496 const FunctionProtoType *FPT = 7497 MD->getType()->castAs<FunctionProtoType>(); 7498 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7499 EPI.TypeQuals |= Qualifiers::Const; 7500 MD->setType(Context.getFunctionType(FPT->getResultType(), 7501 FPT->getArgTypes(), EPI)); 7502 7503 // Warn that we did this, if we're not performing template instantiation. 7504 // In that case, we'll have warned already when the template was defined. 7505 if (ActiveTemplateInstantiations.empty()) { 7506 SourceLocation AddConstLoc; 7507 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7508 .IgnoreParens().getAs<FunctionTypeLoc>()) 7509 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7510 7511 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7512 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7513 } 7514 } 7515 } 7516 7517 if (Redeclaration) { 7518 // NewFD and OldDecl represent declarations that need to be 7519 // merged. 7520 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7521 NewFD->setInvalidDecl(); 7522 return Redeclaration; 7523 } 7524 7525 Previous.clear(); 7526 Previous.addDecl(OldDecl); 7527 7528 if (FunctionTemplateDecl *OldTemplateDecl 7529 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7530 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7531 FunctionTemplateDecl *NewTemplateDecl 7532 = NewFD->getDescribedFunctionTemplate(); 7533 assert(NewTemplateDecl && "Template/non-template mismatch"); 7534 if (CXXMethodDecl *Method 7535 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7536 Method->setAccess(OldTemplateDecl->getAccess()); 7537 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7538 } 7539 7540 // If this is an explicit specialization of a member that is a function 7541 // template, mark it as a member specialization. 7542 if (IsExplicitSpecialization && 7543 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7544 NewTemplateDecl->setMemberSpecialization(); 7545 assert(OldTemplateDecl->isMemberSpecialization()); 7546 } 7547 7548 } else { 7549 // This needs to happen first so that 'inline' propagates. 7550 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7551 7552 if (isa<CXXMethodDecl>(NewFD)) { 7553 // A valid redeclaration of a C++ method must be out-of-line, 7554 // but (unfortunately) it's not necessarily a definition 7555 // because of templates, which means that the previous 7556 // declaration is not necessarily from the class definition. 7557 7558 // For just setting the access, that doesn't matter. 7559 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7560 NewFD->setAccess(oldMethod->getAccess()); 7561 7562 // Update the key-function state if necessary for this ABI. 7563 if (NewFD->isInlined() && 7564 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7565 // setNonKeyFunction needs to work with the original 7566 // declaration from the class definition, and isVirtual() is 7567 // just faster in that case, so map back to that now. 7568 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7569 if (oldMethod->isVirtual()) { 7570 Context.setNonKeyFunction(oldMethod); 7571 } 7572 } 7573 } 7574 } 7575 } 7576 7577 // Semantic checking for this function declaration (in isolation). 7578 if (getLangOpts().CPlusPlus) { 7579 // C++-specific checks. 7580 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7581 CheckConstructor(Constructor); 7582 } else if (CXXDestructorDecl *Destructor = 7583 dyn_cast<CXXDestructorDecl>(NewFD)) { 7584 CXXRecordDecl *Record = Destructor->getParent(); 7585 QualType ClassType = Context.getTypeDeclType(Record); 7586 7587 // FIXME: Shouldn't we be able to perform this check even when the class 7588 // type is dependent? Both gcc and edg can handle that. 7589 if (!ClassType->isDependentType()) { 7590 DeclarationName Name 7591 = Context.DeclarationNames.getCXXDestructorName( 7592 Context.getCanonicalType(ClassType)); 7593 if (NewFD->getDeclName() != Name) { 7594 Diag(NewFD->getLocation(), diag::err_destructor_name); 7595 NewFD->setInvalidDecl(); 7596 return Redeclaration; 7597 } 7598 } 7599 } else if (CXXConversionDecl *Conversion 7600 = dyn_cast<CXXConversionDecl>(NewFD)) { 7601 ActOnConversionDeclarator(Conversion); 7602 } 7603 7604 // Find any virtual functions that this function overrides. 7605 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7606 if (!Method->isFunctionTemplateSpecialization() && 7607 !Method->getDescribedFunctionTemplate() && 7608 Method->isCanonicalDecl()) { 7609 if (AddOverriddenMethods(Method->getParent(), Method)) { 7610 // If the function was marked as "static", we have a problem. 7611 if (NewFD->getStorageClass() == SC_Static) { 7612 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7613 } 7614 } 7615 } 7616 7617 if (Method->isStatic()) 7618 checkThisInStaticMemberFunctionType(Method); 7619 } 7620 7621 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7622 if (NewFD->isOverloadedOperator() && 7623 CheckOverloadedOperatorDeclaration(NewFD)) { 7624 NewFD->setInvalidDecl(); 7625 return Redeclaration; 7626 } 7627 7628 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7629 if (NewFD->getLiteralIdentifier() && 7630 CheckLiteralOperatorDeclaration(NewFD)) { 7631 NewFD->setInvalidDecl(); 7632 return Redeclaration; 7633 } 7634 7635 // In C++, check default arguments now that we have merged decls. Unless 7636 // the lexical context is the class, because in this case this is done 7637 // during delayed parsing anyway. 7638 if (!CurContext->isRecord()) 7639 CheckCXXDefaultArguments(NewFD); 7640 7641 // If this function declares a builtin function, check the type of this 7642 // declaration against the expected type for the builtin. 7643 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7644 ASTContext::GetBuiltinTypeError Error; 7645 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7646 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7647 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7648 // The type of this function differs from the type of the builtin, 7649 // so forget about the builtin entirely. 7650 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7651 } 7652 } 7653 7654 // If this function is declared as being extern "C", then check to see if 7655 // the function returns a UDT (class, struct, or union type) that is not C 7656 // compatible, and if it does, warn the user. 7657 // But, issue any diagnostic on the first declaration only. 7658 if (NewFD->isExternC() && Previous.empty()) { 7659 QualType R = NewFD->getResultType(); 7660 if (R->isIncompleteType() && !R->isVoidType()) 7661 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7662 << NewFD << R; 7663 else if (!R.isPODType(Context) && !R->isVoidType() && 7664 !R->isObjCObjectPointerType()) 7665 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7666 } 7667 } 7668 return Redeclaration; 7669} 7670 7671static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7672 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7673 if (!TSI) 7674 return SourceRange(); 7675 7676 TypeLoc TL = TSI->getTypeLoc(); 7677 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7678 if (!FunctionTL) 7679 return SourceRange(); 7680 7681 TypeLoc ResultTL = FunctionTL.getResultLoc(); 7682 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7683 return ResultTL.getSourceRange(); 7684 7685 return SourceRange(); 7686} 7687 7688void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7689 // C++11 [basic.start.main]p3: A program that declares main to be inline, 7690 // static or constexpr is ill-formed. 7691 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7692 // appear in a declaration of main. 7693 // static main is not an error under C99, but we should warn about it. 7694 // We accept _Noreturn main as an extension. 7695 if (FD->getStorageClass() == SC_Static) 7696 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7697 ? diag::err_static_main : diag::warn_static_main) 7698 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7699 if (FD->isInlineSpecified()) 7700 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7701 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7702 if (DS.isNoreturnSpecified()) { 7703 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7704 SourceRange NoreturnRange(NoreturnLoc, 7705 PP.getLocForEndOfToken(NoreturnLoc)); 7706 Diag(NoreturnLoc, diag::ext_noreturn_main); 7707 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7708 << FixItHint::CreateRemoval(NoreturnRange); 7709 } 7710 if (FD->isConstexpr()) { 7711 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7712 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7713 FD->setConstexpr(false); 7714 } 7715 7716 if (getLangOpts().OpenCL) { 7717 Diag(FD->getLocation(), diag::err_opencl_no_main) 7718 << FD->hasAttr<OpenCLKernelAttr>(); 7719 FD->setInvalidDecl(); 7720 return; 7721 } 7722 7723 QualType T = FD->getType(); 7724 assert(T->isFunctionType() && "function decl is not of function type"); 7725 const FunctionType* FT = T->castAs<FunctionType>(); 7726 7727 // All the standards say that main() should should return 'int'. 7728 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 7729 // In C and C++, main magically returns 0 if you fall off the end; 7730 // set the flag which tells us that. 7731 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7732 FD->setHasImplicitReturnZero(true); 7733 7734 // In C with GNU extensions we allow main() to have non-integer return 7735 // type, but we should warn about the extension, and we disable the 7736 // implicit-return-zero rule. 7737 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7738 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7739 7740 SourceRange ResultRange = getResultSourceRange(FD); 7741 if (ResultRange.isValid()) 7742 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7743 << FixItHint::CreateReplacement(ResultRange, "int"); 7744 7745 // Otherwise, this is just a flat-out error. 7746 } else { 7747 SourceRange ResultRange = getResultSourceRange(FD); 7748 if (ResultRange.isValid()) 7749 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7750 << FixItHint::CreateReplacement(ResultRange, "int"); 7751 else 7752 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7753 7754 FD->setInvalidDecl(true); 7755 } 7756 7757 // Treat protoless main() as nullary. 7758 if (isa<FunctionNoProtoType>(FT)) return; 7759 7760 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7761 unsigned nparams = FTP->getNumArgs(); 7762 assert(FD->getNumParams() == nparams); 7763 7764 bool HasExtraParameters = (nparams > 3); 7765 7766 // Darwin passes an undocumented fourth argument of type char**. If 7767 // other platforms start sprouting these, the logic below will start 7768 // getting shifty. 7769 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7770 HasExtraParameters = false; 7771 7772 if (HasExtraParameters) { 7773 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7774 FD->setInvalidDecl(true); 7775 nparams = 3; 7776 } 7777 7778 // FIXME: a lot of the following diagnostics would be improved 7779 // if we had some location information about types. 7780 7781 QualType CharPP = 7782 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7783 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7784 7785 for (unsigned i = 0; i < nparams; ++i) { 7786 QualType AT = FTP->getArgType(i); 7787 7788 bool mismatch = true; 7789 7790 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7791 mismatch = false; 7792 else if (Expected[i] == CharPP) { 7793 // As an extension, the following forms are okay: 7794 // char const ** 7795 // char const * const * 7796 // char * const * 7797 7798 QualifierCollector qs; 7799 const PointerType* PT; 7800 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7801 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7802 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7803 Context.CharTy)) { 7804 qs.removeConst(); 7805 mismatch = !qs.empty(); 7806 } 7807 } 7808 7809 if (mismatch) { 7810 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7811 // TODO: suggest replacing given type with expected type 7812 FD->setInvalidDecl(true); 7813 } 7814 } 7815 7816 if (nparams == 1 && !FD->isInvalidDecl()) { 7817 Diag(FD->getLocation(), diag::warn_main_one_arg); 7818 } 7819 7820 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7821 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7822 FD->setInvalidDecl(); 7823 } 7824} 7825 7826void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7827 QualType T = FD->getType(); 7828 assert(T->isFunctionType() && "function decl is not of function type"); 7829 const FunctionType *FT = T->castAs<FunctionType>(); 7830 7831 // Set an implicit return of 'zero' if the function can return some integral, 7832 // enumeration, pointer or nullptr type. 7833 if (FT->getResultType()->isIntegralOrEnumerationType() || 7834 FT->getResultType()->isAnyPointerType() || 7835 FT->getResultType()->isNullPtrType()) 7836 // DllMain is exempt because a return value of zero means it failed. 7837 if (FD->getName() != "DllMain") 7838 FD->setHasImplicitReturnZero(true); 7839 7840 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7841 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7842 FD->setInvalidDecl(); 7843 } 7844} 7845 7846bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7847 // FIXME: Need strict checking. In C89, we need to check for 7848 // any assignment, increment, decrement, function-calls, or 7849 // commas outside of a sizeof. In C99, it's the same list, 7850 // except that the aforementioned are allowed in unevaluated 7851 // expressions. Everything else falls under the 7852 // "may accept other forms of constant expressions" exception. 7853 // (We never end up here for C++, so the constant expression 7854 // rules there don't matter.) 7855 if (Init->isConstantInitializer(Context, false)) 7856 return false; 7857 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7858 << Init->getSourceRange(); 7859 return true; 7860} 7861 7862namespace { 7863 // Visits an initialization expression to see if OrigDecl is evaluated in 7864 // its own initialization and throws a warning if it does. 7865 class SelfReferenceChecker 7866 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7867 Sema &S; 7868 Decl *OrigDecl; 7869 bool isRecordType; 7870 bool isPODType; 7871 bool isReferenceType; 7872 7873 public: 7874 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7875 7876 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7877 S(S), OrigDecl(OrigDecl) { 7878 isPODType = false; 7879 isRecordType = false; 7880 isReferenceType = false; 7881 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7882 isPODType = VD->getType().isPODType(S.Context); 7883 isRecordType = VD->getType()->isRecordType(); 7884 isReferenceType = VD->getType()->isReferenceType(); 7885 } 7886 } 7887 7888 // For most expressions, the cast is directly above the DeclRefExpr. 7889 // For conditional operators, the cast can be outside the conditional 7890 // operator if both expressions are DeclRefExpr's. 7891 void HandleValue(Expr *E) { 7892 if (isReferenceType) 7893 return; 7894 E = E->IgnoreParenImpCasts(); 7895 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7896 HandleDeclRefExpr(DRE); 7897 return; 7898 } 7899 7900 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7901 HandleValue(CO->getTrueExpr()); 7902 HandleValue(CO->getFalseExpr()); 7903 return; 7904 } 7905 7906 if (isa<MemberExpr>(E)) { 7907 Expr *Base = E->IgnoreParenImpCasts(); 7908 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7909 // Check for static member variables and don't warn on them. 7910 if (!isa<FieldDecl>(ME->getMemberDecl())) 7911 return; 7912 Base = ME->getBase()->IgnoreParenImpCasts(); 7913 } 7914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7915 HandleDeclRefExpr(DRE); 7916 return; 7917 } 7918 } 7919 7920 // Reference types are handled here since all uses of references are 7921 // bad, not just r-value uses. 7922 void VisitDeclRefExpr(DeclRefExpr *E) { 7923 if (isReferenceType) 7924 HandleDeclRefExpr(E); 7925 } 7926 7927 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7928 if (E->getCastKind() == CK_LValueToRValue || 7929 (isRecordType && E->getCastKind() == CK_NoOp)) 7930 HandleValue(E->getSubExpr()); 7931 7932 Inherited::VisitImplicitCastExpr(E); 7933 } 7934 7935 void VisitMemberExpr(MemberExpr *E) { 7936 // Don't warn on arrays since they can be treated as pointers. 7937 if (E->getType()->canDecayToPointerType()) return; 7938 7939 // Warn when a non-static method call is followed by non-static member 7940 // field accesses, which is followed by a DeclRefExpr. 7941 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7942 bool Warn = (MD && !MD->isStatic()); 7943 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7944 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7945 if (!isa<FieldDecl>(ME->getMemberDecl())) 7946 Warn = false; 7947 Base = ME->getBase()->IgnoreParenImpCasts(); 7948 } 7949 7950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7951 if (Warn) 7952 HandleDeclRefExpr(DRE); 7953 return; 7954 } 7955 7956 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7957 // Visit that expression. 7958 Visit(Base); 7959 } 7960 7961 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7962 if (E->getNumArgs() > 0) 7963 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7964 HandleDeclRefExpr(DRE); 7965 7966 Inherited::VisitCXXOperatorCallExpr(E); 7967 } 7968 7969 void VisitUnaryOperator(UnaryOperator *E) { 7970 // For POD record types, addresses of its own members are well-defined. 7971 if (E->getOpcode() == UO_AddrOf && isRecordType && 7972 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7973 if (!isPODType) 7974 HandleValue(E->getSubExpr()); 7975 return; 7976 } 7977 Inherited::VisitUnaryOperator(E); 7978 } 7979 7980 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7981 7982 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7983 Decl* ReferenceDecl = DRE->getDecl(); 7984 if (OrigDecl != ReferenceDecl) return; 7985 unsigned diag; 7986 if (isReferenceType) { 7987 diag = diag::warn_uninit_self_reference_in_reference_init; 7988 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7989 diag = diag::warn_static_self_reference_in_init; 7990 } else { 7991 diag = diag::warn_uninit_self_reference_in_init; 7992 } 7993 7994 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7995 S.PDiag(diag) 7996 << DRE->getNameInfo().getName() 7997 << OrigDecl->getLocation() 7998 << DRE->getSourceRange()); 7999 } 8000 }; 8001 8002 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8003 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8004 bool DirectInit) { 8005 // Parameters arguments are occassionially constructed with itself, 8006 // for instance, in recursive functions. Skip them. 8007 if (isa<ParmVarDecl>(OrigDecl)) 8008 return; 8009 8010 E = E->IgnoreParens(); 8011 8012 // Skip checking T a = a where T is not a record or reference type. 8013 // Doing so is a way to silence uninitialized warnings. 8014 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8015 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8016 if (ICE->getCastKind() == CK_LValueToRValue) 8017 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8018 if (DRE->getDecl() == OrigDecl) 8019 return; 8020 8021 SelfReferenceChecker(S, OrigDecl).Visit(E); 8022 } 8023} 8024 8025/// AddInitializerToDecl - Adds the initializer Init to the 8026/// declaration dcl. If DirectInit is true, this is C++ direct 8027/// initialization rather than copy initialization. 8028void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8029 bool DirectInit, bool TypeMayContainAuto) { 8030 // If there is no declaration, there was an error parsing it. Just ignore 8031 // the initializer. 8032 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8033 return; 8034 8035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8036 // With declarators parsed the way they are, the parser cannot 8037 // distinguish between a normal initializer and a pure-specifier. 8038 // Thus this grotesque test. 8039 IntegerLiteral *IL; 8040 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8041 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8042 CheckPureMethod(Method, Init->getSourceRange()); 8043 else { 8044 Diag(Method->getLocation(), diag::err_member_function_initialization) 8045 << Method->getDeclName() << Init->getSourceRange(); 8046 Method->setInvalidDecl(); 8047 } 8048 return; 8049 } 8050 8051 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8052 if (!VDecl) { 8053 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8054 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8055 RealDecl->setInvalidDecl(); 8056 return; 8057 } 8058 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8059 8060 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8061 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8062 Expr *DeduceInit = Init; 8063 // Initializer could be a C++ direct-initializer. Deduction only works if it 8064 // contains exactly one expression. 8065 if (CXXDirectInit) { 8066 if (CXXDirectInit->getNumExprs() == 0) { 8067 // It isn't possible to write this directly, but it is possible to 8068 // end up in this situation with "auto x(some_pack...);" 8069 Diag(CXXDirectInit->getLocStart(), 8070 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8071 : diag::err_auto_var_init_no_expression) 8072 << VDecl->getDeclName() << VDecl->getType() 8073 << VDecl->getSourceRange(); 8074 RealDecl->setInvalidDecl(); 8075 return; 8076 } else if (CXXDirectInit->getNumExprs() > 1) { 8077 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8078 VDecl->isInitCapture() 8079 ? diag::err_init_capture_multiple_expressions 8080 : diag::err_auto_var_init_multiple_expressions) 8081 << VDecl->getDeclName() << VDecl->getType() 8082 << VDecl->getSourceRange(); 8083 RealDecl->setInvalidDecl(); 8084 return; 8085 } else { 8086 DeduceInit = CXXDirectInit->getExpr(0); 8087 } 8088 } 8089 8090 // Expressions default to 'id' when we're in a debugger. 8091 bool DefaultedToAuto = false; 8092 if (getLangOpts().DebuggerCastResultToId && 8093 Init->getType() == Context.UnknownAnyTy) { 8094 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8095 if (Result.isInvalid()) { 8096 VDecl->setInvalidDecl(); 8097 return; 8098 } 8099 Init = Result.take(); 8100 DefaultedToAuto = true; 8101 } 8102 8103 QualType DeducedType; 8104 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8105 DAR_Failed) 8106 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8107 if (DeducedType.isNull()) { 8108 RealDecl->setInvalidDecl(); 8109 return; 8110 } 8111 VDecl->setType(DeducedType); 8112 assert(VDecl->isLinkageValid()); 8113 8114 // In ARC, infer lifetime. 8115 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8116 VDecl->setInvalidDecl(); 8117 8118 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8119 // 'id' instead of a specific object type prevents most of our usual checks. 8120 // We only want to warn outside of template instantiations, though: 8121 // inside a template, the 'id' could have come from a parameter. 8122 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8123 DeducedType->isObjCIdType()) { 8124 SourceLocation Loc = 8125 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8126 Diag(Loc, diag::warn_auto_var_is_id) 8127 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8128 } 8129 8130 // If this is a redeclaration, check that the type we just deduced matches 8131 // the previously declared type. 8132 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8133 // We never need to merge the type, because we cannot form an incomplete 8134 // array of auto, nor deduce such a type. 8135 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8136 } 8137 8138 // Check the deduced type is valid for a variable declaration. 8139 CheckVariableDeclarationType(VDecl); 8140 if (VDecl->isInvalidDecl()) 8141 return; 8142 } 8143 8144 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8145 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8146 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8147 VDecl->setInvalidDecl(); 8148 return; 8149 } 8150 8151 if (!VDecl->getType()->isDependentType()) { 8152 // A definition must end up with a complete type, which means it must be 8153 // complete with the restriction that an array type might be completed by 8154 // the initializer; note that later code assumes this restriction. 8155 QualType BaseDeclType = VDecl->getType(); 8156 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8157 BaseDeclType = Array->getElementType(); 8158 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8159 diag::err_typecheck_decl_incomplete_type)) { 8160 RealDecl->setInvalidDecl(); 8161 return; 8162 } 8163 8164 // The variable can not have an abstract class type. 8165 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8166 diag::err_abstract_type_in_decl, 8167 AbstractVariableType)) 8168 VDecl->setInvalidDecl(); 8169 } 8170 8171 const VarDecl *Def; 8172 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8173 Diag(VDecl->getLocation(), diag::err_redefinition) 8174 << VDecl->getDeclName(); 8175 Diag(Def->getLocation(), diag::note_previous_definition); 8176 VDecl->setInvalidDecl(); 8177 return; 8178 } 8179 8180 const VarDecl* PrevInit = 0; 8181 if (getLangOpts().CPlusPlus) { 8182 // C++ [class.static.data]p4 8183 // If a static data member is of const integral or const 8184 // enumeration type, its declaration in the class definition can 8185 // specify a constant-initializer which shall be an integral 8186 // constant expression (5.19). In that case, the member can appear 8187 // in integral constant expressions. The member shall still be 8188 // defined in a namespace scope if it is used in the program and the 8189 // namespace scope definition shall not contain an initializer. 8190 // 8191 // We already performed a redefinition check above, but for static 8192 // data members we also need to check whether there was an in-class 8193 // declaration with an initializer. 8194 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8195 Diag(VDecl->getLocation(), diag::err_redefinition) 8196 << VDecl->getDeclName(); 8197 Diag(PrevInit->getLocation(), diag::note_previous_definition); 8198 return; 8199 } 8200 8201 if (VDecl->hasLocalStorage()) 8202 getCurFunction()->setHasBranchProtectedScope(); 8203 8204 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8205 VDecl->setInvalidDecl(); 8206 return; 8207 } 8208 } 8209 8210 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8211 // a kernel function cannot be initialized." 8212 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8213 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8214 VDecl->setInvalidDecl(); 8215 return; 8216 } 8217 8218 // Get the decls type and save a reference for later, since 8219 // CheckInitializerTypes may change it. 8220 QualType DclT = VDecl->getType(), SavT = DclT; 8221 8222 // Expressions default to 'id' when we're in a debugger 8223 // and we are assigning it to a variable of Objective-C pointer type. 8224 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8225 Init->getType() == Context.UnknownAnyTy) { 8226 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8227 if (Result.isInvalid()) { 8228 VDecl->setInvalidDecl(); 8229 return; 8230 } 8231 Init = Result.take(); 8232 } 8233 8234 // Perform the initialization. 8235 if (!VDecl->isInvalidDecl()) { 8236 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8237 InitializationKind Kind 8238 = DirectInit ? 8239 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8240 Init->getLocStart(), 8241 Init->getLocEnd()) 8242 : InitializationKind::CreateDirectList( 8243 VDecl->getLocation()) 8244 : InitializationKind::CreateCopy(VDecl->getLocation(), 8245 Init->getLocStart()); 8246 8247 MultiExprArg Args = Init; 8248 if (CXXDirectInit) 8249 Args = MultiExprArg(CXXDirectInit->getExprs(), 8250 CXXDirectInit->getNumExprs()); 8251 8252 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8253 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8254 if (Result.isInvalid()) { 8255 VDecl->setInvalidDecl(); 8256 return; 8257 } 8258 8259 Init = Result.takeAs<Expr>(); 8260 } 8261 8262 // Check for self-references within variable initializers. 8263 // Variables declared within a function/method body (except for references) 8264 // are handled by a dataflow analysis. 8265 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8266 VDecl->getType()->isReferenceType()) { 8267 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8268 } 8269 8270 // If the type changed, it means we had an incomplete type that was 8271 // completed by the initializer. For example: 8272 // int ary[] = { 1, 3, 5 }; 8273 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8274 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8275 VDecl->setType(DclT); 8276 8277 if (!VDecl->isInvalidDecl()) { 8278 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8279 8280 if (VDecl->hasAttr<BlocksAttr>()) 8281 checkRetainCycles(VDecl, Init); 8282 8283 // It is safe to assign a weak reference into a strong variable. 8284 // Although this code can still have problems: 8285 // id x = self.weakProp; 8286 // id y = self.weakProp; 8287 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8288 // paths through the function. This should be revisited if 8289 // -Wrepeated-use-of-weak is made flow-sensitive. 8290 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8291 DiagnosticsEngine::Level Level = 8292 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8293 Init->getLocStart()); 8294 if (Level != DiagnosticsEngine::Ignored) 8295 getCurFunction()->markSafeWeakUse(Init); 8296 } 8297 } 8298 8299 // The initialization is usually a full-expression. 8300 // 8301 // FIXME: If this is a braced initialization of an aggregate, it is not 8302 // an expression, and each individual field initializer is a separate 8303 // full-expression. For instance, in: 8304 // 8305 // struct Temp { ~Temp(); }; 8306 // struct S { S(Temp); }; 8307 // struct T { S a, b; } t = { Temp(), Temp() } 8308 // 8309 // we should destroy the first Temp before constructing the second. 8310 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8311 false, 8312 VDecl->isConstexpr()); 8313 if (Result.isInvalid()) { 8314 VDecl->setInvalidDecl(); 8315 return; 8316 } 8317 Init = Result.take(); 8318 8319 // Attach the initializer to the decl. 8320 VDecl->setInit(Init); 8321 8322 if (VDecl->isLocalVarDecl()) { 8323 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8324 // static storage duration shall be constant expressions or string literals. 8325 // C++ does not have this restriction. 8326 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8327 if (VDecl->getStorageClass() == SC_Static) 8328 CheckForConstantInitializer(Init, DclT); 8329 // C89 is stricter than C99 for non-static aggregate types. 8330 // C89 6.5.7p3: All the expressions [...] in an initializer list 8331 // for an object that has aggregate or union type shall be 8332 // constant expressions. 8333 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8334 isa<InitListExpr>(Init) && 8335 !Init->isConstantInitializer(Context, false)) 8336 Diag(Init->getExprLoc(), 8337 diag::ext_aggregate_init_not_constant) 8338 << Init->getSourceRange(); 8339 } 8340 } else if (VDecl->isStaticDataMember() && 8341 VDecl->getLexicalDeclContext()->isRecord()) { 8342 // This is an in-class initialization for a static data member, e.g., 8343 // 8344 // struct S { 8345 // static const int value = 17; 8346 // }; 8347 8348 // C++ [class.mem]p4: 8349 // A member-declarator can contain a constant-initializer only 8350 // if it declares a static member (9.4) of const integral or 8351 // const enumeration type, see 9.4.2. 8352 // 8353 // C++11 [class.static.data]p3: 8354 // If a non-volatile const static data member is of integral or 8355 // enumeration type, its declaration in the class definition can 8356 // specify a brace-or-equal-initializer in which every initalizer-clause 8357 // that is an assignment-expression is a constant expression. A static 8358 // data member of literal type can be declared in the class definition 8359 // with the constexpr specifier; if so, its declaration shall specify a 8360 // brace-or-equal-initializer in which every initializer-clause that is 8361 // an assignment-expression is a constant expression. 8362 8363 // Do nothing on dependent types. 8364 if (DclT->isDependentType()) { 8365 8366 // Allow any 'static constexpr' members, whether or not they are of literal 8367 // type. We separately check that every constexpr variable is of literal 8368 // type. 8369 } else if (VDecl->isConstexpr()) { 8370 8371 // Require constness. 8372 } else if (!DclT.isConstQualified()) { 8373 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8374 << Init->getSourceRange(); 8375 VDecl->setInvalidDecl(); 8376 8377 // We allow integer constant expressions in all cases. 8378 } else if (DclT->isIntegralOrEnumerationType()) { 8379 // Check whether the expression is a constant expression. 8380 SourceLocation Loc; 8381 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8382 // In C++11, a non-constexpr const static data member with an 8383 // in-class initializer cannot be volatile. 8384 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8385 else if (Init->isValueDependent()) 8386 ; // Nothing to check. 8387 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8388 ; // Ok, it's an ICE! 8389 else if (Init->isEvaluatable(Context)) { 8390 // If we can constant fold the initializer through heroics, accept it, 8391 // but report this as a use of an extension for -pedantic. 8392 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8393 << Init->getSourceRange(); 8394 } else { 8395 // Otherwise, this is some crazy unknown case. Report the issue at the 8396 // location provided by the isIntegerConstantExpr failed check. 8397 Diag(Loc, diag::err_in_class_initializer_non_constant) 8398 << Init->getSourceRange(); 8399 VDecl->setInvalidDecl(); 8400 } 8401 8402 // We allow foldable floating-point constants as an extension. 8403 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8404 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8405 // it anyway and provide a fixit to add the 'constexpr'. 8406 if (getLangOpts().CPlusPlus11) { 8407 Diag(VDecl->getLocation(), 8408 diag::ext_in_class_initializer_float_type_cxx11) 8409 << DclT << Init->getSourceRange(); 8410 Diag(VDecl->getLocStart(), 8411 diag::note_in_class_initializer_float_type_cxx11) 8412 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8413 } else { 8414 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8415 << DclT << Init->getSourceRange(); 8416 8417 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8418 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8419 << Init->getSourceRange(); 8420 VDecl->setInvalidDecl(); 8421 } 8422 } 8423 8424 // Suggest adding 'constexpr' in C++11 for literal types. 8425 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8426 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8427 << DclT << Init->getSourceRange() 8428 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8429 VDecl->setConstexpr(true); 8430 8431 } else { 8432 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8433 << DclT << Init->getSourceRange(); 8434 VDecl->setInvalidDecl(); 8435 } 8436 } else if (VDecl->isFileVarDecl()) { 8437 if (VDecl->getStorageClass() == SC_Extern && 8438 (!getLangOpts().CPlusPlus || 8439 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8440 VDecl->isExternC())) && 8441 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8442 Diag(VDecl->getLocation(), diag::warn_extern_init); 8443 8444 // C99 6.7.8p4. All file scoped initializers need to be constant. 8445 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8446 CheckForConstantInitializer(Init, DclT); 8447 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8448 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8449 !Init->isValueDependent() && !VDecl->isConstexpr() && 8450 !Init->isConstantInitializer( 8451 Context, VDecl->getType()->isReferenceType())) { 8452 // GNU C++98 edits for __thread, [basic.start.init]p4: 8453 // An object of thread storage duration shall not require dynamic 8454 // initialization. 8455 // FIXME: Need strict checking here. 8456 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8457 if (getLangOpts().CPlusPlus11) 8458 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8459 } 8460 } 8461 8462 // We will represent direct-initialization similarly to copy-initialization: 8463 // int x(1); -as-> int x = 1; 8464 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8465 // 8466 // Clients that want to distinguish between the two forms, can check for 8467 // direct initializer using VarDecl::getInitStyle(). 8468 // A major benefit is that clients that don't particularly care about which 8469 // exactly form was it (like the CodeGen) can handle both cases without 8470 // special case code. 8471 8472 // C++ 8.5p11: 8473 // The form of initialization (using parentheses or '=') is generally 8474 // insignificant, but does matter when the entity being initialized has a 8475 // class type. 8476 if (CXXDirectInit) { 8477 assert(DirectInit && "Call-style initializer must be direct init."); 8478 VDecl->setInitStyle(VarDecl::CallInit); 8479 } else if (DirectInit) { 8480 // This must be list-initialization. No other way is direct-initialization. 8481 VDecl->setInitStyle(VarDecl::ListInit); 8482 } 8483 8484 CheckCompleteVariableDeclaration(VDecl); 8485} 8486 8487/// ActOnInitializerError - Given that there was an error parsing an 8488/// initializer for the given declaration, try to return to some form 8489/// of sanity. 8490void Sema::ActOnInitializerError(Decl *D) { 8491 // Our main concern here is re-establishing invariants like "a 8492 // variable's type is either dependent or complete". 8493 if (!D || D->isInvalidDecl()) return; 8494 8495 VarDecl *VD = dyn_cast<VarDecl>(D); 8496 if (!VD) return; 8497 8498 // Auto types are meaningless if we can't make sense of the initializer. 8499 if (ParsingInitForAutoVars.count(D)) { 8500 D->setInvalidDecl(); 8501 return; 8502 } 8503 8504 QualType Ty = VD->getType(); 8505 if (Ty->isDependentType()) return; 8506 8507 // Require a complete type. 8508 if (RequireCompleteType(VD->getLocation(), 8509 Context.getBaseElementType(Ty), 8510 diag::err_typecheck_decl_incomplete_type)) { 8511 VD->setInvalidDecl(); 8512 return; 8513 } 8514 8515 // Require an abstract type. 8516 if (RequireNonAbstractType(VD->getLocation(), Ty, 8517 diag::err_abstract_type_in_decl, 8518 AbstractVariableType)) { 8519 VD->setInvalidDecl(); 8520 return; 8521 } 8522 8523 // Don't bother complaining about constructors or destructors, 8524 // though. 8525} 8526 8527void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8528 bool TypeMayContainAuto) { 8529 // If there is no declaration, there was an error parsing it. Just ignore it. 8530 if (RealDecl == 0) 8531 return; 8532 8533 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8534 QualType Type = Var->getType(); 8535 8536 // C++11 [dcl.spec.auto]p3 8537 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8538 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8539 << Var->getDeclName() << Type; 8540 Var->setInvalidDecl(); 8541 return; 8542 } 8543 8544 // C++11 [class.static.data]p3: A static data member can be declared with 8545 // the constexpr specifier; if so, its declaration shall specify 8546 // a brace-or-equal-initializer. 8547 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8548 // the definition of a variable [...] or the declaration of a static data 8549 // member. 8550 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8551 if (Var->isStaticDataMember()) 8552 Diag(Var->getLocation(), 8553 diag::err_constexpr_static_mem_var_requires_init) 8554 << Var->getDeclName(); 8555 else 8556 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8557 Var->setInvalidDecl(); 8558 return; 8559 } 8560 8561 switch (Var->isThisDeclarationADefinition()) { 8562 case VarDecl::Definition: 8563 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8564 break; 8565 8566 // We have an out-of-line definition of a static data member 8567 // that has an in-class initializer, so we type-check this like 8568 // a declaration. 8569 // 8570 // Fall through 8571 8572 case VarDecl::DeclarationOnly: 8573 // It's only a declaration. 8574 8575 // Block scope. C99 6.7p7: If an identifier for an object is 8576 // declared with no linkage (C99 6.2.2p6), the type for the 8577 // object shall be complete. 8578 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8579 !Var->hasLinkage() && !Var->isInvalidDecl() && 8580 RequireCompleteType(Var->getLocation(), Type, 8581 diag::err_typecheck_decl_incomplete_type)) 8582 Var->setInvalidDecl(); 8583 8584 // Make sure that the type is not abstract. 8585 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8586 RequireNonAbstractType(Var->getLocation(), Type, 8587 diag::err_abstract_type_in_decl, 8588 AbstractVariableType)) 8589 Var->setInvalidDecl(); 8590 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8591 Var->getStorageClass() == SC_PrivateExtern) { 8592 Diag(Var->getLocation(), diag::warn_private_extern); 8593 Diag(Var->getLocation(), diag::note_private_extern); 8594 } 8595 8596 return; 8597 8598 case VarDecl::TentativeDefinition: 8599 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8600 // object that has file scope without an initializer, and without a 8601 // storage-class specifier or with the storage-class specifier "static", 8602 // constitutes a tentative definition. Note: A tentative definition with 8603 // external linkage is valid (C99 6.2.2p5). 8604 if (!Var->isInvalidDecl()) { 8605 if (const IncompleteArrayType *ArrayT 8606 = Context.getAsIncompleteArrayType(Type)) { 8607 if (RequireCompleteType(Var->getLocation(), 8608 ArrayT->getElementType(), 8609 diag::err_illegal_decl_array_incomplete_type)) 8610 Var->setInvalidDecl(); 8611 } else if (Var->getStorageClass() == SC_Static) { 8612 // C99 6.9.2p3: If the declaration of an identifier for an object is 8613 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8614 // declared type shall not be an incomplete type. 8615 // NOTE: code such as the following 8616 // static struct s; 8617 // struct s { int a; }; 8618 // is accepted by gcc. Hence here we issue a warning instead of 8619 // an error and we do not invalidate the static declaration. 8620 // NOTE: to avoid multiple warnings, only check the first declaration. 8621 if (Var->isFirstDecl()) 8622 RequireCompleteType(Var->getLocation(), Type, 8623 diag::ext_typecheck_decl_incomplete_type); 8624 } 8625 } 8626 8627 // Record the tentative definition; we're done. 8628 if (!Var->isInvalidDecl()) 8629 TentativeDefinitions.push_back(Var); 8630 return; 8631 } 8632 8633 // Provide a specific diagnostic for uninitialized variable 8634 // definitions with incomplete array type. 8635 if (Type->isIncompleteArrayType()) { 8636 Diag(Var->getLocation(), 8637 diag::err_typecheck_incomplete_array_needs_initializer); 8638 Var->setInvalidDecl(); 8639 return; 8640 } 8641 8642 // Provide a specific diagnostic for uninitialized variable 8643 // definitions with reference type. 8644 if (Type->isReferenceType()) { 8645 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8646 << Var->getDeclName() 8647 << SourceRange(Var->getLocation(), Var->getLocation()); 8648 Var->setInvalidDecl(); 8649 return; 8650 } 8651 8652 // Do not attempt to type-check the default initializer for a 8653 // variable with dependent type. 8654 if (Type->isDependentType()) 8655 return; 8656 8657 if (Var->isInvalidDecl()) 8658 return; 8659 8660 if (RequireCompleteType(Var->getLocation(), 8661 Context.getBaseElementType(Type), 8662 diag::err_typecheck_decl_incomplete_type)) { 8663 Var->setInvalidDecl(); 8664 return; 8665 } 8666 8667 // The variable can not have an abstract class type. 8668 if (RequireNonAbstractType(Var->getLocation(), Type, 8669 diag::err_abstract_type_in_decl, 8670 AbstractVariableType)) { 8671 Var->setInvalidDecl(); 8672 return; 8673 } 8674 8675 // Check for jumps past the implicit initializer. C++0x 8676 // clarifies that this applies to a "variable with automatic 8677 // storage duration", not a "local variable". 8678 // C++11 [stmt.dcl]p3 8679 // A program that jumps from a point where a variable with automatic 8680 // storage duration is not in scope to a point where it is in scope is 8681 // ill-formed unless the variable has scalar type, class type with a 8682 // trivial default constructor and a trivial destructor, a cv-qualified 8683 // version of one of these types, or an array of one of the preceding 8684 // types and is declared without an initializer. 8685 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8686 if (const RecordType *Record 8687 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8688 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8689 // Mark the function for further checking even if the looser rules of 8690 // C++11 do not require such checks, so that we can diagnose 8691 // incompatibilities with C++98. 8692 if (!CXXRecord->isPOD()) 8693 getCurFunction()->setHasBranchProtectedScope(); 8694 } 8695 } 8696 8697 // C++03 [dcl.init]p9: 8698 // If no initializer is specified for an object, and the 8699 // object is of (possibly cv-qualified) non-POD class type (or 8700 // array thereof), the object shall be default-initialized; if 8701 // the object is of const-qualified type, the underlying class 8702 // type shall have a user-declared default 8703 // constructor. Otherwise, if no initializer is specified for 8704 // a non- static object, the object and its subobjects, if 8705 // any, have an indeterminate initial value); if the object 8706 // or any of its subobjects are of const-qualified type, the 8707 // program is ill-formed. 8708 // C++0x [dcl.init]p11: 8709 // If no initializer is specified for an object, the object is 8710 // default-initialized; [...]. 8711 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8712 InitializationKind Kind 8713 = InitializationKind::CreateDefault(Var->getLocation()); 8714 8715 InitializationSequence InitSeq(*this, Entity, Kind, None); 8716 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8717 if (Init.isInvalid()) 8718 Var->setInvalidDecl(); 8719 else if (Init.get()) { 8720 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8721 // This is important for template substitution. 8722 Var->setInitStyle(VarDecl::CallInit); 8723 } 8724 8725 CheckCompleteVariableDeclaration(Var); 8726 } 8727} 8728 8729void Sema::ActOnCXXForRangeDecl(Decl *D) { 8730 VarDecl *VD = dyn_cast<VarDecl>(D); 8731 if (!VD) { 8732 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8733 D->setInvalidDecl(); 8734 return; 8735 } 8736 8737 VD->setCXXForRangeDecl(true); 8738 8739 // for-range-declaration cannot be given a storage class specifier. 8740 int Error = -1; 8741 switch (VD->getStorageClass()) { 8742 case SC_None: 8743 break; 8744 case SC_Extern: 8745 Error = 0; 8746 break; 8747 case SC_Static: 8748 Error = 1; 8749 break; 8750 case SC_PrivateExtern: 8751 Error = 2; 8752 break; 8753 case SC_Auto: 8754 Error = 3; 8755 break; 8756 case SC_Register: 8757 Error = 4; 8758 break; 8759 case SC_OpenCLWorkGroupLocal: 8760 llvm_unreachable("Unexpected storage class"); 8761 } 8762 if (VD->isConstexpr()) 8763 Error = 5; 8764 if (Error != -1) { 8765 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8766 << VD->getDeclName() << Error; 8767 D->setInvalidDecl(); 8768 } 8769} 8770 8771void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8772 if (var->isInvalidDecl()) return; 8773 8774 // In ARC, don't allow jumps past the implicit initialization of a 8775 // local retaining variable. 8776 if (getLangOpts().ObjCAutoRefCount && 8777 var->hasLocalStorage()) { 8778 switch (var->getType().getObjCLifetime()) { 8779 case Qualifiers::OCL_None: 8780 case Qualifiers::OCL_ExplicitNone: 8781 case Qualifiers::OCL_Autoreleasing: 8782 break; 8783 8784 case Qualifiers::OCL_Weak: 8785 case Qualifiers::OCL_Strong: 8786 getCurFunction()->setHasBranchProtectedScope(); 8787 break; 8788 } 8789 } 8790 8791 if (var->isThisDeclarationADefinition() && 8792 var->isExternallyVisible() && var->hasLinkage() && 8793 getDiagnostics().getDiagnosticLevel( 8794 diag::warn_missing_variable_declarations, 8795 var->getLocation())) { 8796 // Find a previous declaration that's not a definition. 8797 VarDecl *prev = var->getPreviousDecl(); 8798 while (prev && prev->isThisDeclarationADefinition()) 8799 prev = prev->getPreviousDecl(); 8800 8801 if (!prev) 8802 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8803 } 8804 8805 if (var->getTLSKind() == VarDecl::TLS_Static && 8806 var->getType().isDestructedType()) { 8807 // GNU C++98 edits for __thread, [basic.start.term]p3: 8808 // The type of an object with thread storage duration shall not 8809 // have a non-trivial destructor. 8810 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8811 if (getLangOpts().CPlusPlus11) 8812 Diag(var->getLocation(), diag::note_use_thread_local); 8813 } 8814 8815 // All the following checks are C++ only. 8816 if (!getLangOpts().CPlusPlus) return; 8817 8818 QualType type = var->getType(); 8819 if (type->isDependentType()) return; 8820 8821 // __block variables might require us to capture a copy-initializer. 8822 if (var->hasAttr<BlocksAttr>()) { 8823 // It's currently invalid to ever have a __block variable with an 8824 // array type; should we diagnose that here? 8825 8826 // Regardless, we don't want to ignore array nesting when 8827 // constructing this copy. 8828 if (type->isStructureOrClassType()) { 8829 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8830 SourceLocation poi = var->getLocation(); 8831 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8832 ExprResult result 8833 = PerformMoveOrCopyInitialization( 8834 InitializedEntity::InitializeBlock(poi, type, false), 8835 var, var->getType(), varRef, /*AllowNRVO=*/true); 8836 if (!result.isInvalid()) { 8837 result = MaybeCreateExprWithCleanups(result); 8838 Expr *init = result.takeAs<Expr>(); 8839 Context.setBlockVarCopyInits(var, init); 8840 } 8841 } 8842 } 8843 8844 Expr *Init = var->getInit(); 8845 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8846 QualType baseType = Context.getBaseElementType(type); 8847 8848 if (!var->getDeclContext()->isDependentContext() && 8849 Init && !Init->isValueDependent()) { 8850 if (IsGlobal && !var->isConstexpr() && 8851 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8852 var->getLocation()) 8853 != DiagnosticsEngine::Ignored) { 8854 // Warn about globals which don't have a constant initializer. Don't 8855 // warn about globals with a non-trivial destructor because we already 8856 // warned about them. 8857 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8858 if (!(RD && !RD->hasTrivialDestructor()) && 8859 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8860 Diag(var->getLocation(), diag::warn_global_constructor) 8861 << Init->getSourceRange(); 8862 } 8863 8864 if (var->isConstexpr()) { 8865 SmallVector<PartialDiagnosticAt, 8> Notes; 8866 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8867 SourceLocation DiagLoc = var->getLocation(); 8868 // If the note doesn't add any useful information other than a source 8869 // location, fold it into the primary diagnostic. 8870 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8871 diag::note_invalid_subexpr_in_const_expr) { 8872 DiagLoc = Notes[0].first; 8873 Notes.clear(); 8874 } 8875 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8876 << var << Init->getSourceRange(); 8877 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8878 Diag(Notes[I].first, Notes[I].second); 8879 } 8880 } else if (var->isUsableInConstantExpressions(Context)) { 8881 // Check whether the initializer of a const variable of integral or 8882 // enumeration type is an ICE now, since we can't tell whether it was 8883 // initialized by a constant expression if we check later. 8884 var->checkInitIsICE(); 8885 } 8886 } 8887 8888 // Require the destructor. 8889 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8890 FinalizeVarWithDestructor(var, recordType); 8891} 8892 8893/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8894/// any semantic actions necessary after any initializer has been attached. 8895void 8896Sema::FinalizeDeclaration(Decl *ThisDecl) { 8897 // Note that we are no longer parsing the initializer for this declaration. 8898 ParsingInitForAutoVars.erase(ThisDecl); 8899 8900 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8901 if (!VD) 8902 return; 8903 8904 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8905 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8906 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used"; 8907 VD->dropAttr<UsedAttr>(); 8908 } 8909 } 8910 8911 if (!VD->isInvalidDecl() && 8912 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8913 if (const VarDecl *Def = VD->getDefinition()) { 8914 if (Def->hasAttr<AliasAttr>()) { 8915 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8916 << VD->getDeclName(); 8917 Diag(Def->getLocation(), diag::note_previous_definition); 8918 VD->setInvalidDecl(); 8919 } 8920 } 8921 } 8922 8923 const DeclContext *DC = VD->getDeclContext(); 8924 // If there's a #pragma GCC visibility in scope, and this isn't a class 8925 // member, set the visibility of this variable. 8926 if (!DC->isRecord() && VD->isExternallyVisible()) 8927 AddPushedVisibilityAttribute(VD); 8928 8929 if (VD->isFileVarDecl()) 8930 MarkUnusedFileScopedDecl(VD); 8931 8932 // Now we have parsed the initializer and can update the table of magic 8933 // tag values. 8934 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8935 !VD->getType()->isIntegralOrEnumerationType()) 8936 return; 8937 8938 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8939 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8940 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8941 I != E; ++I) { 8942 const Expr *MagicValueExpr = VD->getInit(); 8943 if (!MagicValueExpr) { 8944 continue; 8945 } 8946 llvm::APSInt MagicValueInt; 8947 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8948 Diag(I->getRange().getBegin(), 8949 diag::err_type_tag_for_datatype_not_ice) 8950 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8951 continue; 8952 } 8953 if (MagicValueInt.getActiveBits() > 64) { 8954 Diag(I->getRange().getBegin(), 8955 diag::err_type_tag_for_datatype_too_large) 8956 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8957 continue; 8958 } 8959 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8960 RegisterTypeTagForDatatype(I->getArgumentKind(), 8961 MagicValue, 8962 I->getMatchingCType(), 8963 I->getLayoutCompatible(), 8964 I->getMustBeNull()); 8965 } 8966} 8967 8968Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8969 ArrayRef<Decl *> Group) { 8970 SmallVector<Decl*, 8> Decls; 8971 8972 if (DS.isTypeSpecOwned()) 8973 Decls.push_back(DS.getRepAsDecl()); 8974 8975 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8976 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8977 if (Decl *D = Group[i]) { 8978 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8979 if (!FirstDeclaratorInGroup) 8980 FirstDeclaratorInGroup = DD; 8981 Decls.push_back(D); 8982 } 8983 8984 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8985 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8986 HandleTagNumbering(*this, Tag); 8987 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8988 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8989 } 8990 } 8991 8992 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8993} 8994 8995/// BuildDeclaratorGroup - convert a list of declarations into a declaration 8996/// group, performing any necessary semantic checking. 8997Sema::DeclGroupPtrTy 8998Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8999 bool TypeMayContainAuto) { 9000 // C++0x [dcl.spec.auto]p7: 9001 // If the type deduced for the template parameter U is not the same in each 9002 // deduction, the program is ill-formed. 9003 // FIXME: When initializer-list support is added, a distinction is needed 9004 // between the deduced type U and the deduced type which 'auto' stands for. 9005 // auto a = 0, b = { 1, 2, 3 }; 9006 // is legal because the deduced type U is 'int' in both cases. 9007 if (TypeMayContainAuto && Group.size() > 1) { 9008 QualType Deduced; 9009 CanQualType DeducedCanon; 9010 VarDecl *DeducedDecl = 0; 9011 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9012 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9013 AutoType *AT = D->getType()->getContainedAutoType(); 9014 // Don't reissue diagnostics when instantiating a template. 9015 if (AT && D->isInvalidDecl()) 9016 break; 9017 QualType U = AT ? AT->getDeducedType() : QualType(); 9018 if (!U.isNull()) { 9019 CanQualType UCanon = Context.getCanonicalType(U); 9020 if (Deduced.isNull()) { 9021 Deduced = U; 9022 DeducedCanon = UCanon; 9023 DeducedDecl = D; 9024 } else if (DeducedCanon != UCanon) { 9025 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9026 diag::err_auto_different_deductions) 9027 << (AT->isDecltypeAuto() ? 1 : 0) 9028 << Deduced << DeducedDecl->getDeclName() 9029 << U << D->getDeclName() 9030 << DeducedDecl->getInit()->getSourceRange() 9031 << D->getInit()->getSourceRange(); 9032 D->setInvalidDecl(); 9033 break; 9034 } 9035 } 9036 } 9037 } 9038 } 9039 9040 ActOnDocumentableDecls(Group); 9041 9042 return DeclGroupPtrTy::make( 9043 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9044} 9045 9046void Sema::ActOnDocumentableDecl(Decl *D) { 9047 ActOnDocumentableDecls(D); 9048} 9049 9050void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9051 // Don't parse the comment if Doxygen diagnostics are ignored. 9052 if (Group.empty() || !Group[0]) 9053 return; 9054 9055 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9056 Group[0]->getLocation()) 9057 == DiagnosticsEngine::Ignored) 9058 return; 9059 9060 if (Group.size() >= 2) { 9061 // This is a decl group. Normally it will contain only declarations 9062 // produced from declarator list. But in case we have any definitions or 9063 // additional declaration references: 9064 // 'typedef struct S {} S;' 9065 // 'typedef struct S *S;' 9066 // 'struct S *pS;' 9067 // FinalizeDeclaratorGroup adds these as separate declarations. 9068 Decl *MaybeTagDecl = Group[0]; 9069 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9070 Group = Group.slice(1); 9071 } 9072 } 9073 9074 // See if there are any new comments that are not attached to a decl. 9075 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9076 if (!Comments.empty() && 9077 !Comments.back()->isAttached()) { 9078 // There is at least one comment that not attached to a decl. 9079 // Maybe it should be attached to one of these decls? 9080 // 9081 // Note that this way we pick up not only comments that precede the 9082 // declaration, but also comments that *follow* the declaration -- thanks to 9083 // the lookahead in the lexer: we've consumed the semicolon and looked 9084 // ahead through comments. 9085 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9086 Context.getCommentForDecl(Group[i], &PP); 9087 } 9088} 9089 9090/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9091/// to introduce parameters into function prototype scope. 9092Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9093 const DeclSpec &DS = D.getDeclSpec(); 9094 9095 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9096 9097 // C++03 [dcl.stc]p2 also permits 'auto'. 9098 VarDecl::StorageClass StorageClass = SC_None; 9099 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9100 StorageClass = SC_Register; 9101 } else if (getLangOpts().CPlusPlus && 9102 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9103 StorageClass = SC_Auto; 9104 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9105 Diag(DS.getStorageClassSpecLoc(), 9106 diag::err_invalid_storage_class_in_func_decl); 9107 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9108 } 9109 9110 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9111 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9112 << DeclSpec::getSpecifierName(TSCS); 9113 if (DS.isConstexprSpecified()) 9114 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9115 << 0; 9116 9117 DiagnoseFunctionSpecifiers(DS); 9118 9119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9120 QualType parmDeclType = TInfo->getType(); 9121 9122 if (getLangOpts().CPlusPlus) { 9123 // Check that there are no default arguments inside the type of this 9124 // parameter. 9125 CheckExtraCXXDefaultArguments(D); 9126 9127 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9128 if (D.getCXXScopeSpec().isSet()) { 9129 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9130 << D.getCXXScopeSpec().getRange(); 9131 D.getCXXScopeSpec().clear(); 9132 } 9133 } 9134 9135 // Ensure we have a valid name 9136 IdentifierInfo *II = 0; 9137 if (D.hasName()) { 9138 II = D.getIdentifier(); 9139 if (!II) { 9140 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9141 << GetNameForDeclarator(D).getName().getAsString(); 9142 D.setInvalidType(true); 9143 } 9144 } 9145 9146 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9147 if (II) { 9148 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9149 ForRedeclaration); 9150 LookupName(R, S); 9151 if (R.isSingleResult()) { 9152 NamedDecl *PrevDecl = R.getFoundDecl(); 9153 if (PrevDecl->isTemplateParameter()) { 9154 // Maybe we will complain about the shadowed template parameter. 9155 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9156 // Just pretend that we didn't see the previous declaration. 9157 PrevDecl = 0; 9158 } else if (S->isDeclScope(PrevDecl)) { 9159 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9160 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9161 9162 // Recover by removing the name 9163 II = 0; 9164 D.SetIdentifier(0, D.getIdentifierLoc()); 9165 D.setInvalidType(true); 9166 } 9167 } 9168 } 9169 9170 // Temporarily put parameter variables in the translation unit, not 9171 // the enclosing context. This prevents them from accidentally 9172 // looking like class members in C++. 9173 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9174 D.getLocStart(), 9175 D.getIdentifierLoc(), II, 9176 parmDeclType, TInfo, 9177 StorageClass); 9178 9179 if (D.isInvalidType()) 9180 New->setInvalidDecl(); 9181 9182 assert(S->isFunctionPrototypeScope()); 9183 assert(S->getFunctionPrototypeDepth() >= 1); 9184 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9185 S->getNextFunctionPrototypeIndex()); 9186 9187 // Add the parameter declaration into this scope. 9188 S->AddDecl(New); 9189 if (II) 9190 IdResolver.AddDecl(New); 9191 9192 ProcessDeclAttributes(S, New, D); 9193 9194 if (D.getDeclSpec().isModulePrivateSpecified()) 9195 Diag(New->getLocation(), diag::err_module_private_local) 9196 << 1 << New->getDeclName() 9197 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9198 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9199 9200 if (New->hasAttr<BlocksAttr>()) { 9201 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9202 } 9203 return New; 9204} 9205 9206/// \brief Synthesizes a variable for a parameter arising from a 9207/// typedef. 9208ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9209 SourceLocation Loc, 9210 QualType T) { 9211 /* FIXME: setting StartLoc == Loc. 9212 Would it be worth to modify callers so as to provide proper source 9213 location for the unnamed parameters, embedding the parameter's type? */ 9214 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9215 T, Context.getTrivialTypeSourceInfo(T, Loc), 9216 SC_None, 0); 9217 Param->setImplicit(); 9218 return Param; 9219} 9220 9221void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9222 ParmVarDecl * const *ParamEnd) { 9223 // Don't diagnose unused-parameter errors in template instantiations; we 9224 // will already have done so in the template itself. 9225 if (!ActiveTemplateInstantiations.empty()) 9226 return; 9227 9228 for (; Param != ParamEnd; ++Param) { 9229 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9230 !(*Param)->hasAttr<UnusedAttr>()) { 9231 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9232 << (*Param)->getDeclName(); 9233 } 9234 } 9235} 9236 9237void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9238 ParmVarDecl * const *ParamEnd, 9239 QualType ReturnTy, 9240 NamedDecl *D) { 9241 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9242 return; 9243 9244 // Warn if the return value is pass-by-value and larger than the specified 9245 // threshold. 9246 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9247 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9248 if (Size > LangOpts.NumLargeByValueCopy) 9249 Diag(D->getLocation(), diag::warn_return_value_size) 9250 << D->getDeclName() << Size; 9251 } 9252 9253 // Warn if any parameter is pass-by-value and larger than the specified 9254 // threshold. 9255 for (; Param != ParamEnd; ++Param) { 9256 QualType T = (*Param)->getType(); 9257 if (T->isDependentType() || !T.isPODType(Context)) 9258 continue; 9259 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9260 if (Size > LangOpts.NumLargeByValueCopy) 9261 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9262 << (*Param)->getDeclName() << Size; 9263 } 9264} 9265 9266ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9267 SourceLocation NameLoc, IdentifierInfo *Name, 9268 QualType T, TypeSourceInfo *TSInfo, 9269 VarDecl::StorageClass StorageClass) { 9270 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9271 if (getLangOpts().ObjCAutoRefCount && 9272 T.getObjCLifetime() == Qualifiers::OCL_None && 9273 T->isObjCLifetimeType()) { 9274 9275 Qualifiers::ObjCLifetime lifetime; 9276 9277 // Special cases for arrays: 9278 // - if it's const, use __unsafe_unretained 9279 // - otherwise, it's an error 9280 if (T->isArrayType()) { 9281 if (!T.isConstQualified()) { 9282 DelayedDiagnostics.add( 9283 sema::DelayedDiagnostic::makeForbiddenType( 9284 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9285 } 9286 lifetime = Qualifiers::OCL_ExplicitNone; 9287 } else { 9288 lifetime = T->getObjCARCImplicitLifetime(); 9289 } 9290 T = Context.getLifetimeQualifiedType(T, lifetime); 9291 } 9292 9293 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9294 Context.getAdjustedParameterType(T), 9295 TSInfo, 9296 StorageClass, 0); 9297 9298 // Parameters can not be abstract class types. 9299 // For record types, this is done by the AbstractClassUsageDiagnoser once 9300 // the class has been completely parsed. 9301 if (!CurContext->isRecord() && 9302 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9303 AbstractParamType)) 9304 New->setInvalidDecl(); 9305 9306 // Parameter declarators cannot be interface types. All ObjC objects are 9307 // passed by reference. 9308 if (T->isObjCObjectType()) { 9309 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9310 Diag(NameLoc, 9311 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9312 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9313 T = Context.getObjCObjectPointerType(T); 9314 New->setType(T); 9315 } 9316 9317 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9318 // duration shall not be qualified by an address-space qualifier." 9319 // Since all parameters have automatic store duration, they can not have 9320 // an address space. 9321 if (T.getAddressSpace() != 0) { 9322 Diag(NameLoc, diag::err_arg_with_address_space); 9323 New->setInvalidDecl(); 9324 } 9325 9326 return New; 9327} 9328 9329void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9330 SourceLocation LocAfterDecls) { 9331 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9332 9333 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9334 // for a K&R function. 9335 if (!FTI.hasPrototype) { 9336 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9337 --i; 9338 if (FTI.ArgInfo[i].Param == 0) { 9339 SmallString<256> Code; 9340 llvm::raw_svector_ostream(Code) << " int " 9341 << FTI.ArgInfo[i].Ident->getName() 9342 << ";\n"; 9343 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9344 << FTI.ArgInfo[i].Ident 9345 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9346 9347 // Implicitly declare the argument as type 'int' for lack of a better 9348 // type. 9349 AttributeFactory attrs; 9350 DeclSpec DS(attrs); 9351 const char* PrevSpec; // unused 9352 unsigned DiagID; // unused 9353 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9354 PrevSpec, DiagID); 9355 // Use the identifier location for the type source range. 9356 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9357 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9358 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9359 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9360 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9361 } 9362 } 9363 } 9364} 9365 9366Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9367 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9368 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9369 Scope *ParentScope = FnBodyScope->getParent(); 9370 9371 D.setFunctionDefinitionKind(FDK_Definition); 9372 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9373 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9374} 9375 9376static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9377 const FunctionDecl*& PossibleZeroParamPrototype) { 9378 // Don't warn about invalid declarations. 9379 if (FD->isInvalidDecl()) 9380 return false; 9381 9382 // Or declarations that aren't global. 9383 if (!FD->isGlobal()) 9384 return false; 9385 9386 // Don't warn about C++ member functions. 9387 if (isa<CXXMethodDecl>(FD)) 9388 return false; 9389 9390 // Don't warn about 'main'. 9391 if (FD->isMain()) 9392 return false; 9393 9394 // Don't warn about inline functions. 9395 if (FD->isInlined()) 9396 return false; 9397 9398 // Don't warn about function templates. 9399 if (FD->getDescribedFunctionTemplate()) 9400 return false; 9401 9402 // Don't warn about function template specializations. 9403 if (FD->isFunctionTemplateSpecialization()) 9404 return false; 9405 9406 // Don't warn for OpenCL kernels. 9407 if (FD->hasAttr<OpenCLKernelAttr>()) 9408 return false; 9409 9410 bool MissingPrototype = true; 9411 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9412 Prev; Prev = Prev->getPreviousDecl()) { 9413 // Ignore any declarations that occur in function or method 9414 // scope, because they aren't visible from the header. 9415 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9416 continue; 9417 9418 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9419 if (FD->getNumParams() == 0) 9420 PossibleZeroParamPrototype = Prev; 9421 break; 9422 } 9423 9424 return MissingPrototype; 9425} 9426 9427void 9428Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9429 const FunctionDecl *EffectiveDefinition) { 9430 // Don't complain if we're in GNU89 mode and the previous definition 9431 // was an extern inline function. 9432 const FunctionDecl *Definition = EffectiveDefinition; 9433 if (!Definition) 9434 if (!FD->isDefined(Definition)) 9435 return; 9436 9437 if (canRedefineFunction(Definition, getLangOpts())) 9438 return; 9439 9440 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9441 Definition->getStorageClass() == SC_Extern) 9442 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9443 << FD->getDeclName() << getLangOpts().CPlusPlus; 9444 else 9445 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9446 9447 Diag(Definition->getLocation(), diag::note_previous_definition); 9448 FD->setInvalidDecl(); 9449} 9450 9451 9452static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9453 Sema &S) { 9454 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9455 9456 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9457 LSI->CallOperator = CallOperator; 9458 LSI->Lambda = LambdaClass; 9459 LSI->ReturnType = CallOperator->getResultType(); 9460 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9461 9462 if (LCD == LCD_None) 9463 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9464 else if (LCD == LCD_ByCopy) 9465 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9466 else if (LCD == LCD_ByRef) 9467 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9468 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9469 9470 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9471 LSI->Mutable = !CallOperator->isConst(); 9472 9473 // Add the captures to the LSI so they can be noted as already 9474 // captured within tryCaptureVar. 9475 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9476 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9477 if (C->capturesVariable()) { 9478 VarDecl *VD = C->getCapturedVar(); 9479 if (VD->isInitCapture()) 9480 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9481 QualType CaptureType = VD->getType(); 9482 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9483 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9484 /*RefersToEnclosingLocal*/true, C->getLocation(), 9485 /*EllipsisLoc*/C->isPackExpansion() 9486 ? C->getEllipsisLoc() : SourceLocation(), 9487 CaptureType, /*Expr*/ 0); 9488 9489 } else if (C->capturesThis()) { 9490 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9491 S.getCurrentThisType(), /*Expr*/ 0); 9492 } 9493 } 9494} 9495 9496Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9497 // Clear the last template instantiation error context. 9498 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9499 9500 if (!D) 9501 return D; 9502 FunctionDecl *FD = 0; 9503 9504 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9505 FD = FunTmpl->getTemplatedDecl(); 9506 else 9507 FD = cast<FunctionDecl>(D); 9508 // If we are instantiating a generic lambda call operator, push 9509 // a LambdaScopeInfo onto the function stack. But use the information 9510 // that's already been calculated (ActOnLambdaExpr) to prime the current 9511 // LambdaScopeInfo. 9512 // When the template operator is being specialized, the LambdaScopeInfo, 9513 // has to be properly restored so that tryCaptureVariable doesn't try 9514 // and capture any new variables. In addition when calculating potential 9515 // captures during transformation of nested lambdas, it is necessary to 9516 // have the LSI properly restored. 9517 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9518 assert(ActiveTemplateInstantiations.size() && 9519 "There should be an active template instantiation on the stack " 9520 "when instantiating a generic lambda!"); 9521 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9522 } 9523 else 9524 // Enter a new function scope 9525 PushFunctionScope(); 9526 9527 // See if this is a redefinition. 9528 if (!FD->isLateTemplateParsed()) 9529 CheckForFunctionRedefinition(FD); 9530 9531 // Builtin functions cannot be defined. 9532 if (unsigned BuiltinID = FD->getBuiltinID()) { 9533 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9534 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9535 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9536 FD->setInvalidDecl(); 9537 } 9538 } 9539 9540 // The return type of a function definition must be complete 9541 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9542 QualType ResultType = FD->getResultType(); 9543 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9544 !FD->isInvalidDecl() && 9545 RequireCompleteType(FD->getLocation(), ResultType, 9546 diag::err_func_def_incomplete_result)) 9547 FD->setInvalidDecl(); 9548 9549 // GNU warning -Wmissing-prototypes: 9550 // Warn if a global function is defined without a previous 9551 // prototype declaration. This warning is issued even if the 9552 // definition itself provides a prototype. The aim is to detect 9553 // global functions that fail to be declared in header files. 9554 const FunctionDecl *PossibleZeroParamPrototype = 0; 9555 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9556 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9557 9558 if (PossibleZeroParamPrototype) { 9559 // We found a declaration that is not a prototype, 9560 // but that could be a zero-parameter prototype 9561 if (TypeSourceInfo *TI = 9562 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9563 TypeLoc TL = TI->getTypeLoc(); 9564 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9565 Diag(PossibleZeroParamPrototype->getLocation(), 9566 diag::note_declaration_not_a_prototype) 9567 << PossibleZeroParamPrototype 9568 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9569 } 9570 } 9571 } 9572 9573 if (FnBodyScope) 9574 PushDeclContext(FnBodyScope, FD); 9575 9576 // Check the validity of our function parameters 9577 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9578 /*CheckParameterNames=*/true); 9579 9580 // Introduce our parameters into the function scope 9581 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9582 ParmVarDecl *Param = FD->getParamDecl(p); 9583 Param->setOwningFunction(FD); 9584 9585 // If this has an identifier, add it to the scope stack. 9586 if (Param->getIdentifier() && FnBodyScope) { 9587 CheckShadow(FnBodyScope, Param); 9588 9589 PushOnScopeChains(Param, FnBodyScope); 9590 } 9591 } 9592 9593 // If we had any tags defined in the function prototype, 9594 // introduce them into the function scope. 9595 if (FnBodyScope) { 9596 for (ArrayRef<NamedDecl *>::iterator 9597 I = FD->getDeclsInPrototypeScope().begin(), 9598 E = FD->getDeclsInPrototypeScope().end(); 9599 I != E; ++I) { 9600 NamedDecl *D = *I; 9601 9602 // Some of these decls (like enums) may have been pinned to the translation unit 9603 // for lack of a real context earlier. If so, remove from the translation unit 9604 // and reattach to the current context. 9605 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9606 // Is the decl actually in the context? 9607 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9608 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9609 if (*DI == D) { 9610 Context.getTranslationUnitDecl()->removeDecl(D); 9611 break; 9612 } 9613 } 9614 // Either way, reassign the lexical decl context to our FunctionDecl. 9615 D->setLexicalDeclContext(CurContext); 9616 } 9617 9618 // If the decl has a non-null name, make accessible in the current scope. 9619 if (!D->getName().empty()) 9620 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9621 9622 // Similarly, dive into enums and fish their constants out, making them 9623 // accessible in this scope. 9624 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9625 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9626 EE = ED->enumerator_end(); EI != EE; ++EI) 9627 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9628 } 9629 } 9630 } 9631 9632 // Ensure that the function's exception specification is instantiated. 9633 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9634 ResolveExceptionSpec(D->getLocation(), FPT); 9635 9636 // Checking attributes of current function definition 9637 // dllimport attribute. 9638 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9639 if (DA && (!FD->getAttr<DLLExportAttr>())) { 9640 // dllimport attribute cannot be directly applied to definition. 9641 // Microsoft accepts dllimport for functions defined within class scope. 9642 if (!DA->isInherited() && 9643 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9644 Diag(FD->getLocation(), 9645 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9646 << "dllimport"; 9647 FD->setInvalidDecl(); 9648 return D; 9649 } 9650 9651 // Visual C++ appears to not think this is an issue, so only issue 9652 // a warning when Microsoft extensions are disabled. 9653 if (!LangOpts.MicrosoftExt) { 9654 // If a symbol previously declared dllimport is later defined, the 9655 // attribute is ignored in subsequent references, and a warning is 9656 // emitted. 9657 Diag(FD->getLocation(), 9658 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9659 << FD->getName() << "dllimport"; 9660 } 9661 } 9662 // We want to attach documentation to original Decl (which might be 9663 // a function template). 9664 ActOnDocumentableDecl(D); 9665 return D; 9666} 9667 9668/// \brief Given the set of return statements within a function body, 9669/// compute the variables that are subject to the named return value 9670/// optimization. 9671/// 9672/// Each of the variables that is subject to the named return value 9673/// optimization will be marked as NRVO variables in the AST, and any 9674/// return statement that has a marked NRVO variable as its NRVO candidate can 9675/// use the named return value optimization. 9676/// 9677/// This function applies a very simplistic algorithm for NRVO: if every return 9678/// statement in the function has the same NRVO candidate, that candidate is 9679/// the NRVO variable. 9680/// 9681/// FIXME: Employ a smarter algorithm that accounts for multiple return 9682/// statements and the lifetimes of the NRVO candidates. We should be able to 9683/// find a maximal set of NRVO variables. 9684void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9685 ReturnStmt **Returns = Scope->Returns.data(); 9686 9687 const VarDecl *NRVOCandidate = 0; 9688 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9689 if (!Returns[I]->getNRVOCandidate()) 9690 return; 9691 9692 if (!NRVOCandidate) 9693 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9694 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9695 return; 9696 } 9697 9698 if (NRVOCandidate) 9699 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9700} 9701 9702bool Sema::canSkipFunctionBody(Decl *D) { 9703 if (!Consumer.shouldSkipFunctionBody(D)) 9704 return false; 9705 9706 if (isa<ObjCMethodDecl>(D)) 9707 return true; 9708 9709 FunctionDecl *FD = 0; 9710 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 9711 FD = FTD->getTemplatedDecl(); 9712 else 9713 FD = cast<FunctionDecl>(D); 9714 9715 // We cannot skip the body of a function (or function template) which is 9716 // constexpr, since we may need to evaluate its body in order to parse the 9717 // rest of the file. 9718 // We cannot skip the body of a function with an undeduced return type, 9719 // because any callers of that function need to know the type. 9720 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType(); 9721} 9722 9723Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9724 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9725 FD->setHasSkippedBody(); 9726 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9727 MD->setHasSkippedBody(); 9728 return ActOnFinishFunctionBody(Decl, 0); 9729} 9730 9731Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9732 return ActOnFinishFunctionBody(D, BodyArg, false); 9733} 9734 9735Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9736 bool IsInstantiation) { 9737 FunctionDecl *FD = 0; 9738 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 9739 if (FunTmpl) 9740 FD = FunTmpl->getTemplatedDecl(); 9741 else 9742 FD = dyn_cast_or_null<FunctionDecl>(dcl); 9743 9744 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9745 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9746 9747 if (FD) { 9748 FD->setBody(Body); 9749 9750 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9751 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) { 9752 // If the function has a deduced result type but contains no 'return' 9753 // statements, the result type as written must be exactly 'auto', and 9754 // the deduced result type is 'void'. 9755 if (!FD->getResultType()->getAs<AutoType>()) { 9756 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9757 << FD->getResultType(); 9758 FD->setInvalidDecl(); 9759 } else { 9760 // Substitute 'void' for the 'auto' in the type. 9761 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9762 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc(); 9763 Context.adjustDeducedFunctionResultType( 9764 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9765 } 9766 } 9767 9768 // The only way to be included in UndefinedButUsed is if there is an 9769 // ODR use before the definition. Avoid the expensive map lookup if this 9770 // is the first declaration. 9771 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9772 if (!FD->isExternallyVisible()) 9773 UndefinedButUsed.erase(FD); 9774 else if (FD->isInlined() && 9775 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9776 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9777 UndefinedButUsed.erase(FD); 9778 } 9779 9780 // If the function implicitly returns zero (like 'main') or is naked, 9781 // don't complain about missing return statements. 9782 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9783 WP.disableCheckFallThrough(); 9784 9785 // MSVC permits the use of pure specifier (=0) on function definition, 9786 // defined at class scope, warn about this non standard construct. 9787 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9788 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9789 9790 if (!FD->isInvalidDecl()) { 9791 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9792 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9793 FD->getResultType(), FD); 9794 9795 // If this is a constructor, we need a vtable. 9796 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9797 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9798 9799 // Try to apply the named return value optimization. We have to check 9800 // if we can do this here because lambdas keep return statements around 9801 // to deduce an implicit return type. 9802 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 9803 !FD->isDependentContext()) 9804 computeNRVO(Body, getCurFunction()); 9805 } 9806 9807 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9808 "Function parsing confused"); 9809 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9810 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9811 MD->setBody(Body); 9812 if (!MD->isInvalidDecl()) { 9813 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9814 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9815 MD->getResultType(), MD); 9816 9817 if (Body) 9818 computeNRVO(Body, getCurFunction()); 9819 } 9820 if (getCurFunction()->ObjCShouldCallSuper) { 9821 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9822 << MD->getSelector().getAsString(); 9823 getCurFunction()->ObjCShouldCallSuper = false; 9824 } 9825 } else { 9826 return 0; 9827 } 9828 9829 assert(!getCurFunction()->ObjCShouldCallSuper && 9830 "This should only be set for ObjC methods, which should have been " 9831 "handled in the block above."); 9832 9833 // Verify and clean out per-function state. 9834 if (Body) { 9835 // C++ constructors that have function-try-blocks can't have return 9836 // statements in the handlers of that block. (C++ [except.handle]p14) 9837 // Verify this. 9838 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9839 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9840 9841 // Verify that gotos and switch cases don't jump into scopes illegally. 9842 if (getCurFunction()->NeedsScopeChecking() && 9843 !dcl->isInvalidDecl() && 9844 !hasAnyUnrecoverableErrorsInThisFunction() && 9845 !PP.isCodeCompletionEnabled()) 9846 DiagnoseInvalidJumps(Body); 9847 9848 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9849 if (!Destructor->getParent()->isDependentType()) 9850 CheckDestructor(Destructor); 9851 9852 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9853 Destructor->getParent()); 9854 } 9855 9856 // If any errors have occurred, clear out any temporaries that may have 9857 // been leftover. This ensures that these temporaries won't be picked up for 9858 // deletion in some later function. 9859 if (PP.getDiagnostics().hasErrorOccurred() || 9860 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9861 DiscardCleanupsInEvaluationContext(); 9862 } 9863 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9864 !isa<FunctionTemplateDecl>(dcl)) { 9865 // Since the body is valid, issue any analysis-based warnings that are 9866 // enabled. 9867 ActivePolicy = &WP; 9868 } 9869 9870 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9871 (!CheckConstexprFunctionDecl(FD) || 9872 !CheckConstexprFunctionBody(FD, Body))) 9873 FD->setInvalidDecl(); 9874 9875 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9876 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9877 assert(MaybeODRUseExprs.empty() && 9878 "Leftover expressions for odr-use checking"); 9879 } 9880 9881 if (!IsInstantiation) 9882 PopDeclContext(); 9883 9884 PopFunctionScopeInfo(ActivePolicy, dcl); 9885 // If any errors have occurred, clear out any temporaries that may have 9886 // been leftover. This ensures that these temporaries won't be picked up for 9887 // deletion in some later function. 9888 if (getDiagnostics().hasErrorOccurred()) { 9889 DiscardCleanupsInEvaluationContext(); 9890 } 9891 9892 return dcl; 9893} 9894 9895 9896/// When we finish delayed parsing of an attribute, we must attach it to the 9897/// relevant Decl. 9898void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9899 ParsedAttributes &Attrs) { 9900 // Always attach attributes to the underlying decl. 9901 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9902 D = TD->getTemplatedDecl(); 9903 ProcessDeclAttributeList(S, D, Attrs.getList()); 9904 9905 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9906 if (Method->isStatic()) 9907 checkThisInStaticMemberFunctionAttributes(Method); 9908} 9909 9910 9911/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9912/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9913NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9914 IdentifierInfo &II, Scope *S) { 9915 // Before we produce a declaration for an implicitly defined 9916 // function, see whether there was a locally-scoped declaration of 9917 // this name as a function or variable. If so, use that 9918 // (non-visible) declaration, and complain about it. 9919 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9920 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9921 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9922 return ExternCPrev; 9923 } 9924 9925 // Extension in C99. Legal in C90, but warn about it. 9926 unsigned diag_id; 9927 if (II.getName().startswith("__builtin_")) 9928 diag_id = diag::warn_builtin_unknown; 9929 else if (getLangOpts().C99) 9930 diag_id = diag::ext_implicit_function_decl; 9931 else 9932 diag_id = diag::warn_implicit_function_decl; 9933 Diag(Loc, diag_id) << &II; 9934 9935 // Because typo correction is expensive, only do it if the implicit 9936 // function declaration is going to be treated as an error. 9937 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9938 TypoCorrection Corrected; 9939 DeclFilterCCC<FunctionDecl> Validator; 9940 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9941 LookupOrdinaryName, S, 0, Validator))) 9942 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9943 /*ErrorRecovery*/false); 9944 } 9945 9946 // Set a Declarator for the implicit definition: int foo(); 9947 const char *Dummy; 9948 AttributeFactory attrFactory; 9949 DeclSpec DS(attrFactory); 9950 unsigned DiagID; 9951 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 9952 (void)Error; // Silence warning. 9953 assert(!Error && "Error setting up implicit decl!"); 9954 SourceLocation NoLoc; 9955 Declarator D(DS, Declarator::BlockContext); 9956 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9957 /*IsAmbiguous=*/false, 9958 /*RParenLoc=*/NoLoc, 9959 /*ArgInfo=*/0, 9960 /*NumArgs=*/0, 9961 /*EllipsisLoc=*/NoLoc, 9962 /*RParenLoc=*/NoLoc, 9963 /*TypeQuals=*/0, 9964 /*RefQualifierIsLvalueRef=*/true, 9965 /*RefQualifierLoc=*/NoLoc, 9966 /*ConstQualifierLoc=*/NoLoc, 9967 /*VolatileQualifierLoc=*/NoLoc, 9968 /*MutableLoc=*/NoLoc, 9969 EST_None, 9970 /*ESpecLoc=*/NoLoc, 9971 /*Exceptions=*/0, 9972 /*ExceptionRanges=*/0, 9973 /*NumExceptions=*/0, 9974 /*NoexceptExpr=*/0, 9975 Loc, Loc, D), 9976 DS.getAttributes(), 9977 SourceLocation()); 9978 D.SetIdentifier(&II, Loc); 9979 9980 // Insert this function into translation-unit scope. 9981 9982 DeclContext *PrevDC = CurContext; 9983 CurContext = Context.getTranslationUnitDecl(); 9984 9985 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9986 FD->setImplicit(); 9987 9988 CurContext = PrevDC; 9989 9990 AddKnownFunctionAttributes(FD); 9991 9992 return FD; 9993} 9994 9995/// \brief Adds any function attributes that we know a priori based on 9996/// the declaration of this function. 9997/// 9998/// These attributes can apply both to implicitly-declared builtins 9999/// (like __builtin___printf_chk) or to library-declared functions 10000/// like NSLog or printf. 10001/// 10002/// We need to check for duplicate attributes both here and where user-written 10003/// attributes are applied to declarations. 10004void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10005 if (FD->isInvalidDecl()) 10006 return; 10007 10008 // If this is a built-in function, map its builtin attributes to 10009 // actual attributes. 10010 if (unsigned BuiltinID = FD->getBuiltinID()) { 10011 // Handle printf-formatting attributes. 10012 unsigned FormatIdx; 10013 bool HasVAListArg; 10014 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10015 if (!FD->getAttr<FormatAttr>()) { 10016 const char *fmt = "printf"; 10017 unsigned int NumParams = FD->getNumParams(); 10018 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10019 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10020 fmt = "NSString"; 10021 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10022 &Context.Idents.get(fmt), 10023 FormatIdx+1, 10024 HasVAListArg ? 0 : FormatIdx+2)); 10025 } 10026 } 10027 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10028 HasVAListArg)) { 10029 if (!FD->getAttr<FormatAttr>()) 10030 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10031 &Context.Idents.get("scanf"), 10032 FormatIdx+1, 10033 HasVAListArg ? 0 : FormatIdx+2)); 10034 } 10035 10036 // Mark const if we don't care about errno and that is the only 10037 // thing preventing the function from being const. This allows 10038 // IRgen to use LLVM intrinsics for such functions. 10039 if (!getLangOpts().MathErrno && 10040 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10041 if (!FD->getAttr<ConstAttr>()) 10042 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10043 } 10044 10045 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10046 !FD->getAttr<ReturnsTwiceAttr>()) 10047 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 10048 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 10049 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 10050 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 10051 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10052 } 10053 10054 IdentifierInfo *Name = FD->getIdentifier(); 10055 if (!Name) 10056 return; 10057 if ((!getLangOpts().CPlusPlus && 10058 FD->getDeclContext()->isTranslationUnit()) || 10059 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10060 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10061 LinkageSpecDecl::lang_c)) { 10062 // Okay: this could be a libc/libm/Objective-C function we know 10063 // about. 10064 } else 10065 return; 10066 10067 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10068 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10069 // target-specific builtins, perhaps? 10070 if (!FD->getAttr<FormatAttr>()) 10071 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10072 &Context.Idents.get("printf"), 2, 10073 Name->isStr("vasprintf") ? 0 : 3)); 10074 } 10075 10076 if (Name->isStr("__CFStringMakeConstantString")) { 10077 // We already have a __builtin___CFStringMakeConstantString, 10078 // but builds that use -fno-constant-cfstrings don't go through that. 10079 if (!FD->getAttr<FormatArgAttr>()) 10080 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 10081 } 10082} 10083 10084TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10085 TypeSourceInfo *TInfo) { 10086 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10087 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10088 10089 if (!TInfo) { 10090 assert(D.isInvalidType() && "no declarator info for valid type"); 10091 TInfo = Context.getTrivialTypeSourceInfo(T); 10092 } 10093 10094 // Scope manipulation handled by caller. 10095 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10096 D.getLocStart(), 10097 D.getIdentifierLoc(), 10098 D.getIdentifier(), 10099 TInfo); 10100 10101 // Bail out immediately if we have an invalid declaration. 10102 if (D.isInvalidType()) { 10103 NewTD->setInvalidDecl(); 10104 return NewTD; 10105 } 10106 10107 if (D.getDeclSpec().isModulePrivateSpecified()) { 10108 if (CurContext->isFunctionOrMethod()) 10109 Diag(NewTD->getLocation(), diag::err_module_private_local) 10110 << 2 << NewTD->getDeclName() 10111 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10112 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10113 else 10114 NewTD->setModulePrivate(); 10115 } 10116 10117 // C++ [dcl.typedef]p8: 10118 // If the typedef declaration defines an unnamed class (or 10119 // enum), the first typedef-name declared by the declaration 10120 // to be that class type (or enum type) is used to denote the 10121 // class type (or enum type) for linkage purposes only. 10122 // We need to check whether the type was declared in the declaration. 10123 switch (D.getDeclSpec().getTypeSpecType()) { 10124 case TST_enum: 10125 case TST_struct: 10126 case TST_interface: 10127 case TST_union: 10128 case TST_class: { 10129 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10130 10131 // Do nothing if the tag is not anonymous or already has an 10132 // associated typedef (from an earlier typedef in this decl group). 10133 if (tagFromDeclSpec->getIdentifier()) break; 10134 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10135 10136 // A well-formed anonymous tag must always be a TUK_Definition. 10137 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10138 10139 // The type must match the tag exactly; no qualifiers allowed. 10140 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10141 break; 10142 10143 // Otherwise, set this is the anon-decl typedef for the tag. 10144 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10145 break; 10146 } 10147 10148 default: 10149 break; 10150 } 10151 10152 return NewTD; 10153} 10154 10155 10156/// \brief Check that this is a valid underlying type for an enum declaration. 10157bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10158 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10159 QualType T = TI->getType(); 10160 10161 if (T->isDependentType()) 10162 return false; 10163 10164 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10165 if (BT->isInteger()) 10166 return false; 10167 10168 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10169 return true; 10170} 10171 10172/// Check whether this is a valid redeclaration of a previous enumeration. 10173/// \return true if the redeclaration was invalid. 10174bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10175 QualType EnumUnderlyingTy, 10176 const EnumDecl *Prev) { 10177 bool IsFixed = !EnumUnderlyingTy.isNull(); 10178 10179 if (IsScoped != Prev->isScoped()) { 10180 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10181 << Prev->isScoped(); 10182 Diag(Prev->getLocation(), diag::note_previous_use); 10183 return true; 10184 } 10185 10186 if (IsFixed && Prev->isFixed()) { 10187 if (!EnumUnderlyingTy->isDependentType() && 10188 !Prev->getIntegerType()->isDependentType() && 10189 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10190 Prev->getIntegerType())) { 10191 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10192 << EnumUnderlyingTy << Prev->getIntegerType(); 10193 Diag(Prev->getLocation(), diag::note_previous_use); 10194 return true; 10195 } 10196 } else if (IsFixed != Prev->isFixed()) { 10197 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10198 << Prev->isFixed(); 10199 Diag(Prev->getLocation(), diag::note_previous_use); 10200 return true; 10201 } 10202 10203 return false; 10204} 10205 10206/// \brief Get diagnostic %select index for tag kind for 10207/// redeclaration diagnostic message. 10208/// WARNING: Indexes apply to particular diagnostics only! 10209/// 10210/// \returns diagnostic %select index. 10211static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10212 switch (Tag) { 10213 case TTK_Struct: return 0; 10214 case TTK_Interface: return 1; 10215 case TTK_Class: return 2; 10216 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10217 } 10218} 10219 10220/// \brief Determine if tag kind is a class-key compatible with 10221/// class for redeclaration (class, struct, or __interface). 10222/// 10223/// \returns true iff the tag kind is compatible. 10224static bool isClassCompatTagKind(TagTypeKind Tag) 10225{ 10226 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10227} 10228 10229/// \brief Determine whether a tag with a given kind is acceptable 10230/// as a redeclaration of the given tag declaration. 10231/// 10232/// \returns true if the new tag kind is acceptable, false otherwise. 10233bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10234 TagTypeKind NewTag, bool isDefinition, 10235 SourceLocation NewTagLoc, 10236 const IdentifierInfo &Name) { 10237 // C++ [dcl.type.elab]p3: 10238 // The class-key or enum keyword present in the 10239 // elaborated-type-specifier shall agree in kind with the 10240 // declaration to which the name in the elaborated-type-specifier 10241 // refers. This rule also applies to the form of 10242 // elaborated-type-specifier that declares a class-name or 10243 // friend class since it can be construed as referring to the 10244 // definition of the class. Thus, in any 10245 // elaborated-type-specifier, the enum keyword shall be used to 10246 // refer to an enumeration (7.2), the union class-key shall be 10247 // used to refer to a union (clause 9), and either the class or 10248 // struct class-key shall be used to refer to a class (clause 9) 10249 // declared using the class or struct class-key. 10250 TagTypeKind OldTag = Previous->getTagKind(); 10251 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10252 if (OldTag == NewTag) 10253 return true; 10254 10255 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10256 // Warn about the struct/class tag mismatch. 10257 bool isTemplate = false; 10258 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10259 isTemplate = Record->getDescribedClassTemplate(); 10260 10261 if (!ActiveTemplateInstantiations.empty()) { 10262 // In a template instantiation, do not offer fix-its for tag mismatches 10263 // since they usually mess up the template instead of fixing the problem. 10264 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10265 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10266 << getRedeclDiagFromTagKind(OldTag); 10267 return true; 10268 } 10269 10270 if (isDefinition) { 10271 // On definitions, check previous tags and issue a fix-it for each 10272 // one that doesn't match the current tag. 10273 if (Previous->getDefinition()) { 10274 // Don't suggest fix-its for redefinitions. 10275 return true; 10276 } 10277 10278 bool previousMismatch = false; 10279 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10280 E(Previous->redecls_end()); I != E; ++I) { 10281 if (I->getTagKind() != NewTag) { 10282 if (!previousMismatch) { 10283 previousMismatch = true; 10284 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10285 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10286 << getRedeclDiagFromTagKind(I->getTagKind()); 10287 } 10288 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10289 << getRedeclDiagFromTagKind(NewTag) 10290 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10291 TypeWithKeyword::getTagTypeKindName(NewTag)); 10292 } 10293 } 10294 return true; 10295 } 10296 10297 // Check for a previous definition. If current tag and definition 10298 // are same type, do nothing. If no definition, but disagree with 10299 // with previous tag type, give a warning, but no fix-it. 10300 const TagDecl *Redecl = Previous->getDefinition() ? 10301 Previous->getDefinition() : Previous; 10302 if (Redecl->getTagKind() == NewTag) { 10303 return true; 10304 } 10305 10306 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10307 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10308 << getRedeclDiagFromTagKind(OldTag); 10309 Diag(Redecl->getLocation(), diag::note_previous_use); 10310 10311 // If there is a previous defintion, suggest a fix-it. 10312 if (Previous->getDefinition()) { 10313 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10314 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10315 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10316 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10317 } 10318 10319 return true; 10320 } 10321 return false; 10322} 10323 10324/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10325/// former case, Name will be non-null. In the later case, Name will be null. 10326/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10327/// reference/declaration/definition of a tag. 10328Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10329 SourceLocation KWLoc, CXXScopeSpec &SS, 10330 IdentifierInfo *Name, SourceLocation NameLoc, 10331 AttributeList *Attr, AccessSpecifier AS, 10332 SourceLocation ModulePrivateLoc, 10333 MultiTemplateParamsArg TemplateParameterLists, 10334 bool &OwnedDecl, bool &IsDependent, 10335 SourceLocation ScopedEnumKWLoc, 10336 bool ScopedEnumUsesClassTag, 10337 TypeResult UnderlyingType) { 10338 // If this is not a definition, it must have a name. 10339 IdentifierInfo *OrigName = Name; 10340 assert((Name != 0 || TUK == TUK_Definition) && 10341 "Nameless record must be a definition!"); 10342 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10343 10344 OwnedDecl = false; 10345 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10346 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10347 10348 // FIXME: Check explicit specializations more carefully. 10349 bool isExplicitSpecialization = false; 10350 bool Invalid = false; 10351 10352 // We only need to do this matching if we have template parameters 10353 // or a scope specifier, which also conveniently avoids this work 10354 // for non-C++ cases. 10355 if (TemplateParameterLists.size() > 0 || 10356 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10357 if (TemplateParameterList *TemplateParams = 10358 MatchTemplateParametersToScopeSpecifier( 10359 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10360 isExplicitSpecialization, Invalid)) { 10361 if (Kind == TTK_Enum) { 10362 Diag(KWLoc, diag::err_enum_template); 10363 return 0; 10364 } 10365 10366 if (TemplateParams->size() > 0) { 10367 // This is a declaration or definition of a class template (which may 10368 // be a member of another template). 10369 10370 if (Invalid) 10371 return 0; 10372 10373 OwnedDecl = false; 10374 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10375 SS, Name, NameLoc, Attr, 10376 TemplateParams, AS, 10377 ModulePrivateLoc, 10378 TemplateParameterLists.size()-1, 10379 TemplateParameterLists.data()); 10380 return Result.get(); 10381 } else { 10382 // The "template<>" header is extraneous. 10383 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10384 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10385 isExplicitSpecialization = true; 10386 } 10387 } 10388 } 10389 10390 // Figure out the underlying type if this a enum declaration. We need to do 10391 // this early, because it's needed to detect if this is an incompatible 10392 // redeclaration. 10393 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10394 10395 if (Kind == TTK_Enum) { 10396 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10397 // No underlying type explicitly specified, or we failed to parse the 10398 // type, default to int. 10399 EnumUnderlying = Context.IntTy.getTypePtr(); 10400 else if (UnderlyingType.get()) { 10401 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10402 // integral type; any cv-qualification is ignored. 10403 TypeSourceInfo *TI = 0; 10404 GetTypeFromParser(UnderlyingType.get(), &TI); 10405 EnumUnderlying = TI; 10406 10407 if (CheckEnumUnderlyingType(TI)) 10408 // Recover by falling back to int. 10409 EnumUnderlying = Context.IntTy.getTypePtr(); 10410 10411 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10412 UPPC_FixedUnderlyingType)) 10413 EnumUnderlying = Context.IntTy.getTypePtr(); 10414 10415 } else if (getLangOpts().MicrosoftMode) 10416 // Microsoft enums are always of int type. 10417 EnumUnderlying = Context.IntTy.getTypePtr(); 10418 } 10419 10420 DeclContext *SearchDC = CurContext; 10421 DeclContext *DC = CurContext; 10422 bool isStdBadAlloc = false; 10423 10424 RedeclarationKind Redecl = ForRedeclaration; 10425 if (TUK == TUK_Friend || TUK == TUK_Reference) 10426 Redecl = NotForRedeclaration; 10427 10428 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10429 bool FriendSawTagOutsideEnclosingNamespace = false; 10430 if (Name && SS.isNotEmpty()) { 10431 // We have a nested-name tag ('struct foo::bar'). 10432 10433 // Check for invalid 'foo::'. 10434 if (SS.isInvalid()) { 10435 Name = 0; 10436 goto CreateNewDecl; 10437 } 10438 10439 // If this is a friend or a reference to a class in a dependent 10440 // context, don't try to make a decl for it. 10441 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10442 DC = computeDeclContext(SS, false); 10443 if (!DC) { 10444 IsDependent = true; 10445 return 0; 10446 } 10447 } else { 10448 DC = computeDeclContext(SS, true); 10449 if (!DC) { 10450 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10451 << SS.getRange(); 10452 return 0; 10453 } 10454 } 10455 10456 if (RequireCompleteDeclContext(SS, DC)) 10457 return 0; 10458 10459 SearchDC = DC; 10460 // Look-up name inside 'foo::'. 10461 LookupQualifiedName(Previous, DC); 10462 10463 if (Previous.isAmbiguous()) 10464 return 0; 10465 10466 if (Previous.empty()) { 10467 // Name lookup did not find anything. However, if the 10468 // nested-name-specifier refers to the current instantiation, 10469 // and that current instantiation has any dependent base 10470 // classes, we might find something at instantiation time: treat 10471 // this as a dependent elaborated-type-specifier. 10472 // But this only makes any sense for reference-like lookups. 10473 if (Previous.wasNotFoundInCurrentInstantiation() && 10474 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10475 IsDependent = true; 10476 return 0; 10477 } 10478 10479 // A tag 'foo::bar' must already exist. 10480 Diag(NameLoc, diag::err_not_tag_in_scope) 10481 << Kind << Name << DC << SS.getRange(); 10482 Name = 0; 10483 Invalid = true; 10484 goto CreateNewDecl; 10485 } 10486 } else if (Name) { 10487 // If this is a named struct, check to see if there was a previous forward 10488 // declaration or definition. 10489 // FIXME: We're looking into outer scopes here, even when we 10490 // shouldn't be. Doing so can result in ambiguities that we 10491 // shouldn't be diagnosing. 10492 LookupName(Previous, S); 10493 10494 // When declaring or defining a tag, ignore ambiguities introduced 10495 // by types using'ed into this scope. 10496 if (Previous.isAmbiguous() && 10497 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10498 LookupResult::Filter F = Previous.makeFilter(); 10499 while (F.hasNext()) { 10500 NamedDecl *ND = F.next(); 10501 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10502 F.erase(); 10503 } 10504 F.done(); 10505 } 10506 10507 // C++11 [namespace.memdef]p3: 10508 // If the name in a friend declaration is neither qualified nor 10509 // a template-id and the declaration is a function or an 10510 // elaborated-type-specifier, the lookup to determine whether 10511 // the entity has been previously declared shall not consider 10512 // any scopes outside the innermost enclosing namespace. 10513 // 10514 // Does it matter that this should be by scope instead of by 10515 // semantic context? 10516 if (!Previous.empty() && TUK == TUK_Friend) { 10517 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10518 LookupResult::Filter F = Previous.makeFilter(); 10519 while (F.hasNext()) { 10520 NamedDecl *ND = F.next(); 10521 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10522 if (DC->isFileContext() && 10523 !EnclosingNS->Encloses(ND->getDeclContext())) { 10524 F.erase(); 10525 FriendSawTagOutsideEnclosingNamespace = true; 10526 } 10527 } 10528 F.done(); 10529 } 10530 10531 // Note: there used to be some attempt at recovery here. 10532 if (Previous.isAmbiguous()) 10533 return 0; 10534 10535 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10536 // FIXME: This makes sure that we ignore the contexts associated 10537 // with C structs, unions, and enums when looking for a matching 10538 // tag declaration or definition. See the similar lookup tweak 10539 // in Sema::LookupName; is there a better way to deal with this? 10540 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10541 SearchDC = SearchDC->getParent(); 10542 } 10543 } else if (S->isFunctionPrototypeScope()) { 10544 // If this is an enum declaration in function prototype scope, set its 10545 // initial context to the translation unit. 10546 // FIXME: [citation needed] 10547 SearchDC = Context.getTranslationUnitDecl(); 10548 } 10549 10550 if (Previous.isSingleResult() && 10551 Previous.getFoundDecl()->isTemplateParameter()) { 10552 // Maybe we will complain about the shadowed template parameter. 10553 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10554 // Just pretend that we didn't see the previous declaration. 10555 Previous.clear(); 10556 } 10557 10558 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10559 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10560 // This is a declaration of or a reference to "std::bad_alloc". 10561 isStdBadAlloc = true; 10562 10563 if (Previous.empty() && StdBadAlloc) { 10564 // std::bad_alloc has been implicitly declared (but made invisible to 10565 // name lookup). Fill in this implicit declaration as the previous 10566 // declaration, so that the declarations get chained appropriately. 10567 Previous.addDecl(getStdBadAlloc()); 10568 } 10569 } 10570 10571 // If we didn't find a previous declaration, and this is a reference 10572 // (or friend reference), move to the correct scope. In C++, we 10573 // also need to do a redeclaration lookup there, just in case 10574 // there's a shadow friend decl. 10575 if (Name && Previous.empty() && 10576 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10577 if (Invalid) goto CreateNewDecl; 10578 assert(SS.isEmpty()); 10579 10580 if (TUK == TUK_Reference) { 10581 // C++ [basic.scope.pdecl]p5: 10582 // -- for an elaborated-type-specifier of the form 10583 // 10584 // class-key identifier 10585 // 10586 // if the elaborated-type-specifier is used in the 10587 // decl-specifier-seq or parameter-declaration-clause of a 10588 // function defined in namespace scope, the identifier is 10589 // declared as a class-name in the namespace that contains 10590 // the declaration; otherwise, except as a friend 10591 // declaration, the identifier is declared in the smallest 10592 // non-class, non-function-prototype scope that contains the 10593 // declaration. 10594 // 10595 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10596 // C structs and unions. 10597 // 10598 // It is an error in C++ to declare (rather than define) an enum 10599 // type, including via an elaborated type specifier. We'll 10600 // diagnose that later; for now, declare the enum in the same 10601 // scope as we would have picked for any other tag type. 10602 // 10603 // GNU C also supports this behavior as part of its incomplete 10604 // enum types extension, while GNU C++ does not. 10605 // 10606 // Find the context where we'll be declaring the tag. 10607 // FIXME: We would like to maintain the current DeclContext as the 10608 // lexical context, 10609 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10610 SearchDC = SearchDC->getParent(); 10611 10612 // Find the scope where we'll be declaring the tag. 10613 while (S->isClassScope() || 10614 (getLangOpts().CPlusPlus && 10615 S->isFunctionPrototypeScope()) || 10616 ((S->getFlags() & Scope::DeclScope) == 0) || 10617 (S->getEntity() && S->getEntity()->isTransparentContext())) 10618 S = S->getParent(); 10619 } else { 10620 assert(TUK == TUK_Friend); 10621 // C++ [namespace.memdef]p3: 10622 // If a friend declaration in a non-local class first declares a 10623 // class or function, the friend class or function is a member of 10624 // the innermost enclosing namespace. 10625 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10626 } 10627 10628 // In C++, we need to do a redeclaration lookup to properly 10629 // diagnose some problems. 10630 if (getLangOpts().CPlusPlus) { 10631 Previous.setRedeclarationKind(ForRedeclaration); 10632 LookupQualifiedName(Previous, SearchDC); 10633 } 10634 } 10635 10636 if (!Previous.empty()) { 10637 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 10638 10639 // It's okay to have a tag decl in the same scope as a typedef 10640 // which hides a tag decl in the same scope. Finding this 10641 // insanity with a redeclaration lookup can only actually happen 10642 // in C++. 10643 // 10644 // This is also okay for elaborated-type-specifiers, which is 10645 // technically forbidden by the current standard but which is 10646 // okay according to the likely resolution of an open issue; 10647 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10648 if (getLangOpts().CPlusPlus) { 10649 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10650 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10651 TagDecl *Tag = TT->getDecl(); 10652 if (Tag->getDeclName() == Name && 10653 Tag->getDeclContext()->getRedeclContext() 10654 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10655 PrevDecl = Tag; 10656 Previous.clear(); 10657 Previous.addDecl(Tag); 10658 Previous.resolveKind(); 10659 } 10660 } 10661 } 10662 } 10663 10664 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10665 // If this is a use of a previous tag, or if the tag is already declared 10666 // in the same scope (so that the definition/declaration completes or 10667 // rementions the tag), reuse the decl. 10668 if (TUK == TUK_Reference || TUK == TUK_Friend || 10669 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 10670 // Make sure that this wasn't declared as an enum and now used as a 10671 // struct or something similar. 10672 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10673 TUK == TUK_Definition, KWLoc, 10674 *Name)) { 10675 bool SafeToContinue 10676 = (PrevTagDecl->getTagKind() != TTK_Enum && 10677 Kind != TTK_Enum); 10678 if (SafeToContinue) 10679 Diag(KWLoc, diag::err_use_with_wrong_tag) 10680 << Name 10681 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10682 PrevTagDecl->getKindName()); 10683 else 10684 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10685 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10686 10687 if (SafeToContinue) 10688 Kind = PrevTagDecl->getTagKind(); 10689 else { 10690 // Recover by making this an anonymous redefinition. 10691 Name = 0; 10692 Previous.clear(); 10693 Invalid = true; 10694 } 10695 } 10696 10697 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10698 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10699 10700 // If this is an elaborated-type-specifier for a scoped enumeration, 10701 // the 'class' keyword is not necessary and not permitted. 10702 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10703 if (ScopedEnum) 10704 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10705 << PrevEnum->isScoped() 10706 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10707 return PrevTagDecl; 10708 } 10709 10710 QualType EnumUnderlyingTy; 10711 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10712 EnumUnderlyingTy = TI->getType(); 10713 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10714 EnumUnderlyingTy = QualType(T, 0); 10715 10716 // All conflicts with previous declarations are recovered by 10717 // returning the previous declaration, unless this is a definition, 10718 // in which case we want the caller to bail out. 10719 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10720 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10721 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10722 } 10723 10724 // C++11 [class.mem]p1: 10725 // A member shall not be declared twice in the member-specification, 10726 // except that a nested class or member class template can be declared 10727 // and then later defined. 10728 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10729 S->isDeclScope(PrevDecl)) { 10730 Diag(NameLoc, diag::ext_member_redeclared); 10731 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10732 } 10733 10734 if (!Invalid) { 10735 // If this is a use, just return the declaration we found. 10736 10737 // FIXME: In the future, return a variant or some other clue 10738 // for the consumer of this Decl to know it doesn't own it. 10739 // For our current ASTs this shouldn't be a problem, but will 10740 // need to be changed with DeclGroups. 10741 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10742 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10743 return PrevTagDecl; 10744 10745 // Diagnose attempts to redefine a tag. 10746 if (TUK == TUK_Definition) { 10747 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10748 // If we're defining a specialization and the previous definition 10749 // is from an implicit instantiation, don't emit an error 10750 // here; we'll catch this in the general case below. 10751 bool IsExplicitSpecializationAfterInstantiation = false; 10752 if (isExplicitSpecialization) { 10753 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10754 IsExplicitSpecializationAfterInstantiation = 10755 RD->getTemplateSpecializationKind() != 10756 TSK_ExplicitSpecialization; 10757 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10758 IsExplicitSpecializationAfterInstantiation = 10759 ED->getTemplateSpecializationKind() != 10760 TSK_ExplicitSpecialization; 10761 } 10762 10763 if (!IsExplicitSpecializationAfterInstantiation) { 10764 // A redeclaration in function prototype scope in C isn't 10765 // visible elsewhere, so merely issue a warning. 10766 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10767 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10768 else 10769 Diag(NameLoc, diag::err_redefinition) << Name; 10770 Diag(Def->getLocation(), diag::note_previous_definition); 10771 // If this is a redefinition, recover by making this 10772 // struct be anonymous, which will make any later 10773 // references get the previous definition. 10774 Name = 0; 10775 Previous.clear(); 10776 Invalid = true; 10777 } 10778 } else { 10779 // If the type is currently being defined, complain 10780 // about a nested redefinition. 10781 const TagType *Tag 10782 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10783 if (Tag->isBeingDefined()) { 10784 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10785 Diag(PrevTagDecl->getLocation(), 10786 diag::note_previous_definition); 10787 Name = 0; 10788 Previous.clear(); 10789 Invalid = true; 10790 } 10791 } 10792 10793 // Okay, this is definition of a previously declared or referenced 10794 // tag PrevDecl. We're going to create a new Decl for it. 10795 } 10796 } 10797 // If we get here we have (another) forward declaration or we 10798 // have a definition. Just create a new decl. 10799 10800 } else { 10801 // If we get here, this is a definition of a new tag type in a nested 10802 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10803 // new decl/type. We set PrevDecl to NULL so that the entities 10804 // have distinct types. 10805 Previous.clear(); 10806 } 10807 // If we get here, we're going to create a new Decl. If PrevDecl 10808 // is non-NULL, it's a definition of the tag declared by 10809 // PrevDecl. If it's NULL, we have a new definition. 10810 10811 10812 // Otherwise, PrevDecl is not a tag, but was found with tag 10813 // lookup. This is only actually possible in C++, where a few 10814 // things like templates still live in the tag namespace. 10815 } else { 10816 // Use a better diagnostic if an elaborated-type-specifier 10817 // found the wrong kind of type on the first 10818 // (non-redeclaration) lookup. 10819 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10820 !Previous.isForRedeclaration()) { 10821 unsigned Kind = 0; 10822 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10823 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10824 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10825 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10826 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10827 Invalid = true; 10828 10829 // Otherwise, only diagnose if the declaration is in scope. 10830 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10831 isExplicitSpecialization)) { 10832 // do nothing 10833 10834 // Diagnose implicit declarations introduced by elaborated types. 10835 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10836 unsigned Kind = 0; 10837 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10838 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10839 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10840 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10841 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10842 Invalid = true; 10843 10844 // Otherwise it's a declaration. Call out a particularly common 10845 // case here. 10846 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10847 unsigned Kind = 0; 10848 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10849 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10850 << Name << Kind << TND->getUnderlyingType(); 10851 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10852 Invalid = true; 10853 10854 // Otherwise, diagnose. 10855 } else { 10856 // The tag name clashes with something else in the target scope, 10857 // issue an error and recover by making this tag be anonymous. 10858 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10859 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10860 Name = 0; 10861 Invalid = true; 10862 } 10863 10864 // The existing declaration isn't relevant to us; we're in a 10865 // new scope, so clear out the previous declaration. 10866 Previous.clear(); 10867 } 10868 } 10869 10870CreateNewDecl: 10871 10872 TagDecl *PrevDecl = 0; 10873 if (Previous.isSingleResult()) 10874 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10875 10876 // If there is an identifier, use the location of the identifier as the 10877 // location of the decl, otherwise use the location of the struct/union 10878 // keyword. 10879 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10880 10881 // Otherwise, create a new declaration. If there is a previous 10882 // declaration of the same entity, the two will be linked via 10883 // PrevDecl. 10884 TagDecl *New; 10885 10886 bool IsForwardReference = false; 10887 if (Kind == TTK_Enum) { 10888 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10889 // enum X { A, B, C } D; D should chain to X. 10890 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10891 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10892 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10893 // If this is an undefined enum, warn. 10894 if (TUK != TUK_Definition && !Invalid) { 10895 TagDecl *Def; 10896 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10897 cast<EnumDecl>(New)->isFixed()) { 10898 // C++0x: 7.2p2: opaque-enum-declaration. 10899 // Conflicts are diagnosed above. Do nothing. 10900 } 10901 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10902 Diag(Loc, diag::ext_forward_ref_enum_def) 10903 << New; 10904 Diag(Def->getLocation(), diag::note_previous_definition); 10905 } else { 10906 unsigned DiagID = diag::ext_forward_ref_enum; 10907 if (getLangOpts().MicrosoftMode) 10908 DiagID = diag::ext_ms_forward_ref_enum; 10909 else if (getLangOpts().CPlusPlus) 10910 DiagID = diag::err_forward_ref_enum; 10911 Diag(Loc, DiagID); 10912 10913 // If this is a forward-declared reference to an enumeration, make a 10914 // note of it; we won't actually be introducing the declaration into 10915 // the declaration context. 10916 if (TUK == TUK_Reference) 10917 IsForwardReference = true; 10918 } 10919 } 10920 10921 if (EnumUnderlying) { 10922 EnumDecl *ED = cast<EnumDecl>(New); 10923 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10924 ED->setIntegerTypeSourceInfo(TI); 10925 else 10926 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10927 ED->setPromotionType(ED->getIntegerType()); 10928 } 10929 10930 } else { 10931 // struct/union/class 10932 10933 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10934 // struct X { int A; } D; D should chain to X. 10935 if (getLangOpts().CPlusPlus) { 10936 // FIXME: Look for a way to use RecordDecl for simple structs. 10937 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10938 cast_or_null<CXXRecordDecl>(PrevDecl)); 10939 10940 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10941 StdBadAlloc = cast<CXXRecordDecl>(New); 10942 } else 10943 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10944 cast_or_null<RecordDecl>(PrevDecl)); 10945 } 10946 10947 // Maybe add qualifier info. 10948 if (SS.isNotEmpty()) { 10949 if (SS.isSet()) { 10950 // If this is either a declaration or a definition, check the 10951 // nested-name-specifier against the current context. We don't do this 10952 // for explicit specializations, because they have similar checking 10953 // (with more specific diagnostics) in the call to 10954 // CheckMemberSpecialization, below. 10955 if (!isExplicitSpecialization && 10956 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10957 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10958 Invalid = true; 10959 10960 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10961 if (TemplateParameterLists.size() > 0) { 10962 New->setTemplateParameterListsInfo(Context, 10963 TemplateParameterLists.size(), 10964 TemplateParameterLists.data()); 10965 } 10966 } 10967 else 10968 Invalid = true; 10969 } 10970 10971 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 10972 // Add alignment attributes if necessary; these attributes are checked when 10973 // the ASTContext lays out the structure. 10974 // 10975 // It is important for implementing the correct semantics that this 10976 // happen here (in act on tag decl). The #pragma pack stack is 10977 // maintained as a result of parser callbacks which can occur at 10978 // many points during the parsing of a struct declaration (because 10979 // the #pragma tokens are effectively skipped over during the 10980 // parsing of the struct). 10981 if (TUK == TUK_Definition) { 10982 AddAlignmentAttributesForRecord(RD); 10983 AddMsStructLayoutForRecord(RD); 10984 } 10985 } 10986 10987 if (ModulePrivateLoc.isValid()) { 10988 if (isExplicitSpecialization) 10989 Diag(New->getLocation(), diag::err_module_private_specialization) 10990 << 2 10991 << FixItHint::CreateRemoval(ModulePrivateLoc); 10992 // __module_private__ does not apply to local classes. However, we only 10993 // diagnose this as an error when the declaration specifiers are 10994 // freestanding. Here, we just ignore the __module_private__. 10995 else if (!SearchDC->isFunctionOrMethod()) 10996 New->setModulePrivate(); 10997 } 10998 10999 // If this is a specialization of a member class (of a class template), 11000 // check the specialization. 11001 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11002 Invalid = true; 11003 11004 if (Invalid) 11005 New->setInvalidDecl(); 11006 11007 if (Attr) 11008 ProcessDeclAttributeList(S, New, Attr); 11009 11010 // If we're declaring or defining a tag in function prototype scope 11011 // in C, note that this type can only be used within the function. 11012 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 11013 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11014 11015 // Set the lexical context. If the tag has a C++ scope specifier, the 11016 // lexical context will be different from the semantic context. 11017 New->setLexicalDeclContext(CurContext); 11018 11019 // Mark this as a friend decl if applicable. 11020 // In Microsoft mode, a friend declaration also acts as a forward 11021 // declaration so we always pass true to setObjectOfFriendDecl to make 11022 // the tag name visible. 11023 if (TUK == TUK_Friend) 11024 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11025 getLangOpts().MicrosoftExt); 11026 11027 // Set the access specifier. 11028 if (!Invalid && SearchDC->isRecord()) 11029 SetMemberAccessSpecifier(New, PrevDecl, AS); 11030 11031 if (TUK == TUK_Definition) 11032 New->startDefinition(); 11033 11034 // If this has an identifier, add it to the scope stack. 11035 if (TUK == TUK_Friend) { 11036 // We might be replacing an existing declaration in the lookup tables; 11037 // if so, borrow its access specifier. 11038 if (PrevDecl) 11039 New->setAccess(PrevDecl->getAccess()); 11040 11041 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11042 DC->makeDeclVisibleInContext(New); 11043 if (Name) // can be null along some error paths 11044 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11045 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11046 } else if (Name) { 11047 S = getNonFieldDeclScope(S); 11048 PushOnScopeChains(New, S, !IsForwardReference); 11049 if (IsForwardReference) 11050 SearchDC->makeDeclVisibleInContext(New); 11051 11052 } else { 11053 CurContext->addDecl(New); 11054 } 11055 11056 // If this is the C FILE type, notify the AST context. 11057 if (IdentifierInfo *II = New->getIdentifier()) 11058 if (!New->isInvalidDecl() && 11059 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11060 II->isStr("FILE")) 11061 Context.setFILEDecl(New); 11062 11063 // If we were in function prototype scope (and not in C++ mode), add this 11064 // tag to the list of decls to inject into the function definition scope. 11065 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11066 InFunctionDeclarator && Name) 11067 DeclsInPrototypeScope.push_back(New); 11068 11069 if (PrevDecl) 11070 mergeDeclAttributes(New, PrevDecl); 11071 11072 // If there's a #pragma GCC visibility in scope, set the visibility of this 11073 // record. 11074 AddPushedVisibilityAttribute(New); 11075 11076 OwnedDecl = true; 11077 // In C++, don't return an invalid declaration. We can't recover well from 11078 // the cases where we make the type anonymous. 11079 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11080} 11081 11082void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11083 AdjustDeclIfTemplate(TagD); 11084 TagDecl *Tag = cast<TagDecl>(TagD); 11085 11086 // Enter the tag context. 11087 PushDeclContext(S, Tag); 11088 11089 ActOnDocumentableDecl(TagD); 11090 11091 // If there's a #pragma GCC visibility in scope, set the visibility of this 11092 // record. 11093 AddPushedVisibilityAttribute(Tag); 11094} 11095 11096Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11097 assert(isa<ObjCContainerDecl>(IDecl) && 11098 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11099 DeclContext *OCD = cast<DeclContext>(IDecl); 11100 assert(getContainingDC(OCD) == CurContext && 11101 "The next DeclContext should be lexically contained in the current one."); 11102 CurContext = OCD; 11103 return IDecl; 11104} 11105 11106void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11107 SourceLocation FinalLoc, 11108 bool IsFinalSpelledSealed, 11109 SourceLocation LBraceLoc) { 11110 AdjustDeclIfTemplate(TagD); 11111 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11112 11113 FieldCollector->StartClass(); 11114 11115 if (!Record->getIdentifier()) 11116 return; 11117 11118 if (FinalLoc.isValid()) 11119 Record->addAttr(new (Context) 11120 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11121 11122 // C++ [class]p2: 11123 // [...] The class-name is also inserted into the scope of the 11124 // class itself; this is known as the injected-class-name. For 11125 // purposes of access checking, the injected-class-name is treated 11126 // as if it were a public member name. 11127 CXXRecordDecl *InjectedClassName 11128 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11129 Record->getLocStart(), Record->getLocation(), 11130 Record->getIdentifier(), 11131 /*PrevDecl=*/0, 11132 /*DelayTypeCreation=*/true); 11133 Context.getTypeDeclType(InjectedClassName, Record); 11134 InjectedClassName->setImplicit(); 11135 InjectedClassName->setAccess(AS_public); 11136 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11137 InjectedClassName->setDescribedClassTemplate(Template); 11138 PushOnScopeChains(InjectedClassName, S); 11139 assert(InjectedClassName->isInjectedClassName() && 11140 "Broken injected-class-name"); 11141} 11142 11143void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11144 SourceLocation RBraceLoc) { 11145 AdjustDeclIfTemplate(TagD); 11146 TagDecl *Tag = cast<TagDecl>(TagD); 11147 Tag->setRBraceLoc(RBraceLoc); 11148 11149 // Make sure we "complete" the definition even it is invalid. 11150 if (Tag->isBeingDefined()) { 11151 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11152 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11153 RD->completeDefinition(); 11154 } 11155 11156 if (isa<CXXRecordDecl>(Tag)) 11157 FieldCollector->FinishClass(); 11158 11159 // Exit this scope of this tag's definition. 11160 PopDeclContext(); 11161 11162 if (getCurLexicalContext()->isObjCContainer() && 11163 Tag->getDeclContext()->isFileContext()) 11164 Tag->setTopLevelDeclInObjCContainer(); 11165 11166 // Notify the consumer that we've defined a tag. 11167 if (!Tag->isInvalidDecl()) 11168 Consumer.HandleTagDeclDefinition(Tag); 11169} 11170 11171void Sema::ActOnObjCContainerFinishDefinition() { 11172 // Exit this scope of this interface definition. 11173 PopDeclContext(); 11174} 11175 11176void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11177 assert(DC == CurContext && "Mismatch of container contexts"); 11178 OriginalLexicalContext = DC; 11179 ActOnObjCContainerFinishDefinition(); 11180} 11181 11182void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11183 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11184 OriginalLexicalContext = 0; 11185} 11186 11187void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11188 AdjustDeclIfTemplate(TagD); 11189 TagDecl *Tag = cast<TagDecl>(TagD); 11190 Tag->setInvalidDecl(); 11191 11192 // Make sure we "complete" the definition even it is invalid. 11193 if (Tag->isBeingDefined()) { 11194 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11195 RD->completeDefinition(); 11196 } 11197 11198 // We're undoing ActOnTagStartDefinition here, not 11199 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11200 // the FieldCollector. 11201 11202 PopDeclContext(); 11203} 11204 11205// Note that FieldName may be null for anonymous bitfields. 11206ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11207 IdentifierInfo *FieldName, 11208 QualType FieldTy, bool IsMsStruct, 11209 Expr *BitWidth, bool *ZeroWidth) { 11210 // Default to true; that shouldn't confuse checks for emptiness 11211 if (ZeroWidth) 11212 *ZeroWidth = true; 11213 11214 // C99 6.7.2.1p4 - verify the field type. 11215 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11216 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11217 // Handle incomplete types with specific error. 11218 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11219 return ExprError(); 11220 if (FieldName) 11221 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11222 << FieldName << FieldTy << BitWidth->getSourceRange(); 11223 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11224 << FieldTy << BitWidth->getSourceRange(); 11225 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11226 UPPC_BitFieldWidth)) 11227 return ExprError(); 11228 11229 // If the bit-width is type- or value-dependent, don't try to check 11230 // it now. 11231 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11232 return Owned(BitWidth); 11233 11234 llvm::APSInt Value; 11235 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11236 if (ICE.isInvalid()) 11237 return ICE; 11238 BitWidth = ICE.take(); 11239 11240 if (Value != 0 && ZeroWidth) 11241 *ZeroWidth = false; 11242 11243 // Zero-width bitfield is ok for anonymous field. 11244 if (Value == 0 && FieldName) 11245 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11246 11247 if (Value.isSigned() && Value.isNegative()) { 11248 if (FieldName) 11249 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11250 << FieldName << Value.toString(10); 11251 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11252 << Value.toString(10); 11253 } 11254 11255 if (!FieldTy->isDependentType()) { 11256 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11257 if (Value.getZExtValue() > TypeSize) { 11258 if (!getLangOpts().CPlusPlus || IsMsStruct) { 11259 if (FieldName) 11260 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11261 << FieldName << (unsigned)Value.getZExtValue() 11262 << (unsigned)TypeSize; 11263 11264 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11265 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11266 } 11267 11268 if (FieldName) 11269 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11270 << FieldName << (unsigned)Value.getZExtValue() 11271 << (unsigned)TypeSize; 11272 else 11273 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11274 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11275 } 11276 } 11277 11278 return Owned(BitWidth); 11279} 11280 11281/// ActOnField - Each field of a C struct/union is passed into this in order 11282/// to create a FieldDecl object for it. 11283Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11284 Declarator &D, Expr *BitfieldWidth) { 11285 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11286 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11287 /*InitStyle=*/ICIS_NoInit, AS_public); 11288 return Res; 11289} 11290 11291/// HandleField - Analyze a field of a C struct or a C++ data member. 11292/// 11293FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11294 SourceLocation DeclStart, 11295 Declarator &D, Expr *BitWidth, 11296 InClassInitStyle InitStyle, 11297 AccessSpecifier AS) { 11298 IdentifierInfo *II = D.getIdentifier(); 11299 SourceLocation Loc = DeclStart; 11300 if (II) Loc = D.getIdentifierLoc(); 11301 11302 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11303 QualType T = TInfo->getType(); 11304 if (getLangOpts().CPlusPlus) { 11305 CheckExtraCXXDefaultArguments(D); 11306 11307 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11308 UPPC_DataMemberType)) { 11309 D.setInvalidType(); 11310 T = Context.IntTy; 11311 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11312 } 11313 } 11314 11315 // TR 18037 does not allow fields to be declared with address spaces. 11316 if (T.getQualifiers().hasAddressSpace()) { 11317 Diag(Loc, diag::err_field_with_address_space); 11318 D.setInvalidType(); 11319 } 11320 11321 // OpenCL 1.2 spec, s6.9 r: 11322 // The event type cannot be used to declare a structure or union field. 11323 if (LangOpts.OpenCL && T->isEventT()) { 11324 Diag(Loc, diag::err_event_t_struct_field); 11325 D.setInvalidType(); 11326 } 11327 11328 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11329 11330 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11331 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11332 diag::err_invalid_thread) 11333 << DeclSpec::getSpecifierName(TSCS); 11334 11335 // Check to see if this name was declared as a member previously 11336 NamedDecl *PrevDecl = 0; 11337 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11338 LookupName(Previous, S); 11339 switch (Previous.getResultKind()) { 11340 case LookupResult::Found: 11341 case LookupResult::FoundUnresolvedValue: 11342 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11343 break; 11344 11345 case LookupResult::FoundOverloaded: 11346 PrevDecl = Previous.getRepresentativeDecl(); 11347 break; 11348 11349 case LookupResult::NotFound: 11350 case LookupResult::NotFoundInCurrentInstantiation: 11351 case LookupResult::Ambiguous: 11352 break; 11353 } 11354 Previous.suppressDiagnostics(); 11355 11356 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11357 // Maybe we will complain about the shadowed template parameter. 11358 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11359 // Just pretend that we didn't see the previous declaration. 11360 PrevDecl = 0; 11361 } 11362 11363 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11364 PrevDecl = 0; 11365 11366 bool Mutable 11367 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11368 SourceLocation TSSL = D.getLocStart(); 11369 FieldDecl *NewFD 11370 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11371 TSSL, AS, PrevDecl, &D); 11372 11373 if (NewFD->isInvalidDecl()) 11374 Record->setInvalidDecl(); 11375 11376 if (D.getDeclSpec().isModulePrivateSpecified()) 11377 NewFD->setModulePrivate(); 11378 11379 if (NewFD->isInvalidDecl() && PrevDecl) { 11380 // Don't introduce NewFD into scope; there's already something 11381 // with the same name in the same scope. 11382 } else if (II) { 11383 PushOnScopeChains(NewFD, S); 11384 } else 11385 Record->addDecl(NewFD); 11386 11387 return NewFD; 11388} 11389 11390/// \brief Build a new FieldDecl and check its well-formedness. 11391/// 11392/// This routine builds a new FieldDecl given the fields name, type, 11393/// record, etc. \p PrevDecl should refer to any previous declaration 11394/// with the same name and in the same scope as the field to be 11395/// created. 11396/// 11397/// \returns a new FieldDecl. 11398/// 11399/// \todo The Declarator argument is a hack. It will be removed once 11400FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11401 TypeSourceInfo *TInfo, 11402 RecordDecl *Record, SourceLocation Loc, 11403 bool Mutable, Expr *BitWidth, 11404 InClassInitStyle InitStyle, 11405 SourceLocation TSSL, 11406 AccessSpecifier AS, NamedDecl *PrevDecl, 11407 Declarator *D) { 11408 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11409 bool InvalidDecl = false; 11410 if (D) InvalidDecl = D->isInvalidType(); 11411 11412 // If we receive a broken type, recover by assuming 'int' and 11413 // marking this declaration as invalid. 11414 if (T.isNull()) { 11415 InvalidDecl = true; 11416 T = Context.IntTy; 11417 } 11418 11419 QualType EltTy = Context.getBaseElementType(T); 11420 if (!EltTy->isDependentType()) { 11421 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11422 // Fields of incomplete type force their record to be invalid. 11423 Record->setInvalidDecl(); 11424 InvalidDecl = true; 11425 } else { 11426 NamedDecl *Def; 11427 EltTy->isIncompleteType(&Def); 11428 if (Def && Def->isInvalidDecl()) { 11429 Record->setInvalidDecl(); 11430 InvalidDecl = true; 11431 } 11432 } 11433 } 11434 11435 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11436 if (BitWidth && getLangOpts().OpenCL) { 11437 Diag(Loc, diag::err_opencl_bitfields); 11438 InvalidDecl = true; 11439 } 11440 11441 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11442 // than a variably modified type. 11443 if (!InvalidDecl && T->isVariablyModifiedType()) { 11444 bool SizeIsNegative; 11445 llvm::APSInt Oversized; 11446 11447 TypeSourceInfo *FixedTInfo = 11448 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11449 SizeIsNegative, 11450 Oversized); 11451 if (FixedTInfo) { 11452 Diag(Loc, diag::warn_illegal_constant_array_size); 11453 TInfo = FixedTInfo; 11454 T = FixedTInfo->getType(); 11455 } else { 11456 if (SizeIsNegative) 11457 Diag(Loc, diag::err_typecheck_negative_array_size); 11458 else if (Oversized.getBoolValue()) 11459 Diag(Loc, diag::err_array_too_large) 11460 << Oversized.toString(10); 11461 else 11462 Diag(Loc, diag::err_typecheck_field_variable_size); 11463 InvalidDecl = true; 11464 } 11465 } 11466 11467 // Fields can not have abstract class types 11468 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11469 diag::err_abstract_type_in_decl, 11470 AbstractFieldType)) 11471 InvalidDecl = true; 11472 11473 bool ZeroWidth = false; 11474 // If this is declared as a bit-field, check the bit-field. 11475 if (!InvalidDecl && BitWidth) { 11476 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11477 &ZeroWidth).take(); 11478 if (!BitWidth) { 11479 InvalidDecl = true; 11480 BitWidth = 0; 11481 ZeroWidth = false; 11482 } 11483 } 11484 11485 // Check that 'mutable' is consistent with the type of the declaration. 11486 if (!InvalidDecl && Mutable) { 11487 unsigned DiagID = 0; 11488 if (T->isReferenceType()) 11489 DiagID = diag::err_mutable_reference; 11490 else if (T.isConstQualified()) 11491 DiagID = diag::err_mutable_const; 11492 11493 if (DiagID) { 11494 SourceLocation ErrLoc = Loc; 11495 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11496 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11497 Diag(ErrLoc, DiagID); 11498 Mutable = false; 11499 InvalidDecl = true; 11500 } 11501 } 11502 11503 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11504 BitWidth, Mutable, InitStyle); 11505 if (InvalidDecl) 11506 NewFD->setInvalidDecl(); 11507 11508 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11509 Diag(Loc, diag::err_duplicate_member) << II; 11510 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11511 NewFD->setInvalidDecl(); 11512 } 11513 11514 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11515 if (Record->isUnion()) { 11516 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11517 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11518 if (RDecl->getDefinition()) { 11519 // C++ [class.union]p1: An object of a class with a non-trivial 11520 // constructor, a non-trivial copy constructor, a non-trivial 11521 // destructor, or a non-trivial copy assignment operator 11522 // cannot be a member of a union, nor can an array of such 11523 // objects. 11524 if (CheckNontrivialField(NewFD)) 11525 NewFD->setInvalidDecl(); 11526 } 11527 } 11528 11529 // C++ [class.union]p1: If a union contains a member of reference type, 11530 // the program is ill-formed, except when compiling with MSVC extensions 11531 // enabled. 11532 if (EltTy->isReferenceType()) { 11533 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11534 diag::ext_union_member_of_reference_type : 11535 diag::err_union_member_of_reference_type) 11536 << NewFD->getDeclName() << EltTy; 11537 if (!getLangOpts().MicrosoftExt) 11538 NewFD->setInvalidDecl(); 11539 } 11540 } 11541 } 11542 11543 // FIXME: We need to pass in the attributes given an AST 11544 // representation, not a parser representation. 11545 if (D) { 11546 // FIXME: The current scope is almost... but not entirely... correct here. 11547 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11548 11549 if (NewFD->hasAttrs()) 11550 CheckAlignasUnderalignment(NewFD); 11551 } 11552 11553 // In auto-retain/release, infer strong retension for fields of 11554 // retainable type. 11555 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11556 NewFD->setInvalidDecl(); 11557 11558 if (T.isObjCGCWeak()) 11559 Diag(Loc, diag::warn_attribute_weak_on_field); 11560 11561 NewFD->setAccess(AS); 11562 return NewFD; 11563} 11564 11565bool Sema::CheckNontrivialField(FieldDecl *FD) { 11566 assert(FD); 11567 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11568 11569 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11570 return false; 11571 11572 QualType EltTy = Context.getBaseElementType(FD->getType()); 11573 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11574 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11575 if (RDecl->getDefinition()) { 11576 // We check for copy constructors before constructors 11577 // because otherwise we'll never get complaints about 11578 // copy constructors. 11579 11580 CXXSpecialMember member = CXXInvalid; 11581 // We're required to check for any non-trivial constructors. Since the 11582 // implicit default constructor is suppressed if there are any 11583 // user-declared constructors, we just need to check that there is a 11584 // trivial default constructor and a trivial copy constructor. (We don't 11585 // worry about move constructors here, since this is a C++98 check.) 11586 if (RDecl->hasNonTrivialCopyConstructor()) 11587 member = CXXCopyConstructor; 11588 else if (!RDecl->hasTrivialDefaultConstructor()) 11589 member = CXXDefaultConstructor; 11590 else if (RDecl->hasNonTrivialCopyAssignment()) 11591 member = CXXCopyAssignment; 11592 else if (RDecl->hasNonTrivialDestructor()) 11593 member = CXXDestructor; 11594 11595 if (member != CXXInvalid) { 11596 if (!getLangOpts().CPlusPlus11 && 11597 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11598 // Objective-C++ ARC: it is an error to have a non-trivial field of 11599 // a union. However, system headers in Objective-C programs 11600 // occasionally have Objective-C lifetime objects within unions, 11601 // and rather than cause the program to fail, we make those 11602 // members unavailable. 11603 SourceLocation Loc = FD->getLocation(); 11604 if (getSourceManager().isInSystemHeader(Loc)) { 11605 if (!FD->hasAttr<UnavailableAttr>()) 11606 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 11607 "this system field has retaining ownership")); 11608 return false; 11609 } 11610 } 11611 11612 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11613 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11614 diag::err_illegal_union_or_anon_struct_member) 11615 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11616 DiagnoseNontrivial(RDecl, member); 11617 return !getLangOpts().CPlusPlus11; 11618 } 11619 } 11620 } 11621 11622 return false; 11623} 11624 11625/// TranslateIvarVisibility - Translate visibility from a token ID to an 11626/// AST enum value. 11627static ObjCIvarDecl::AccessControl 11628TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11629 switch (ivarVisibility) { 11630 default: llvm_unreachable("Unknown visitibility kind"); 11631 case tok::objc_private: return ObjCIvarDecl::Private; 11632 case tok::objc_public: return ObjCIvarDecl::Public; 11633 case tok::objc_protected: return ObjCIvarDecl::Protected; 11634 case tok::objc_package: return ObjCIvarDecl::Package; 11635 } 11636} 11637 11638/// ActOnIvar - Each ivar field of an objective-c class is passed into this 11639/// in order to create an IvarDecl object for it. 11640Decl *Sema::ActOnIvar(Scope *S, 11641 SourceLocation DeclStart, 11642 Declarator &D, Expr *BitfieldWidth, 11643 tok::ObjCKeywordKind Visibility) { 11644 11645 IdentifierInfo *II = D.getIdentifier(); 11646 Expr *BitWidth = (Expr*)BitfieldWidth; 11647 SourceLocation Loc = DeclStart; 11648 if (II) Loc = D.getIdentifierLoc(); 11649 11650 // FIXME: Unnamed fields can be handled in various different ways, for 11651 // example, unnamed unions inject all members into the struct namespace! 11652 11653 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11654 QualType T = TInfo->getType(); 11655 11656 if (BitWidth) { 11657 // 6.7.2.1p3, 6.7.2.1p4 11658 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11659 if (!BitWidth) 11660 D.setInvalidType(); 11661 } else { 11662 // Not a bitfield. 11663 11664 // validate II. 11665 11666 } 11667 if (T->isReferenceType()) { 11668 Diag(Loc, diag::err_ivar_reference_type); 11669 D.setInvalidType(); 11670 } 11671 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11672 // than a variably modified type. 11673 else if (T->isVariablyModifiedType()) { 11674 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11675 D.setInvalidType(); 11676 } 11677 11678 // Get the visibility (access control) for this ivar. 11679 ObjCIvarDecl::AccessControl ac = 11680 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11681 : ObjCIvarDecl::None; 11682 // Must set ivar's DeclContext to its enclosing interface. 11683 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11684 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11685 return 0; 11686 ObjCContainerDecl *EnclosingContext; 11687 if (ObjCImplementationDecl *IMPDecl = 11688 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11689 if (LangOpts.ObjCRuntime.isFragile()) { 11690 // Case of ivar declared in an implementation. Context is that of its class. 11691 EnclosingContext = IMPDecl->getClassInterface(); 11692 assert(EnclosingContext && "Implementation has no class interface!"); 11693 } 11694 else 11695 EnclosingContext = EnclosingDecl; 11696 } else { 11697 if (ObjCCategoryDecl *CDecl = 11698 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11699 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11700 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11701 return 0; 11702 } 11703 } 11704 EnclosingContext = EnclosingDecl; 11705 } 11706 11707 // Construct the decl. 11708 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11709 DeclStart, Loc, II, T, 11710 TInfo, ac, (Expr *)BitfieldWidth); 11711 11712 if (II) { 11713 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11714 ForRedeclaration); 11715 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11716 && !isa<TagDecl>(PrevDecl)) { 11717 Diag(Loc, diag::err_duplicate_member) << II; 11718 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11719 NewID->setInvalidDecl(); 11720 } 11721 } 11722 11723 // Process attributes attached to the ivar. 11724 ProcessDeclAttributes(S, NewID, D); 11725 11726 if (D.isInvalidType()) 11727 NewID->setInvalidDecl(); 11728 11729 // In ARC, infer 'retaining' for ivars of retainable type. 11730 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11731 NewID->setInvalidDecl(); 11732 11733 if (D.getDeclSpec().isModulePrivateSpecified()) 11734 NewID->setModulePrivate(); 11735 11736 if (II) { 11737 // FIXME: When interfaces are DeclContexts, we'll need to add 11738 // these to the interface. 11739 S->AddDecl(NewID); 11740 IdResolver.AddDecl(NewID); 11741 } 11742 11743 if (LangOpts.ObjCRuntime.isNonFragile() && 11744 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11745 Diag(Loc, diag::warn_ivars_in_interface); 11746 11747 return NewID; 11748} 11749 11750/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11751/// class and class extensions. For every class \@interface and class 11752/// extension \@interface, if the last ivar is a bitfield of any type, 11753/// then add an implicit `char :0` ivar to the end of that interface. 11754void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11755 SmallVectorImpl<Decl *> &AllIvarDecls) { 11756 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11757 return; 11758 11759 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11760 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11761 11762 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11763 return; 11764 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11765 if (!ID) { 11766 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11767 if (!CD->IsClassExtension()) 11768 return; 11769 } 11770 // No need to add this to end of @implementation. 11771 else 11772 return; 11773 } 11774 // All conditions are met. Add a new bitfield to the tail end of ivars. 11775 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11776 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11777 11778 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11779 DeclLoc, DeclLoc, 0, 11780 Context.CharTy, 11781 Context.getTrivialTypeSourceInfo(Context.CharTy, 11782 DeclLoc), 11783 ObjCIvarDecl::Private, BW, 11784 true); 11785 AllIvarDecls.push_back(Ivar); 11786} 11787 11788void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11789 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11790 SourceLocation RBrac, AttributeList *Attr) { 11791 assert(EnclosingDecl && "missing record or interface decl"); 11792 11793 // If this is an Objective-C @implementation or category and we have 11794 // new fields here we should reset the layout of the interface since 11795 // it will now change. 11796 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11797 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11798 switch (DC->getKind()) { 11799 default: break; 11800 case Decl::ObjCCategory: 11801 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11802 break; 11803 case Decl::ObjCImplementation: 11804 Context. 11805 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11806 break; 11807 } 11808 } 11809 11810 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11811 11812 // Start counting up the number of named members; make sure to include 11813 // members of anonymous structs and unions in the total. 11814 unsigned NumNamedMembers = 0; 11815 if (Record) { 11816 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11817 e = Record->decls_end(); i != e; i++) { 11818 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11819 if (IFD->getDeclName()) 11820 ++NumNamedMembers; 11821 } 11822 } 11823 11824 // Verify that all the fields are okay. 11825 SmallVector<FieldDecl*, 32> RecFields; 11826 11827 bool ARCErrReported = false; 11828 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11829 i != end; ++i) { 11830 FieldDecl *FD = cast<FieldDecl>(*i); 11831 11832 // Get the type for the field. 11833 const Type *FDTy = FD->getType().getTypePtr(); 11834 11835 if (!FD->isAnonymousStructOrUnion()) { 11836 // Remember all fields written by the user. 11837 RecFields.push_back(FD); 11838 } 11839 11840 // If the field is already invalid for some reason, don't emit more 11841 // diagnostics about it. 11842 if (FD->isInvalidDecl()) { 11843 EnclosingDecl->setInvalidDecl(); 11844 continue; 11845 } 11846 11847 // C99 6.7.2.1p2: 11848 // A structure or union shall not contain a member with 11849 // incomplete or function type (hence, a structure shall not 11850 // contain an instance of itself, but may contain a pointer to 11851 // an instance of itself), except that the last member of a 11852 // structure with more than one named member may have incomplete 11853 // array type; such a structure (and any union containing, 11854 // possibly recursively, a member that is such a structure) 11855 // shall not be a member of a structure or an element of an 11856 // array. 11857 if (FDTy->isFunctionType()) { 11858 // Field declared as a function. 11859 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11860 << FD->getDeclName(); 11861 FD->setInvalidDecl(); 11862 EnclosingDecl->setInvalidDecl(); 11863 continue; 11864 } else if (FDTy->isIncompleteArrayType() && Record && 11865 ((i + 1 == Fields.end() && !Record->isUnion()) || 11866 ((getLangOpts().MicrosoftExt || 11867 getLangOpts().CPlusPlus) && 11868 (i + 1 == Fields.end() || Record->isUnion())))) { 11869 // Flexible array member. 11870 // Microsoft and g++ is more permissive regarding flexible array. 11871 // It will accept flexible array in union and also 11872 // as the sole element of a struct/class. 11873 unsigned DiagID = 0; 11874 if (Record->isUnion()) 11875 DiagID = getLangOpts().MicrosoftExt 11876 ? diag::ext_flexible_array_union_ms 11877 : getLangOpts().CPlusPlus 11878 ? diag::ext_flexible_array_union_gnu 11879 : diag::err_flexible_array_union; 11880 else if (Fields.size() == 1) 11881 DiagID = getLangOpts().MicrosoftExt 11882 ? diag::ext_flexible_array_empty_aggregate_ms 11883 : getLangOpts().CPlusPlus 11884 ? diag::ext_flexible_array_empty_aggregate_gnu 11885 : NumNamedMembers < 1 11886 ? diag::err_flexible_array_empty_aggregate 11887 : 0; 11888 11889 if (DiagID) 11890 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11891 << Record->getTagKind(); 11892 // While the layout of types that contain virtual bases is not specified 11893 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11894 // virtual bases after the derived members. This would make a flexible 11895 // array member declared at the end of an object not adjacent to the end 11896 // of the type. 11897 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11898 if (RD->getNumVBases() != 0) 11899 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11900 << FD->getDeclName() << Record->getTagKind(); 11901 if (!getLangOpts().C99) 11902 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11903 << FD->getDeclName() << Record->getTagKind(); 11904 11905 if (!FD->getType()->isDependentType() && 11906 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 11907 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 11908 << FD->getDeclName() << FD->getType(); 11909 FD->setInvalidDecl(); 11910 EnclosingDecl->setInvalidDecl(); 11911 continue; 11912 } 11913 // Okay, we have a legal flexible array member at the end of the struct. 11914 if (Record) 11915 Record->setHasFlexibleArrayMember(true); 11916 } else if (!FDTy->isDependentType() && 11917 RequireCompleteType(FD->getLocation(), FD->getType(), 11918 diag::err_field_incomplete)) { 11919 // Incomplete type 11920 FD->setInvalidDecl(); 11921 EnclosingDecl->setInvalidDecl(); 11922 continue; 11923 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11924 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11925 // If this is a member of a union, then entire union becomes "flexible". 11926 if (Record && Record->isUnion()) { 11927 Record->setHasFlexibleArrayMember(true); 11928 } else { 11929 // If this is a struct/class and this is not the last element, reject 11930 // it. Note that GCC supports variable sized arrays in the middle of 11931 // structures. 11932 if (i + 1 != Fields.end()) 11933 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11934 << FD->getDeclName() << FD->getType(); 11935 else { 11936 // We support flexible arrays at the end of structs in 11937 // other structs as an extension. 11938 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11939 << FD->getDeclName(); 11940 if (Record) 11941 Record->setHasFlexibleArrayMember(true); 11942 } 11943 } 11944 } 11945 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11946 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11947 diag::err_abstract_type_in_decl, 11948 AbstractIvarType)) { 11949 // Ivars can not have abstract class types 11950 FD->setInvalidDecl(); 11951 } 11952 if (Record && FDTTy->getDecl()->hasObjectMember()) 11953 Record->setHasObjectMember(true); 11954 if (Record && FDTTy->getDecl()->hasVolatileMember()) 11955 Record->setHasVolatileMember(true); 11956 } else if (FDTy->isObjCObjectType()) { 11957 /// A field cannot be an Objective-c object 11958 Diag(FD->getLocation(), diag::err_statically_allocated_object) 11959 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 11960 QualType T = Context.getObjCObjectPointerType(FD->getType()); 11961 FD->setType(T); 11962 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 11963 (!getLangOpts().CPlusPlus || Record->isUnion())) { 11964 // It's an error in ARC if a field has lifetime. 11965 // We don't want to report this in a system header, though, 11966 // so we just make the field unavailable. 11967 // FIXME: that's really not sufficient; we need to make the type 11968 // itself invalid to, say, initialize or copy. 11969 QualType T = FD->getType(); 11970 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 11971 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 11972 SourceLocation loc = FD->getLocation(); 11973 if (getSourceManager().isInSystemHeader(loc)) { 11974 if (!FD->hasAttr<UnavailableAttr>()) { 11975 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 11976 "this system field has retaining ownership")); 11977 } 11978 } else { 11979 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 11980 << T->isBlockPointerType() << Record->getTagKind(); 11981 } 11982 ARCErrReported = true; 11983 } 11984 } else if (getLangOpts().ObjC1 && 11985 getLangOpts().getGC() != LangOptions::NonGC && 11986 Record && !Record->hasObjectMember()) { 11987 if (FD->getType()->isObjCObjectPointerType() || 11988 FD->getType().isObjCGCStrong()) 11989 Record->setHasObjectMember(true); 11990 else if (Context.getAsArrayType(FD->getType())) { 11991 QualType BaseType = Context.getBaseElementType(FD->getType()); 11992 if (BaseType->isRecordType() && 11993 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 11994 Record->setHasObjectMember(true); 11995 else if (BaseType->isObjCObjectPointerType() || 11996 BaseType.isObjCGCStrong()) 11997 Record->setHasObjectMember(true); 11998 } 11999 } 12000 if (Record && FD->getType().isVolatileQualified()) 12001 Record->setHasVolatileMember(true); 12002 // Keep track of the number of named members. 12003 if (FD->getIdentifier()) 12004 ++NumNamedMembers; 12005 } 12006 12007 // Okay, we successfully defined 'Record'. 12008 if (Record) { 12009 bool Completed = false; 12010 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12011 if (!CXXRecord->isInvalidDecl()) { 12012 // Set access bits correctly on the directly-declared conversions. 12013 for (CXXRecordDecl::conversion_iterator 12014 I = CXXRecord->conversion_begin(), 12015 E = CXXRecord->conversion_end(); I != E; ++I) 12016 I.setAccess((*I)->getAccess()); 12017 12018 if (!CXXRecord->isDependentType()) { 12019 if (CXXRecord->hasUserDeclaredDestructor()) { 12020 // Adjust user-defined destructor exception spec. 12021 if (getLangOpts().CPlusPlus11) 12022 AdjustDestructorExceptionSpec(CXXRecord, 12023 CXXRecord->getDestructor()); 12024 12025 // The Microsoft ABI requires that we perform the destructor body 12026 // checks (i.e. operator delete() lookup) at every declaration, as 12027 // any translation unit may need to emit a deleting destructor. 12028 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12029 CheckDestructor(CXXRecord->getDestructor()); 12030 } 12031 12032 // Add any implicitly-declared members to this class. 12033 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12034 12035 // If we have virtual base classes, we may end up finding multiple 12036 // final overriders for a given virtual function. Check for this 12037 // problem now. 12038 if (CXXRecord->getNumVBases()) { 12039 CXXFinalOverriderMap FinalOverriders; 12040 CXXRecord->getFinalOverriders(FinalOverriders); 12041 12042 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12043 MEnd = FinalOverriders.end(); 12044 M != MEnd; ++M) { 12045 for (OverridingMethods::iterator SO = M->second.begin(), 12046 SOEnd = M->second.end(); 12047 SO != SOEnd; ++SO) { 12048 assert(SO->second.size() > 0 && 12049 "Virtual function without overridding functions?"); 12050 if (SO->second.size() == 1) 12051 continue; 12052 12053 // C++ [class.virtual]p2: 12054 // In a derived class, if a virtual member function of a base 12055 // class subobject has more than one final overrider the 12056 // program is ill-formed. 12057 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12058 << (const NamedDecl *)M->first << Record; 12059 Diag(M->first->getLocation(), 12060 diag::note_overridden_virtual_function); 12061 for (OverridingMethods::overriding_iterator 12062 OM = SO->second.begin(), 12063 OMEnd = SO->second.end(); 12064 OM != OMEnd; ++OM) 12065 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12066 << (const NamedDecl *)M->first << OM->Method->getParent(); 12067 12068 Record->setInvalidDecl(); 12069 } 12070 } 12071 CXXRecord->completeDefinition(&FinalOverriders); 12072 Completed = true; 12073 } 12074 } 12075 } 12076 } 12077 12078 if (!Completed) 12079 Record->completeDefinition(); 12080 12081 if (Record->hasAttrs()) 12082 CheckAlignasUnderalignment(Record); 12083 12084 // Check if the structure/union declaration is a type that can have zero 12085 // size in C. For C this is a language extension, for C++ it may cause 12086 // compatibility problems. 12087 bool CheckForZeroSize; 12088 if (!getLangOpts().CPlusPlus) { 12089 CheckForZeroSize = true; 12090 } else { 12091 // For C++ filter out types that cannot be referenced in C code. 12092 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12093 CheckForZeroSize = 12094 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12095 !CXXRecord->isDependentType() && 12096 CXXRecord->isCLike(); 12097 } 12098 if (CheckForZeroSize) { 12099 bool ZeroSize = true; 12100 bool IsEmpty = true; 12101 unsigned NonBitFields = 0; 12102 for (RecordDecl::field_iterator I = Record->field_begin(), 12103 E = Record->field_end(); 12104 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12105 IsEmpty = false; 12106 if (I->isUnnamedBitfield()) { 12107 if (I->getBitWidthValue(Context) > 0) 12108 ZeroSize = false; 12109 } else { 12110 ++NonBitFields; 12111 QualType FieldType = I->getType(); 12112 if (FieldType->isIncompleteType() || 12113 !Context.getTypeSizeInChars(FieldType).isZero()) 12114 ZeroSize = false; 12115 } 12116 } 12117 12118 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12119 // allowed in C++, but warn if its declaration is inside 12120 // extern "C" block. 12121 if (ZeroSize) { 12122 Diag(RecLoc, getLangOpts().CPlusPlus ? 12123 diag::warn_zero_size_struct_union_in_extern_c : 12124 diag::warn_zero_size_struct_union_compat) 12125 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12126 } 12127 12128 // Structs without named members are extension in C (C99 6.7.2.1p7), 12129 // but are accepted by GCC. 12130 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12131 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12132 diag::ext_no_named_members_in_struct_union) 12133 << Record->isUnion(); 12134 } 12135 } 12136 } else { 12137 ObjCIvarDecl **ClsFields = 12138 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12139 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12140 ID->setEndOfDefinitionLoc(RBrac); 12141 // Add ivar's to class's DeclContext. 12142 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12143 ClsFields[i]->setLexicalDeclContext(ID); 12144 ID->addDecl(ClsFields[i]); 12145 } 12146 // Must enforce the rule that ivars in the base classes may not be 12147 // duplicates. 12148 if (ID->getSuperClass()) 12149 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12150 } else if (ObjCImplementationDecl *IMPDecl = 12151 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12152 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12153 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12154 // Ivar declared in @implementation never belongs to the implementation. 12155 // Only it is in implementation's lexical context. 12156 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12157 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12158 IMPDecl->setIvarLBraceLoc(LBrac); 12159 IMPDecl->setIvarRBraceLoc(RBrac); 12160 } else if (ObjCCategoryDecl *CDecl = 12161 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12162 // case of ivars in class extension; all other cases have been 12163 // reported as errors elsewhere. 12164 // FIXME. Class extension does not have a LocEnd field. 12165 // CDecl->setLocEnd(RBrac); 12166 // Add ivar's to class extension's DeclContext. 12167 // Diagnose redeclaration of private ivars. 12168 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12169 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12170 if (IDecl) { 12171 if (const ObjCIvarDecl *ClsIvar = 12172 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12173 Diag(ClsFields[i]->getLocation(), 12174 diag::err_duplicate_ivar_declaration); 12175 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12176 continue; 12177 } 12178 for (ObjCInterfaceDecl::known_extensions_iterator 12179 Ext = IDecl->known_extensions_begin(), 12180 ExtEnd = IDecl->known_extensions_end(); 12181 Ext != ExtEnd; ++Ext) { 12182 if (const ObjCIvarDecl *ClsExtIvar 12183 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12184 Diag(ClsFields[i]->getLocation(), 12185 diag::err_duplicate_ivar_declaration); 12186 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12187 continue; 12188 } 12189 } 12190 } 12191 ClsFields[i]->setLexicalDeclContext(CDecl); 12192 CDecl->addDecl(ClsFields[i]); 12193 } 12194 CDecl->setIvarLBraceLoc(LBrac); 12195 CDecl->setIvarRBraceLoc(RBrac); 12196 } 12197 } 12198 12199 if (Attr) 12200 ProcessDeclAttributeList(S, Record, Attr); 12201} 12202 12203/// \brief Determine whether the given integral value is representable within 12204/// the given type T. 12205static bool isRepresentableIntegerValue(ASTContext &Context, 12206 llvm::APSInt &Value, 12207 QualType T) { 12208 assert(T->isIntegralType(Context) && "Integral type required!"); 12209 unsigned BitWidth = Context.getIntWidth(T); 12210 12211 if (Value.isUnsigned() || Value.isNonNegative()) { 12212 if (T->isSignedIntegerOrEnumerationType()) 12213 --BitWidth; 12214 return Value.getActiveBits() <= BitWidth; 12215 } 12216 return Value.getMinSignedBits() <= BitWidth; 12217} 12218 12219// \brief Given an integral type, return the next larger integral type 12220// (or a NULL type of no such type exists). 12221static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12222 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12223 // enum checking below. 12224 assert(T->isIntegralType(Context) && "Integral type required!"); 12225 const unsigned NumTypes = 4; 12226 QualType SignedIntegralTypes[NumTypes] = { 12227 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12228 }; 12229 QualType UnsignedIntegralTypes[NumTypes] = { 12230 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12231 Context.UnsignedLongLongTy 12232 }; 12233 12234 unsigned BitWidth = Context.getTypeSize(T); 12235 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12236 : UnsignedIntegralTypes; 12237 for (unsigned I = 0; I != NumTypes; ++I) 12238 if (Context.getTypeSize(Types[I]) > BitWidth) 12239 return Types[I]; 12240 12241 return QualType(); 12242} 12243 12244EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12245 EnumConstantDecl *LastEnumConst, 12246 SourceLocation IdLoc, 12247 IdentifierInfo *Id, 12248 Expr *Val) { 12249 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12250 llvm::APSInt EnumVal(IntWidth); 12251 QualType EltTy; 12252 12253 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12254 Val = 0; 12255 12256 if (Val) 12257 Val = DefaultLvalueConversion(Val).take(); 12258 12259 if (Val) { 12260 if (Enum->isDependentType() || Val->isTypeDependent()) 12261 EltTy = Context.DependentTy; 12262 else { 12263 SourceLocation ExpLoc; 12264 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12265 !getLangOpts().MicrosoftMode) { 12266 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12267 // constant-expression in the enumerator-definition shall be a converted 12268 // constant expression of the underlying type. 12269 EltTy = Enum->getIntegerType(); 12270 ExprResult Converted = 12271 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12272 CCEK_Enumerator); 12273 if (Converted.isInvalid()) 12274 Val = 0; 12275 else 12276 Val = Converted.take(); 12277 } else if (!Val->isValueDependent() && 12278 !(Val = VerifyIntegerConstantExpression(Val, 12279 &EnumVal).take())) { 12280 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12281 } else { 12282 if (Enum->isFixed()) { 12283 EltTy = Enum->getIntegerType(); 12284 12285 // In Obj-C and Microsoft mode, require the enumeration value to be 12286 // representable in the underlying type of the enumeration. In C++11, 12287 // we perform a non-narrowing conversion as part of converted constant 12288 // expression checking. 12289 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12290 if (getLangOpts().MicrosoftMode) { 12291 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12292 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12293 } else 12294 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12295 } else 12296 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12297 } else if (getLangOpts().CPlusPlus) { 12298 // C++11 [dcl.enum]p5: 12299 // If the underlying type is not fixed, the type of each enumerator 12300 // is the type of its initializing value: 12301 // - If an initializer is specified for an enumerator, the 12302 // initializing value has the same type as the expression. 12303 EltTy = Val->getType(); 12304 } else { 12305 // C99 6.7.2.2p2: 12306 // The expression that defines the value of an enumeration constant 12307 // shall be an integer constant expression that has a value 12308 // representable as an int. 12309 12310 // Complain if the value is not representable in an int. 12311 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12312 Diag(IdLoc, diag::ext_enum_value_not_int) 12313 << EnumVal.toString(10) << Val->getSourceRange() 12314 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12315 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12316 // Force the type of the expression to 'int'. 12317 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12318 } 12319 EltTy = Val->getType(); 12320 } 12321 } 12322 } 12323 } 12324 12325 if (!Val) { 12326 if (Enum->isDependentType()) 12327 EltTy = Context.DependentTy; 12328 else if (!LastEnumConst) { 12329 // C++0x [dcl.enum]p5: 12330 // If the underlying type is not fixed, the type of each enumerator 12331 // is the type of its initializing value: 12332 // - If no initializer is specified for the first enumerator, the 12333 // initializing value has an unspecified integral type. 12334 // 12335 // GCC uses 'int' for its unspecified integral type, as does 12336 // C99 6.7.2.2p3. 12337 if (Enum->isFixed()) { 12338 EltTy = Enum->getIntegerType(); 12339 } 12340 else { 12341 EltTy = Context.IntTy; 12342 } 12343 } else { 12344 // Assign the last value + 1. 12345 EnumVal = LastEnumConst->getInitVal(); 12346 ++EnumVal; 12347 EltTy = LastEnumConst->getType(); 12348 12349 // Check for overflow on increment. 12350 if (EnumVal < LastEnumConst->getInitVal()) { 12351 // C++0x [dcl.enum]p5: 12352 // If the underlying type is not fixed, the type of each enumerator 12353 // is the type of its initializing value: 12354 // 12355 // - Otherwise the type of the initializing value is the same as 12356 // the type of the initializing value of the preceding enumerator 12357 // unless the incremented value is not representable in that type, 12358 // in which case the type is an unspecified integral type 12359 // sufficient to contain the incremented value. If no such type 12360 // exists, the program is ill-formed. 12361 QualType T = getNextLargerIntegralType(Context, EltTy); 12362 if (T.isNull() || Enum->isFixed()) { 12363 // There is no integral type larger enough to represent this 12364 // value. Complain, then allow the value to wrap around. 12365 EnumVal = LastEnumConst->getInitVal(); 12366 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12367 ++EnumVal; 12368 if (Enum->isFixed()) 12369 // When the underlying type is fixed, this is ill-formed. 12370 Diag(IdLoc, diag::err_enumerator_wrapped) 12371 << EnumVal.toString(10) 12372 << EltTy; 12373 else 12374 Diag(IdLoc, diag::warn_enumerator_too_large) 12375 << EnumVal.toString(10); 12376 } else { 12377 EltTy = T; 12378 } 12379 12380 // Retrieve the last enumerator's value, extent that type to the 12381 // type that is supposed to be large enough to represent the incremented 12382 // value, then increment. 12383 EnumVal = LastEnumConst->getInitVal(); 12384 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12385 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12386 ++EnumVal; 12387 12388 // If we're not in C++, diagnose the overflow of enumerator values, 12389 // which in C99 means that the enumerator value is not representable in 12390 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12391 // permits enumerator values that are representable in some larger 12392 // integral type. 12393 if (!getLangOpts().CPlusPlus && !T.isNull()) 12394 Diag(IdLoc, diag::warn_enum_value_overflow); 12395 } else if (!getLangOpts().CPlusPlus && 12396 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12397 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12398 Diag(IdLoc, diag::ext_enum_value_not_int) 12399 << EnumVal.toString(10) << 1; 12400 } 12401 } 12402 } 12403 12404 if (!EltTy->isDependentType()) { 12405 // Make the enumerator value match the signedness and size of the 12406 // enumerator's type. 12407 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12408 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12409 } 12410 12411 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12412 Val, EnumVal); 12413} 12414 12415 12416Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12417 SourceLocation IdLoc, IdentifierInfo *Id, 12418 AttributeList *Attr, 12419 SourceLocation EqualLoc, Expr *Val) { 12420 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12421 EnumConstantDecl *LastEnumConst = 12422 cast_or_null<EnumConstantDecl>(lastEnumConst); 12423 12424 // The scope passed in may not be a decl scope. Zip up the scope tree until 12425 // we find one that is. 12426 S = getNonFieldDeclScope(S); 12427 12428 // Verify that there isn't already something declared with this name in this 12429 // scope. 12430 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12431 ForRedeclaration); 12432 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12433 // Maybe we will complain about the shadowed template parameter. 12434 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12435 // Just pretend that we didn't see the previous declaration. 12436 PrevDecl = 0; 12437 } 12438 12439 if (PrevDecl) { 12440 // When in C++, we may get a TagDecl with the same name; in this case the 12441 // enum constant will 'hide' the tag. 12442 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12443 "Received TagDecl when not in C++!"); 12444 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12445 if (isa<EnumConstantDecl>(PrevDecl)) 12446 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12447 else 12448 Diag(IdLoc, diag::err_redefinition) << Id; 12449 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12450 return 0; 12451 } 12452 } 12453 12454 // C++ [class.mem]p15: 12455 // If T is the name of a class, then each of the following shall have a name 12456 // different from T: 12457 // - every enumerator of every member of class T that is an unscoped 12458 // enumerated type 12459 if (CXXRecordDecl *Record 12460 = dyn_cast<CXXRecordDecl>( 12461 TheEnumDecl->getDeclContext()->getRedeclContext())) 12462 if (!TheEnumDecl->isScoped() && 12463 Record->getIdentifier() && Record->getIdentifier() == Id) 12464 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12465 12466 EnumConstantDecl *New = 12467 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12468 12469 if (New) { 12470 // Process attributes. 12471 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12472 12473 // Register this decl in the current scope stack. 12474 New->setAccess(TheEnumDecl->getAccess()); 12475 PushOnScopeChains(New, S); 12476 } 12477 12478 ActOnDocumentableDecl(New); 12479 12480 return New; 12481} 12482 12483// Returns true when the enum initial expression does not trigger the 12484// duplicate enum warning. A few common cases are exempted as follows: 12485// Element2 = Element1 12486// Element2 = Element1 + 1 12487// Element2 = Element1 - 1 12488// Where Element2 and Element1 are from the same enum. 12489static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12490 Expr *InitExpr = ECD->getInitExpr(); 12491 if (!InitExpr) 12492 return true; 12493 InitExpr = InitExpr->IgnoreImpCasts(); 12494 12495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12496 if (!BO->isAdditiveOp()) 12497 return true; 12498 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12499 if (!IL) 12500 return true; 12501 if (IL->getValue() != 1) 12502 return true; 12503 12504 InitExpr = BO->getLHS(); 12505 } 12506 12507 // This checks if the elements are from the same enum. 12508 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12509 if (!DRE) 12510 return true; 12511 12512 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12513 if (!EnumConstant) 12514 return true; 12515 12516 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12517 Enum) 12518 return true; 12519 12520 return false; 12521} 12522 12523struct DupKey { 12524 int64_t val; 12525 bool isTombstoneOrEmptyKey; 12526 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12527 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12528}; 12529 12530static DupKey GetDupKey(const llvm::APSInt& Val) { 12531 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12532 false); 12533} 12534 12535struct DenseMapInfoDupKey { 12536 static DupKey getEmptyKey() { return DupKey(0, true); } 12537 static DupKey getTombstoneKey() { return DupKey(1, true); } 12538 static unsigned getHashValue(const DupKey Key) { 12539 return (unsigned)(Key.val * 37); 12540 } 12541 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12542 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12543 LHS.val == RHS.val; 12544 } 12545}; 12546 12547// Emits a warning when an element is implicitly set a value that 12548// a previous element has already been set to. 12549static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12550 EnumDecl *Enum, 12551 QualType EnumType) { 12552 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12553 Enum->getLocation()) == 12554 DiagnosticsEngine::Ignored) 12555 return; 12556 // Avoid anonymous enums 12557 if (!Enum->getIdentifier()) 12558 return; 12559 12560 // Only check for small enums. 12561 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12562 return; 12563 12564 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12565 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12566 12567 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12568 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12569 ValueToVectorMap; 12570 12571 DuplicatesVector DupVector; 12572 ValueToVectorMap EnumMap; 12573 12574 // Populate the EnumMap with all values represented by enum constants without 12575 // an initialier. 12576 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12577 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12578 12579 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12580 // this constant. Skip this enum since it may be ill-formed. 12581 if (!ECD) { 12582 return; 12583 } 12584 12585 if (ECD->getInitExpr()) 12586 continue; 12587 12588 DupKey Key = GetDupKey(ECD->getInitVal()); 12589 DeclOrVector &Entry = EnumMap[Key]; 12590 12591 // First time encountering this value. 12592 if (Entry.isNull()) 12593 Entry = ECD; 12594 } 12595 12596 // Create vectors for any values that has duplicates. 12597 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12598 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12599 if (!ValidDuplicateEnum(ECD, Enum)) 12600 continue; 12601 12602 DupKey Key = GetDupKey(ECD->getInitVal()); 12603 12604 DeclOrVector& Entry = EnumMap[Key]; 12605 if (Entry.isNull()) 12606 continue; 12607 12608 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12609 // Ensure constants are different. 12610 if (D == ECD) 12611 continue; 12612 12613 // Create new vector and push values onto it. 12614 ECDVector *Vec = new ECDVector(); 12615 Vec->push_back(D); 12616 Vec->push_back(ECD); 12617 12618 // Update entry to point to the duplicates vector. 12619 Entry = Vec; 12620 12621 // Store the vector somewhere we can consult later for quick emission of 12622 // diagnostics. 12623 DupVector.push_back(Vec); 12624 continue; 12625 } 12626 12627 ECDVector *Vec = Entry.get<ECDVector*>(); 12628 // Make sure constants are not added more than once. 12629 if (*Vec->begin() == ECD) 12630 continue; 12631 12632 Vec->push_back(ECD); 12633 } 12634 12635 // Emit diagnostics. 12636 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12637 DupVectorEnd = DupVector.end(); 12638 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12639 ECDVector *Vec = *DupVectorIter; 12640 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12641 12642 // Emit warning for one enum constant. 12643 ECDVector::iterator I = Vec->begin(); 12644 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12645 << (*I)->getName() << (*I)->getInitVal().toString(10) 12646 << (*I)->getSourceRange(); 12647 ++I; 12648 12649 // Emit one note for each of the remaining enum constants with 12650 // the same value. 12651 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12652 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12653 << (*I)->getName() << (*I)->getInitVal().toString(10) 12654 << (*I)->getSourceRange(); 12655 delete Vec; 12656 } 12657} 12658 12659void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12660 SourceLocation RBraceLoc, Decl *EnumDeclX, 12661 ArrayRef<Decl *> Elements, 12662 Scope *S, AttributeList *Attr) { 12663 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12664 QualType EnumType = Context.getTypeDeclType(Enum); 12665 12666 if (Attr) 12667 ProcessDeclAttributeList(S, Enum, Attr); 12668 12669 if (Enum->isDependentType()) { 12670 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12671 EnumConstantDecl *ECD = 12672 cast_or_null<EnumConstantDecl>(Elements[i]); 12673 if (!ECD) continue; 12674 12675 ECD->setType(EnumType); 12676 } 12677 12678 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12679 return; 12680 } 12681 12682 // TODO: If the result value doesn't fit in an int, it must be a long or long 12683 // long value. ISO C does not support this, but GCC does as an extension, 12684 // emit a warning. 12685 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12686 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12687 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12688 12689 // Verify that all the values are okay, compute the size of the values, and 12690 // reverse the list. 12691 unsigned NumNegativeBits = 0; 12692 unsigned NumPositiveBits = 0; 12693 12694 // Keep track of whether all elements have type int. 12695 bool AllElementsInt = true; 12696 12697 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12698 EnumConstantDecl *ECD = 12699 cast_or_null<EnumConstantDecl>(Elements[i]); 12700 if (!ECD) continue; // Already issued a diagnostic. 12701 12702 const llvm::APSInt &InitVal = ECD->getInitVal(); 12703 12704 // Keep track of the size of positive and negative values. 12705 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12706 NumPositiveBits = std::max(NumPositiveBits, 12707 (unsigned)InitVal.getActiveBits()); 12708 else 12709 NumNegativeBits = std::max(NumNegativeBits, 12710 (unsigned)InitVal.getMinSignedBits()); 12711 12712 // Keep track of whether every enum element has type int (very commmon). 12713 if (AllElementsInt) 12714 AllElementsInt = ECD->getType() == Context.IntTy; 12715 } 12716 12717 // Figure out the type that should be used for this enum. 12718 QualType BestType; 12719 unsigned BestWidth; 12720 12721 // C++0x N3000 [conv.prom]p3: 12722 // An rvalue of an unscoped enumeration type whose underlying 12723 // type is not fixed can be converted to an rvalue of the first 12724 // of the following types that can represent all the values of 12725 // the enumeration: int, unsigned int, long int, unsigned long 12726 // int, long long int, or unsigned long long int. 12727 // C99 6.4.4.3p2: 12728 // An identifier declared as an enumeration constant has type int. 12729 // The C99 rule is modified by a gcc extension 12730 QualType BestPromotionType; 12731 12732 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 12733 // -fshort-enums is the equivalent to specifying the packed attribute on all 12734 // enum definitions. 12735 if (LangOpts.ShortEnums) 12736 Packed = true; 12737 12738 if (Enum->isFixed()) { 12739 BestType = Enum->getIntegerType(); 12740 if (BestType->isPromotableIntegerType()) 12741 BestPromotionType = Context.getPromotedIntegerType(BestType); 12742 else 12743 BestPromotionType = BestType; 12744 // We don't need to set BestWidth, because BestType is going to be the type 12745 // of the enumerators, but we do anyway because otherwise some compilers 12746 // warn that it might be used uninitialized. 12747 BestWidth = CharWidth; 12748 } 12749 else if (NumNegativeBits) { 12750 // If there is a negative value, figure out the smallest integer type (of 12751 // int/long/longlong) that fits. 12752 // If it's packed, check also if it fits a char or a short. 12753 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12754 BestType = Context.SignedCharTy; 12755 BestWidth = CharWidth; 12756 } else if (Packed && NumNegativeBits <= ShortWidth && 12757 NumPositiveBits < ShortWidth) { 12758 BestType = Context.ShortTy; 12759 BestWidth = ShortWidth; 12760 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12761 BestType = Context.IntTy; 12762 BestWidth = IntWidth; 12763 } else { 12764 BestWidth = Context.getTargetInfo().getLongWidth(); 12765 12766 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12767 BestType = Context.LongTy; 12768 } else { 12769 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12770 12771 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12772 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12773 BestType = Context.LongLongTy; 12774 } 12775 } 12776 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12777 } else { 12778 // If there is no negative value, figure out the smallest type that fits 12779 // all of the enumerator values. 12780 // If it's packed, check also if it fits a char or a short. 12781 if (Packed && NumPositiveBits <= CharWidth) { 12782 BestType = Context.UnsignedCharTy; 12783 BestPromotionType = Context.IntTy; 12784 BestWidth = CharWidth; 12785 } else if (Packed && NumPositiveBits <= ShortWidth) { 12786 BestType = Context.UnsignedShortTy; 12787 BestPromotionType = Context.IntTy; 12788 BestWidth = ShortWidth; 12789 } else if (NumPositiveBits <= IntWidth) { 12790 BestType = Context.UnsignedIntTy; 12791 BestWidth = IntWidth; 12792 BestPromotionType 12793 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12794 ? Context.UnsignedIntTy : Context.IntTy; 12795 } else if (NumPositiveBits <= 12796 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12797 BestType = Context.UnsignedLongTy; 12798 BestPromotionType 12799 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12800 ? Context.UnsignedLongTy : Context.LongTy; 12801 } else { 12802 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12803 assert(NumPositiveBits <= BestWidth && 12804 "How could an initializer get larger than ULL?"); 12805 BestType = Context.UnsignedLongLongTy; 12806 BestPromotionType 12807 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12808 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12809 } 12810 } 12811 12812 // Loop over all of the enumerator constants, changing their types to match 12813 // the type of the enum if needed. 12814 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12815 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12816 if (!ECD) continue; // Already issued a diagnostic. 12817 12818 // Standard C says the enumerators have int type, but we allow, as an 12819 // extension, the enumerators to be larger than int size. If each 12820 // enumerator value fits in an int, type it as an int, otherwise type it the 12821 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12822 // that X has type 'int', not 'unsigned'. 12823 12824 // Determine whether the value fits into an int. 12825 llvm::APSInt InitVal = ECD->getInitVal(); 12826 12827 // If it fits into an integer type, force it. Otherwise force it to match 12828 // the enum decl type. 12829 QualType NewTy; 12830 unsigned NewWidth; 12831 bool NewSign; 12832 if (!getLangOpts().CPlusPlus && 12833 !Enum->isFixed() && 12834 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12835 NewTy = Context.IntTy; 12836 NewWidth = IntWidth; 12837 NewSign = true; 12838 } else if (ECD->getType() == BestType) { 12839 // Already the right type! 12840 if (getLangOpts().CPlusPlus) 12841 // C++ [dcl.enum]p4: Following the closing brace of an 12842 // enum-specifier, each enumerator has the type of its 12843 // enumeration. 12844 ECD->setType(EnumType); 12845 continue; 12846 } else { 12847 NewTy = BestType; 12848 NewWidth = BestWidth; 12849 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12850 } 12851 12852 // Adjust the APSInt value. 12853 InitVal = InitVal.extOrTrunc(NewWidth); 12854 InitVal.setIsSigned(NewSign); 12855 ECD->setInitVal(InitVal); 12856 12857 // Adjust the Expr initializer and type. 12858 if (ECD->getInitExpr() && 12859 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12860 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12861 CK_IntegralCast, 12862 ECD->getInitExpr(), 12863 /*base paths*/ 0, 12864 VK_RValue)); 12865 if (getLangOpts().CPlusPlus) 12866 // C++ [dcl.enum]p4: Following the closing brace of an 12867 // enum-specifier, each enumerator has the type of its 12868 // enumeration. 12869 ECD->setType(EnumType); 12870 else 12871 ECD->setType(NewTy); 12872 } 12873 12874 Enum->completeDefinition(BestType, BestPromotionType, 12875 NumPositiveBits, NumNegativeBits); 12876 12877 // If we're declaring a function, ensure this decl isn't forgotten about - 12878 // it needs to go into the function scope. 12879 if (InFunctionDeclarator) 12880 DeclsInPrototypeScope.push_back(Enum); 12881 12882 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12883 12884 // Now that the enum type is defined, ensure it's not been underaligned. 12885 if (Enum->hasAttrs()) 12886 CheckAlignasUnderalignment(Enum); 12887} 12888 12889Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12890 SourceLocation StartLoc, 12891 SourceLocation EndLoc) { 12892 StringLiteral *AsmString = cast<StringLiteral>(expr); 12893 12894 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12895 AsmString, StartLoc, 12896 EndLoc); 12897 CurContext->addDecl(New); 12898 return New; 12899} 12900 12901DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12902 SourceLocation ImportLoc, 12903 ModuleIdPath Path) { 12904 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12905 Module::AllVisible, 12906 /*IsIncludeDirective=*/false); 12907 if (!Mod) 12908 return true; 12909 12910 SmallVector<SourceLocation, 2> IdentifierLocs; 12911 Module *ModCheck = Mod; 12912 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12913 // If we've run out of module parents, just drop the remaining identifiers. 12914 // We need the length to be consistent. 12915 if (!ModCheck) 12916 break; 12917 ModCheck = ModCheck->Parent; 12918 12919 IdentifierLocs.push_back(Path[I].second); 12920 } 12921 12922 ImportDecl *Import = ImportDecl::Create(Context, 12923 Context.getTranslationUnitDecl(), 12924 AtLoc.isValid()? AtLoc : ImportLoc, 12925 Mod, IdentifierLocs); 12926 Context.getTranslationUnitDecl()->addDecl(Import); 12927 return Import; 12928} 12929 12930void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 12931 // FIXME: Should we synthesize an ImportDecl here? 12932 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 12933 /*Complain=*/true); 12934} 12935 12936void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 12937 // Create the implicit import declaration. 12938 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 12939 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 12940 Loc, Mod, Loc); 12941 TU->addDecl(ImportD); 12942 Consumer.HandleImplicitImportDecl(ImportD); 12943 12944 // Make the module visible. 12945 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 12946 /*Complain=*/false); 12947} 12948 12949void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 12950 IdentifierInfo* AliasName, 12951 SourceLocation PragmaLoc, 12952 SourceLocation NameLoc, 12953 SourceLocation AliasNameLoc) { 12954 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 12955 LookupOrdinaryName); 12956 AsmLabelAttr *Attr = 12957 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 12958 12959 if (PrevDecl) 12960 PrevDecl->addAttr(Attr); 12961 else 12962 (void)ExtnameUndeclaredIdentifiers.insert( 12963 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 12964} 12965 12966void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 12967 SourceLocation PragmaLoc, 12968 SourceLocation NameLoc) { 12969 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 12970 12971 if (PrevDecl) { 12972 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 12973 } else { 12974 (void)WeakUndeclaredIdentifiers.insert( 12975 std::pair<IdentifierInfo*,WeakInfo> 12976 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 12977 } 12978} 12979 12980void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 12981 IdentifierInfo* AliasName, 12982 SourceLocation PragmaLoc, 12983 SourceLocation NameLoc, 12984 SourceLocation AliasNameLoc) { 12985 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 12986 LookupOrdinaryName); 12987 WeakInfo W = WeakInfo(Name, NameLoc); 12988 12989 if (PrevDecl) { 12990 if (!PrevDecl->hasAttr<AliasAttr>()) 12991 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 12992 DeclApplyPragmaWeak(TUScope, ND, W); 12993 } else { 12994 (void)WeakUndeclaredIdentifiers.insert( 12995 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 12996 } 12997} 12998 12999Decl *Sema::getObjCDeclContext() const { 13000 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13001} 13002 13003AvailabilityResult Sema::getCurContextAvailability() const { 13004 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13005 return D->getAvailability(); 13006} 13007