SemaDecl.cpp revision 6f6dc158ee2fbe5b9b8685dad45be02cba0873f5
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 "llvm/ADT/SmallString.h" 44#include "llvm/ADT/Triple.h" 45#include <algorithm> 46#include <cstring> 47#include <functional> 48using namespace clang; 49using namespace sema; 50 51Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 52 if (OwnedType) { 53 Decl *Group[2] = { OwnedType, Ptr }; 54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 55 } 56 57 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 58} 59 60namespace { 61 62class TypeNameValidatorCCC : public CorrectionCandidateCallback { 63 public: 64 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 66 WantExpressionKeywords = false; 67 WantCXXNamedCasts = false; 68 WantRemainingKeywords = false; 69 } 70 71 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 72 if (NamedDecl *ND = candidate.getCorrectionDecl()) 73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 74 (AllowInvalidDecl || !ND->isInvalidDecl()); 75 else 76 return !WantClassName && candidate.isKeyword(); 77 } 78 79 private: 80 bool AllowInvalidDecl; 81 bool WantClassName; 82}; 83 84} 85 86/// \brief Determine whether the token kind starts a simple-type-specifier. 87bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 88 switch (Kind) { 89 // FIXME: Take into account the current language when deciding whether a 90 // token kind is a valid type specifier 91 case tok::kw_short: 92 case tok::kw_long: 93 case tok::kw___int64: 94 case tok::kw___int128: 95 case tok::kw_signed: 96 case tok::kw_unsigned: 97 case tok::kw_void: 98 case tok::kw_char: 99 case tok::kw_int: 100 case tok::kw_half: 101 case tok::kw_float: 102 case tok::kw_double: 103 case tok::kw_wchar_t: 104 case tok::kw_bool: 105 case tok::kw___underlying_type: 106 return true; 107 108 case tok::annot_typename: 109 case tok::kw_char16_t: 110 case tok::kw_char32_t: 111 case tok::kw_typeof: 112 case tok::annot_decltype: 113 case tok::kw_decltype: 114 return getLangOpts().CPlusPlus; 115 116 default: 117 break; 118 } 119 120 return false; 121} 122 123/// \brief If the identifier refers to a type name within this scope, 124/// return the declaration of that type. 125/// 126/// This routine performs ordinary name lookup of the identifier II 127/// within the given scope, with optional C++ scope specifier SS, to 128/// determine whether the name refers to a type. If so, returns an 129/// opaque pointer (actually a QualType) corresponding to that 130/// type. Otherwise, returns NULL. 131ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 132 Scope *S, CXXScopeSpec *SS, 133 bool isClassName, bool HasTrailingDot, 134 ParsedType ObjectTypePtr, 135 bool IsCtorOrDtorName, 136 bool WantNontrivialTypeSourceInfo, 137 IdentifierInfo **CorrectedII) { 138 // Determine where we will perform name lookup. 139 DeclContext *LookupCtx = 0; 140 if (ObjectTypePtr) { 141 QualType ObjectType = ObjectTypePtr.get(); 142 if (ObjectType->isRecordType()) 143 LookupCtx = computeDeclContext(ObjectType); 144 } else if (SS && SS->isNotEmpty()) { 145 LookupCtx = computeDeclContext(*SS, false); 146 147 if (!LookupCtx) { 148 if (isDependentScopeSpecifier(*SS)) { 149 // C++ [temp.res]p3: 150 // A qualified-id that refers to a type and in which the 151 // nested-name-specifier depends on a template-parameter (14.6.2) 152 // shall be prefixed by the keyword typename to indicate that the 153 // qualified-id denotes a type, forming an 154 // elaborated-type-specifier (7.1.5.3). 155 // 156 // We therefore do not perform any name lookup if the result would 157 // refer to a member of an unknown specialization. 158 if (!isClassName && !IsCtorOrDtorName) 159 return ParsedType(); 160 161 // We know from the grammar that this name refers to a type, 162 // so build a dependent node to describe the type. 163 if (WantNontrivialTypeSourceInfo) 164 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 165 166 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 167 QualType T = 168 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 169 II, NameLoc); 170 171 return ParsedType::make(T); 172 } 173 174 return ParsedType(); 175 } 176 177 if (!LookupCtx->isDependentContext() && 178 RequireCompleteDeclContext(*SS, LookupCtx)) 179 return ParsedType(); 180 } 181 182 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 183 // lookup for class-names. 184 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 185 LookupOrdinaryName; 186 LookupResult Result(*this, &II, NameLoc, Kind); 187 if (LookupCtx) { 188 // Perform "qualified" name lookup into the declaration context we 189 // computed, which is either the type of the base of a member access 190 // expression or the declaration context associated with a prior 191 // nested-name-specifier. 192 LookupQualifiedName(Result, LookupCtx); 193 194 if (ObjectTypePtr && Result.empty()) { 195 // C++ [basic.lookup.classref]p3: 196 // If the unqualified-id is ~type-name, the type-name is looked up 197 // in the context of the entire postfix-expression. If the type T of 198 // the object expression is of a class type C, the type-name is also 199 // looked up in the scope of class C. At least one of the lookups shall 200 // find a name that refers to (possibly cv-qualified) T. 201 LookupName(Result, S); 202 } 203 } else { 204 // Perform unqualified name lookup. 205 LookupName(Result, S); 206 } 207 208 NamedDecl *IIDecl = 0; 209 switch (Result.getResultKind()) { 210 case LookupResult::NotFound: 211 case LookupResult::NotFoundInCurrentInstantiation: 212 if (CorrectedII) { 213 TypeNameValidatorCCC Validator(true, isClassName); 214 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 215 Kind, S, SS, Validator); 216 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 217 TemplateTy Template; 218 bool MemberOfUnknownSpecialization; 219 UnqualifiedId TemplateName; 220 TemplateName.setIdentifier(NewII, NameLoc); 221 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 222 CXXScopeSpec NewSS, *NewSSPtr = SS; 223 if (SS && NNS) { 224 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 225 NewSSPtr = &NewSS; 226 } 227 if (Correction && (NNS || NewII != &II) && 228 // Ignore a correction to a template type as the to-be-corrected 229 // identifier is not a template (typo correction for template names 230 // is handled elsewhere). 231 !(getLangOpts().CPlusPlus && NewSSPtr && 232 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 233 false, Template, MemberOfUnknownSpecialization))) { 234 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 235 isClassName, HasTrailingDot, ObjectTypePtr, 236 IsCtorOrDtorName, 237 WantNontrivialTypeSourceInfo); 238 if (Ty) { 239 diagnoseTypo(Correction, 240 PDiag(diag::err_unknown_type_or_class_name_suggest) 241 << Result.getLookupName() << isClassName); 242 if (SS && NNS) 243 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 244 *CorrectedII = NewII; 245 return Ty; 246 } 247 } 248 } 249 // If typo correction failed or was not performed, fall through 250 case LookupResult::FoundOverloaded: 251 case LookupResult::FoundUnresolvedValue: 252 Result.suppressDiagnostics(); 253 return ParsedType(); 254 255 case LookupResult::Ambiguous: 256 // Recover from type-hiding ambiguities by hiding the type. We'll 257 // do the lookup again when looking for an object, and we can 258 // diagnose the error then. If we don't do this, then the error 259 // about hiding the type will be immediately followed by an error 260 // that only makes sense if the identifier was treated like a type. 261 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 262 Result.suppressDiagnostics(); 263 return ParsedType(); 264 } 265 266 // Look to see if we have a type anywhere in the list of results. 267 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 268 Res != ResEnd; ++Res) { 269 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 270 if (!IIDecl || 271 (*Res)->getLocation().getRawEncoding() < 272 IIDecl->getLocation().getRawEncoding()) 273 IIDecl = *Res; 274 } 275 } 276 277 if (!IIDecl) { 278 // None of the entities we found is a type, so there is no way 279 // to even assume that the result is a type. In this case, don't 280 // complain about the ambiguity. The parser will either try to 281 // perform this lookup again (e.g., as an object name), which 282 // will produce the ambiguity, or will complain that it expected 283 // a type name. 284 Result.suppressDiagnostics(); 285 return ParsedType(); 286 } 287 288 // We found a type within the ambiguous lookup; diagnose the 289 // ambiguity and then return that type. This might be the right 290 // answer, or it might not be, but it suppresses any attempt to 291 // perform the name lookup again. 292 break; 293 294 case LookupResult::Found: 295 IIDecl = Result.getFoundDecl(); 296 break; 297 } 298 299 assert(IIDecl && "Didn't find decl"); 300 301 QualType T; 302 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 303 DiagnoseUseOfDecl(IIDecl, NameLoc); 304 305 if (T.isNull()) 306 T = Context.getTypeDeclType(TD); 307 308 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 309 // constructor or destructor name (in such a case, the scope specifier 310 // will be attached to the enclosing Expr or Decl node). 311 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 312 if (WantNontrivialTypeSourceInfo) { 313 // Construct a type with type-source information. 314 TypeLocBuilder Builder; 315 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 316 317 T = getElaboratedType(ETK_None, *SS, T); 318 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 319 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 320 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 321 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 322 } else { 323 T = getElaboratedType(ETK_None, *SS, T); 324 } 325 } 326 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 327 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 328 if (!HasTrailingDot) 329 T = Context.getObjCInterfaceType(IDecl); 330 } 331 332 if (T.isNull()) { 333 // If it's not plausibly a type, suppress diagnostics. 334 Result.suppressDiagnostics(); 335 return ParsedType(); 336 } 337 return ParsedType::make(T); 338} 339 340/// isTagName() - This method is called *for error recovery purposes only* 341/// to determine if the specified name is a valid tag name ("struct foo"). If 342/// so, this returns the TST for the tag corresponding to it (TST_enum, 343/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 344/// cases in C where the user forgot to specify the tag. 345DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 346 // Do a tag name lookup in this scope. 347 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 348 LookupName(R, S, false); 349 R.suppressDiagnostics(); 350 if (R.getResultKind() == LookupResult::Found) 351 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 352 switch (TD->getTagKind()) { 353 case TTK_Struct: return DeclSpec::TST_struct; 354 case TTK_Interface: return DeclSpec::TST_interface; 355 case TTK_Union: return DeclSpec::TST_union; 356 case TTK_Class: return DeclSpec::TST_class; 357 case TTK_Enum: return DeclSpec::TST_enum; 358 } 359 } 360 361 return DeclSpec::TST_unspecified; 362} 363 364/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 365/// if a CXXScopeSpec's type is equal to the type of one of the base classes 366/// then downgrade the missing typename error to a warning. 367/// This is needed for MSVC compatibility; Example: 368/// @code 369/// template<class T> class A { 370/// public: 371/// typedef int TYPE; 372/// }; 373/// template<class T> class B : public A<T> { 374/// public: 375/// A<T>::TYPE a; // no typename required because A<T> is a base class. 376/// }; 377/// @endcode 378bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 379 if (CurContext->isRecord()) { 380 const Type *Ty = SS->getScopeRep()->getAsType(); 381 382 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 383 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 384 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 385 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 386 return true; 387 return S->isFunctionPrototypeScope(); 388 } 389 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 390} 391 392bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 393 SourceLocation IILoc, 394 Scope *S, 395 CXXScopeSpec *SS, 396 ParsedType &SuggestedType) { 397 // We don't have anything to suggest (yet). 398 SuggestedType = ParsedType(); 399 400 // There may have been a typo in the name of the type. Look up typo 401 // results, in case we have something that we can suggest. 402 TypeNameValidatorCCC Validator(false); 403 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 404 LookupOrdinaryName, S, SS, 405 Validator)) { 406 if (Corrected.isKeyword()) { 407 // We corrected to a keyword. 408 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 409 II = Corrected.getCorrectionAsIdentifierInfo(); 410 } else { 411 // We found a similarly-named type or interface; suggest that. 412 if (!SS || !SS->isSet()) { 413 diagnoseTypo(Corrected, 414 PDiag(diag::err_unknown_typename_suggest) << II); 415 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 416 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 417 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 418 II->getName().equals(CorrectedStr); 419 diagnoseTypo(Corrected, 420 PDiag(diag::err_unknown_nested_typename_suggest) 421 << II << DC << DroppedSpecifier << SS->getRange()); 422 } else { 423 llvm_unreachable("could not have corrected a typo here"); 424 } 425 426 CXXScopeSpec tmpSS; 427 if (Corrected.getCorrectionSpecifier()) 428 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 429 SourceRange(IILoc)); 430 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 431 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 432 false, ParsedType(), 433 /*IsCtorOrDtorName=*/false, 434 /*NonTrivialTypeSourceInfo=*/true); 435 } 436 return true; 437 } 438 439 if (getLangOpts().CPlusPlus) { 440 // See if II is a class template that the user forgot to pass arguments to. 441 UnqualifiedId Name; 442 Name.setIdentifier(II, IILoc); 443 CXXScopeSpec EmptySS; 444 TemplateTy TemplateResult; 445 bool MemberOfUnknownSpecialization; 446 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 447 Name, ParsedType(), true, TemplateResult, 448 MemberOfUnknownSpecialization) == TNK_Type_template) { 449 TemplateName TplName = TemplateResult.get(); 450 Diag(IILoc, diag::err_template_missing_args) << TplName; 451 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 452 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 453 << TplDecl->getTemplateParameters()->getSourceRange(); 454 } 455 return true; 456 } 457 } 458 459 // FIXME: Should we move the logic that tries to recover from a missing tag 460 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 461 462 if (!SS || (!SS->isSet() && !SS->isInvalid())) 463 Diag(IILoc, diag::err_unknown_typename) << II; 464 else if (DeclContext *DC = computeDeclContext(*SS, false)) 465 Diag(IILoc, diag::err_typename_nested_not_found) 466 << II << DC << SS->getRange(); 467 else if (isDependentScopeSpecifier(*SS)) { 468 unsigned DiagID = diag::err_typename_missing; 469 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 470 DiagID = diag::warn_typename_missing; 471 472 Diag(SS->getRange().getBegin(), DiagID) 473 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 474 << SourceRange(SS->getRange().getBegin(), IILoc) 475 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 476 SuggestedType = ActOnTypenameType(S, SourceLocation(), 477 *SS, *II, IILoc).get(); 478 } else { 479 assert(SS && SS->isInvalid() && 480 "Invalid scope specifier has already been diagnosed"); 481 } 482 483 return true; 484} 485 486/// \brief Determine whether the given result set contains either a type name 487/// or 488static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 489 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 490 NextToken.is(tok::less); 491 492 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 493 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 494 return true; 495 496 if (CheckTemplate && isa<TemplateDecl>(*I)) 497 return true; 498 } 499 500 return false; 501} 502 503static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 504 Scope *S, CXXScopeSpec &SS, 505 IdentifierInfo *&Name, 506 SourceLocation NameLoc) { 507 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 508 SemaRef.LookupParsedName(R, S, &SS); 509 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 510 const char *TagName = 0; 511 const char *FixItTagName = 0; 512 switch (Tag->getTagKind()) { 513 case TTK_Class: 514 TagName = "class"; 515 FixItTagName = "class "; 516 break; 517 518 case TTK_Enum: 519 TagName = "enum"; 520 FixItTagName = "enum "; 521 break; 522 523 case TTK_Struct: 524 TagName = "struct"; 525 FixItTagName = "struct "; 526 break; 527 528 case TTK_Interface: 529 TagName = "__interface"; 530 FixItTagName = "__interface "; 531 break; 532 533 case TTK_Union: 534 TagName = "union"; 535 FixItTagName = "union "; 536 break; 537 } 538 539 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 540 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 541 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 542 543 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 544 I != IEnd; ++I) 545 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 546 << Name << TagName; 547 548 // Replace lookup results with just the tag decl. 549 Result.clear(Sema::LookupTagName); 550 SemaRef.LookupParsedName(Result, S, &SS); 551 return true; 552 } 553 554 return false; 555} 556 557/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 558static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 559 QualType T, SourceLocation NameLoc) { 560 ASTContext &Context = S.Context; 561 562 TypeLocBuilder Builder; 563 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 564 565 T = S.getElaboratedType(ETK_None, SS, T); 566 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 567 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 568 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 569 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 570} 571 572Sema::NameClassification Sema::ClassifyName(Scope *S, 573 CXXScopeSpec &SS, 574 IdentifierInfo *&Name, 575 SourceLocation NameLoc, 576 const Token &NextToken, 577 bool IsAddressOfOperand, 578 CorrectionCandidateCallback *CCC) { 579 DeclarationNameInfo NameInfo(Name, NameLoc); 580 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 581 582 if (NextToken.is(tok::coloncolon)) { 583 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 584 QualType(), false, SS, 0, false); 585 586 } 587 588 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 589 LookupParsedName(Result, S, &SS, !CurMethod); 590 591 // Perform lookup for Objective-C instance variables (including automatically 592 // synthesized instance variables), if we're in an Objective-C method. 593 // FIXME: This lookup really, really needs to be folded in to the normal 594 // unqualified lookup mechanism. 595 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 596 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 597 if (E.get() || E.isInvalid()) 598 return E; 599 } 600 601 bool SecondTry = false; 602 bool IsFilteredTemplateName = false; 603 604Corrected: 605 switch (Result.getResultKind()) { 606 case LookupResult::NotFound: 607 // If an unqualified-id is followed by a '(', then we have a function 608 // call. 609 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 610 // In C++, this is an ADL-only call. 611 // FIXME: Reference? 612 if (getLangOpts().CPlusPlus) 613 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 614 615 // C90 6.3.2.2: 616 // If the expression that precedes the parenthesized argument list in a 617 // function call consists solely of an identifier, and if no 618 // declaration is visible for this identifier, the identifier is 619 // implicitly declared exactly as if, in the innermost block containing 620 // the function call, the declaration 621 // 622 // extern int identifier (); 623 // 624 // appeared. 625 // 626 // We also allow this in C99 as an extension. 627 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 628 Result.addDecl(D); 629 Result.resolveKind(); 630 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 631 } 632 } 633 634 // In C, we first see whether there is a tag type by the same name, in 635 // which case it's likely that the user just forget to write "enum", 636 // "struct", or "union". 637 if (!getLangOpts().CPlusPlus && !SecondTry && 638 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 639 break; 640 } 641 642 // Perform typo correction to determine if there is another name that is 643 // close to this name. 644 if (!SecondTry && CCC) { 645 SecondTry = true; 646 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 647 Result.getLookupKind(), S, 648 &SS, *CCC)) { 649 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 650 unsigned QualifiedDiag = diag::err_no_member_suggest; 651 652 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 653 NamedDecl *UnderlyingFirstDecl 654 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 655 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 656 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 657 UnqualifiedDiag = diag::err_no_template_suggest; 658 QualifiedDiag = diag::err_no_member_template_suggest; 659 } else if (UnderlyingFirstDecl && 660 (isa<TypeDecl>(UnderlyingFirstDecl) || 661 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 662 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 663 UnqualifiedDiag = diag::err_unknown_typename_suggest; 664 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 665 } 666 667 if (SS.isEmpty()) { 668 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 669 } else {// FIXME: is this even reachable? Test it. 670 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 671 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 672 Name->getName().equals(CorrectedStr); 673 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 674 << Name << computeDeclContext(SS, false) 675 << DroppedSpecifier << SS.getRange()); 676 } 677 678 // Update the name, so that the caller has the new name. 679 Name = Corrected.getCorrectionAsIdentifierInfo(); 680 681 // Typo correction corrected to a keyword. 682 if (Corrected.isKeyword()) 683 return Name; 684 685 // Also update the LookupResult... 686 // FIXME: This should probably go away at some point 687 Result.clear(); 688 Result.setLookupName(Corrected.getCorrection()); 689 if (FirstDecl) 690 Result.addDecl(FirstDecl); 691 692 // If we found an Objective-C instance variable, let 693 // LookupInObjCMethod build the appropriate expression to 694 // reference the ivar. 695 // FIXME: This is a gross hack. 696 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 697 Result.clear(); 698 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 699 return E; 700 } 701 702 goto Corrected; 703 } 704 } 705 706 // We failed to correct; just fall through and let the parser deal with it. 707 Result.suppressDiagnostics(); 708 return NameClassification::Unknown(); 709 710 case LookupResult::NotFoundInCurrentInstantiation: { 711 // We performed name lookup into the current instantiation, and there were 712 // dependent bases, so we treat this result the same way as any other 713 // dependent nested-name-specifier. 714 715 // C++ [temp.res]p2: 716 // A name used in a template declaration or definition and that is 717 // dependent on a template-parameter is assumed not to name a type 718 // unless the applicable name lookup finds a type name or the name is 719 // qualified by the keyword typename. 720 // 721 // FIXME: If the next token is '<', we might want to ask the parser to 722 // perform some heroics to see if we actually have a 723 // template-argument-list, which would indicate a missing 'template' 724 // keyword here. 725 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 726 NameInfo, IsAddressOfOperand, 727 /*TemplateArgs=*/0); 728 } 729 730 case LookupResult::Found: 731 case LookupResult::FoundOverloaded: 732 case LookupResult::FoundUnresolvedValue: 733 break; 734 735 case LookupResult::Ambiguous: 736 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 737 hasAnyAcceptableTemplateNames(Result)) { 738 // C++ [temp.local]p3: 739 // A lookup that finds an injected-class-name (10.2) can result in an 740 // ambiguity in certain cases (for example, if it is found in more than 741 // one base class). If all of the injected-class-names that are found 742 // refer to specializations of the same class template, and if the name 743 // is followed by a template-argument-list, the reference refers to the 744 // class template itself and not a specialization thereof, and is not 745 // ambiguous. 746 // 747 // This filtering can make an ambiguous result into an unambiguous one, 748 // so try again after filtering out template names. 749 FilterAcceptableTemplateNames(Result); 750 if (!Result.isAmbiguous()) { 751 IsFilteredTemplateName = true; 752 break; 753 } 754 } 755 756 // Diagnose the ambiguity and return an error. 757 return NameClassification::Error(); 758 } 759 760 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 761 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 762 // C++ [temp.names]p3: 763 // After name lookup (3.4) finds that a name is a template-name or that 764 // an operator-function-id or a literal- operator-id refers to a set of 765 // overloaded functions any member of which is a function template if 766 // this is followed by a <, the < is always taken as the delimiter of a 767 // template-argument-list and never as the less-than operator. 768 if (!IsFilteredTemplateName) 769 FilterAcceptableTemplateNames(Result); 770 771 if (!Result.empty()) { 772 bool IsFunctionTemplate; 773 bool IsVarTemplate; 774 TemplateName Template; 775 if (Result.end() - Result.begin() > 1) { 776 IsFunctionTemplate = true; 777 Template = Context.getOverloadedTemplateName(Result.begin(), 778 Result.end()); 779 } else { 780 TemplateDecl *TD 781 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 782 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 783 IsVarTemplate = isa<VarTemplateDecl>(TD); 784 785 if (SS.isSet() && !SS.isInvalid()) 786 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 787 /*TemplateKeyword=*/false, 788 TD); 789 else 790 Template = TemplateName(TD); 791 } 792 793 if (IsFunctionTemplate) { 794 // Function templates always go through overload resolution, at which 795 // point we'll perform the various checks (e.g., accessibility) we need 796 // to based on which function we selected. 797 Result.suppressDiagnostics(); 798 799 return NameClassification::FunctionTemplate(Template); 800 } 801 802 return IsVarTemplate ? NameClassification::VarTemplate(Template) 803 : NameClassification::TypeTemplate(Template); 804 } 805 } 806 807 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 808 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 809 DiagnoseUseOfDecl(Type, NameLoc); 810 QualType T = Context.getTypeDeclType(Type); 811 if (SS.isNotEmpty()) 812 return buildNestedType(*this, SS, T, NameLoc); 813 return ParsedType::make(T); 814 } 815 816 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 817 if (!Class) { 818 // FIXME: It's unfortunate that we don't have a Type node for handling this. 819 if (ObjCCompatibleAliasDecl *Alias 820 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 821 Class = Alias->getClassInterface(); 822 } 823 824 if (Class) { 825 DiagnoseUseOfDecl(Class, NameLoc); 826 827 if (NextToken.is(tok::period)) { 828 // Interface. <something> is parsed as a property reference expression. 829 // Just return "unknown" as a fall-through for now. 830 Result.suppressDiagnostics(); 831 return NameClassification::Unknown(); 832 } 833 834 QualType T = Context.getObjCInterfaceType(Class); 835 return ParsedType::make(T); 836 } 837 838 // We can have a type template here if we're classifying a template argument. 839 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 840 return NameClassification::TypeTemplate( 841 TemplateName(cast<TemplateDecl>(FirstDecl))); 842 843 // Check for a tag type hidden by a non-type decl in a few cases where it 844 // seems likely a type is wanted instead of the non-type that was found. 845 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 846 if ((NextToken.is(tok::identifier) || 847 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 848 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 849 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 850 DiagnoseUseOfDecl(Type, NameLoc); 851 QualType T = Context.getTypeDeclType(Type); 852 if (SS.isNotEmpty()) 853 return buildNestedType(*this, SS, T, NameLoc); 854 return ParsedType::make(T); 855 } 856 857 if (FirstDecl->isCXXClassMember()) 858 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 859 860 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 861 return BuildDeclarationNameExpr(SS, Result, ADL); 862} 863 864// Determines the context to return to after temporarily entering a 865// context. This depends in an unnecessarily complicated way on the 866// exact ordering of callbacks from the parser. 867DeclContext *Sema::getContainingDC(DeclContext *DC) { 868 869 // Functions defined inline within classes aren't parsed until we've 870 // finished parsing the top-level class, so the top-level class is 871 // the context we'll need to return to. 872 if (isa<FunctionDecl>(DC)) { 873 DC = DC->getLexicalParent(); 874 875 // A function not defined within a class will always return to its 876 // lexical context. 877 if (!isa<CXXRecordDecl>(DC)) 878 return DC; 879 880 // A C++ inline method/friend is parsed *after* the topmost class 881 // it was declared in is fully parsed ("complete"); the topmost 882 // class is the context we need to return to. 883 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 884 DC = RD; 885 886 // Return the declaration context of the topmost class the inline method is 887 // declared in. 888 return DC; 889 } 890 891 return DC->getLexicalParent(); 892} 893 894void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 895 assert(getContainingDC(DC) == CurContext && 896 "The next DeclContext should be lexically contained in the current one."); 897 CurContext = DC; 898 S->setEntity(DC); 899} 900 901void Sema::PopDeclContext() { 902 assert(CurContext && "DeclContext imbalance!"); 903 904 CurContext = getContainingDC(CurContext); 905 assert(CurContext && "Popped translation unit!"); 906} 907 908/// EnterDeclaratorContext - Used when we must lookup names in the context 909/// of a declarator's nested name specifier. 910/// 911void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 912 // C++0x [basic.lookup.unqual]p13: 913 // A name used in the definition of a static data member of class 914 // X (after the qualified-id of the static member) is looked up as 915 // if the name was used in a member function of X. 916 // C++0x [basic.lookup.unqual]p14: 917 // If a variable member of a namespace is defined outside of the 918 // scope of its namespace then any name used in the definition of 919 // the variable member (after the declarator-id) is looked up as 920 // if the definition of the variable member occurred in its 921 // namespace. 922 // Both of these imply that we should push a scope whose context 923 // is the semantic context of the declaration. We can't use 924 // PushDeclContext here because that context is not necessarily 925 // lexically contained in the current context. Fortunately, 926 // the containing scope should have the appropriate information. 927 928 assert(!S->getEntity() && "scope already has entity"); 929 930#ifndef NDEBUG 931 Scope *Ancestor = S->getParent(); 932 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 933 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 934#endif 935 936 CurContext = DC; 937 S->setEntity(DC); 938} 939 940void Sema::ExitDeclaratorContext(Scope *S) { 941 assert(S->getEntity() == CurContext && "Context imbalance!"); 942 943 // Switch back to the lexical context. The safety of this is 944 // enforced by an assert in EnterDeclaratorContext. 945 Scope *Ancestor = S->getParent(); 946 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 947 CurContext = Ancestor->getEntity(); 948 949 // We don't need to do anything with the scope, which is going to 950 // disappear. 951} 952 953 954void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 955 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 956 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 957 // We assume that the caller has already called 958 // ActOnReenterTemplateScope 959 FD = TFD->getTemplatedDecl(); 960 } 961 if (!FD) 962 return; 963 964 // Same implementation as PushDeclContext, but enters the context 965 // from the lexical parent, rather than the top-level class. 966 assert(CurContext == FD->getLexicalParent() && 967 "The next DeclContext should be lexically contained in the current one."); 968 CurContext = FD; 969 S->setEntity(CurContext); 970 971 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 972 ParmVarDecl *Param = FD->getParamDecl(P); 973 // If the parameter has an identifier, then add it to the scope 974 if (Param->getIdentifier()) { 975 S->AddDecl(Param); 976 IdResolver.AddDecl(Param); 977 } 978 } 979} 980 981 982void Sema::ActOnExitFunctionContext() { 983 // Same implementation as PopDeclContext, but returns to the lexical parent, 984 // rather than the top-level class. 985 assert(CurContext && "DeclContext imbalance!"); 986 CurContext = CurContext->getLexicalParent(); 987 assert(CurContext && "Popped translation unit!"); 988} 989 990 991/// \brief Determine whether we allow overloading of the function 992/// PrevDecl with another declaration. 993/// 994/// This routine determines whether overloading is possible, not 995/// whether some new function is actually an overload. It will return 996/// true in C++ (where we can always provide overloads) or, as an 997/// extension, in C when the previous function is already an 998/// overloaded function declaration or has the "overloadable" 999/// attribute. 1000static bool AllowOverloadingOfFunction(LookupResult &Previous, 1001 ASTContext &Context) { 1002 if (Context.getLangOpts().CPlusPlus) 1003 return true; 1004 1005 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1006 return true; 1007 1008 return (Previous.getResultKind() == LookupResult::Found 1009 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1010} 1011 1012/// Add this decl to the scope shadowed decl chains. 1013void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1014 // Move up the scope chain until we find the nearest enclosing 1015 // non-transparent context. The declaration will be introduced into this 1016 // scope. 1017 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1018 S = S->getParent(); 1019 1020 // Add scoped declarations into their context, so that they can be 1021 // found later. Declarations without a context won't be inserted 1022 // into any context. 1023 if (AddToContext) 1024 CurContext->addDecl(D); 1025 1026 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1027 // are function-local declarations. 1028 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1029 !D->getDeclContext()->getRedeclContext()->Equals( 1030 D->getLexicalDeclContext()->getRedeclContext()) && 1031 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1032 return; 1033 1034 // Template instantiations should also not be pushed into scope. 1035 if (isa<FunctionDecl>(D) && 1036 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1037 return; 1038 1039 // If this replaces anything in the current scope, 1040 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1041 IEnd = IdResolver.end(); 1042 for (; I != IEnd; ++I) { 1043 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1044 S->RemoveDecl(*I); 1045 IdResolver.RemoveDecl(*I); 1046 1047 // Should only need to replace one decl. 1048 break; 1049 } 1050 } 1051 1052 S->AddDecl(D); 1053 1054 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1055 // Implicitly-generated labels may end up getting generated in an order that 1056 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1057 // the label at the appropriate place in the identifier chain. 1058 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1059 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1060 if (IDC == CurContext) { 1061 if (!S->isDeclScope(*I)) 1062 continue; 1063 } else if (IDC->Encloses(CurContext)) 1064 break; 1065 } 1066 1067 IdResolver.InsertDeclAfter(I, D); 1068 } else { 1069 IdResolver.AddDecl(D); 1070 } 1071} 1072 1073void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1074 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1075 TUScope->AddDecl(D); 1076} 1077 1078bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1079 bool ExplicitInstantiationOrSpecialization) { 1080 return IdResolver.isDeclInScope(D, Ctx, S, 1081 ExplicitInstantiationOrSpecialization); 1082} 1083 1084Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1085 DeclContext *TargetDC = DC->getPrimaryContext(); 1086 do { 1087 if (DeclContext *ScopeDC = S->getEntity()) 1088 if (ScopeDC->getPrimaryContext() == TargetDC) 1089 return S; 1090 } while ((S = S->getParent())); 1091 1092 return 0; 1093} 1094 1095static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1096 DeclContext*, 1097 ASTContext&); 1098 1099/// Filters out lookup results that don't fall within the given scope 1100/// as determined by isDeclInScope. 1101void Sema::FilterLookupForScope(LookupResult &R, 1102 DeclContext *Ctx, Scope *S, 1103 bool ConsiderLinkage, 1104 bool ExplicitInstantiationOrSpecialization) { 1105 LookupResult::Filter F = R.makeFilter(); 1106 while (F.hasNext()) { 1107 NamedDecl *D = F.next(); 1108 1109 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1110 continue; 1111 1112 if (ConsiderLinkage && 1113 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1114 continue; 1115 1116 F.erase(); 1117 } 1118 1119 F.done(); 1120} 1121 1122static bool isUsingDecl(NamedDecl *D) { 1123 return isa<UsingShadowDecl>(D) || 1124 isa<UnresolvedUsingTypenameDecl>(D) || 1125 isa<UnresolvedUsingValueDecl>(D); 1126} 1127 1128/// Removes using shadow declarations from the lookup results. 1129static void RemoveUsingDecls(LookupResult &R) { 1130 LookupResult::Filter F = R.makeFilter(); 1131 while (F.hasNext()) 1132 if (isUsingDecl(F.next())) 1133 F.erase(); 1134 1135 F.done(); 1136} 1137 1138/// \brief Check for this common pattern: 1139/// @code 1140/// class S { 1141/// S(const S&); // DO NOT IMPLEMENT 1142/// void operator=(const S&); // DO NOT IMPLEMENT 1143/// }; 1144/// @endcode 1145static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1146 // FIXME: Should check for private access too but access is set after we get 1147 // the decl here. 1148 if (D->doesThisDeclarationHaveABody()) 1149 return false; 1150 1151 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1152 return CD->isCopyConstructor(); 1153 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1154 return Method->isCopyAssignmentOperator(); 1155 return false; 1156} 1157 1158// We need this to handle 1159// 1160// typedef struct { 1161// void *foo() { return 0; } 1162// } A; 1163// 1164// When we see foo we don't know if after the typedef we will get 'A' or '*A' 1165// for example. If 'A', foo will have external linkage. If we have '*A', 1166// foo will have no linkage. Since we can't know untill we get to the end 1167// of the typedef, this function finds out if D might have non external linkage. 1168// Callers should verify at the end of the TU if it D has external linkage or 1169// not. 1170bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1171 const DeclContext *DC = D->getDeclContext(); 1172 while (!DC->isTranslationUnit()) { 1173 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1174 if (!RD->hasNameForLinkage()) 1175 return true; 1176 } 1177 DC = DC->getParent(); 1178 } 1179 1180 return !D->isExternallyVisible(); 1181} 1182 1183// FIXME: This needs to be refactored; some other isInMainFile users want 1184// these semantics. 1185static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1186 if (S.TUKind != TU_Complete) 1187 return false; 1188 return S.SourceMgr.isInMainFile(Loc); 1189} 1190 1191bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1192 assert(D); 1193 1194 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1195 return false; 1196 1197 // Ignore class templates. 1198 if (D->getDeclContext()->isDependentContext() || 1199 D->getLexicalDeclContext()->isDependentContext()) 1200 return false; 1201 1202 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1203 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1204 return false; 1205 1206 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1207 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1208 return false; 1209 } else { 1210 // 'static inline' functions are defined in headers; don't warn. 1211 if (FD->isInlineSpecified() && 1212 !isMainFileLoc(*this, FD->getLocation())) 1213 return false; 1214 } 1215 1216 if (FD->doesThisDeclarationHaveABody() && 1217 Context.DeclMustBeEmitted(FD)) 1218 return false; 1219 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1220 // Constants and utility variables are defined in headers with internal 1221 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1222 // like "inline".) 1223 if (!isMainFileLoc(*this, VD->getLocation())) 1224 return false; 1225 1226 if (Context.DeclMustBeEmitted(VD)) 1227 return false; 1228 1229 if (VD->isStaticDataMember() && 1230 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1231 return false; 1232 } else { 1233 return false; 1234 } 1235 1236 // Only warn for unused decls internal to the translation unit. 1237 return mightHaveNonExternalLinkage(D); 1238} 1239 1240void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1241 if (!D) 1242 return; 1243 1244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1245 const FunctionDecl *First = FD->getFirstDecl(); 1246 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1247 return; // First should already be in the vector. 1248 } 1249 1250 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1251 const VarDecl *First = VD->getFirstDecl(); 1252 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1253 return; // First should already be in the vector. 1254 } 1255 1256 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1257 UnusedFileScopedDecls.push_back(D); 1258} 1259 1260static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1261 if (D->isInvalidDecl()) 1262 return false; 1263 1264 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1265 return false; 1266 1267 if (isa<LabelDecl>(D)) 1268 return true; 1269 1270 // White-list anything that isn't a local variable. 1271 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1272 !D->getDeclContext()->isFunctionOrMethod()) 1273 return false; 1274 1275 // Types of valid local variables should be complete, so this should succeed. 1276 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1277 1278 // White-list anything with an __attribute__((unused)) type. 1279 QualType Ty = VD->getType(); 1280 1281 // Only look at the outermost level of typedef. 1282 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1283 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1284 return false; 1285 } 1286 1287 // If we failed to complete the type for some reason, or if the type is 1288 // dependent, don't diagnose the variable. 1289 if (Ty->isIncompleteType() || Ty->isDependentType()) 1290 return false; 1291 1292 if (const TagType *TT = Ty->getAs<TagType>()) { 1293 const TagDecl *Tag = TT->getDecl(); 1294 if (Tag->hasAttr<UnusedAttr>()) 1295 return false; 1296 1297 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1298 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1299 return false; 1300 1301 if (const Expr *Init = VD->getInit()) { 1302 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1303 Init = Cleanups->getSubExpr(); 1304 const CXXConstructExpr *Construct = 1305 dyn_cast<CXXConstructExpr>(Init); 1306 if (Construct && !Construct->isElidable()) { 1307 CXXConstructorDecl *CD = Construct->getConstructor(); 1308 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1309 return false; 1310 } 1311 } 1312 } 1313 } 1314 1315 // TODO: __attribute__((unused)) templates? 1316 } 1317 1318 return true; 1319} 1320 1321static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1322 FixItHint &Hint) { 1323 if (isa<LabelDecl>(D)) { 1324 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1325 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1326 if (AfterColon.isInvalid()) 1327 return; 1328 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1329 getCharRange(D->getLocStart(), AfterColon)); 1330 } 1331 return; 1332} 1333 1334/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1335/// unless they are marked attr(unused). 1336void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1337 FixItHint Hint; 1338 if (!ShouldDiagnoseUnusedDecl(D)) 1339 return; 1340 1341 GenerateFixForUnusedDecl(D, Context, Hint); 1342 1343 unsigned DiagID; 1344 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1345 DiagID = diag::warn_unused_exception_param; 1346 else if (isa<LabelDecl>(D)) 1347 DiagID = diag::warn_unused_label; 1348 else 1349 DiagID = diag::warn_unused_variable; 1350 1351 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1352} 1353 1354static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1355 // Verify that we have no forward references left. If so, there was a goto 1356 // or address of a label taken, but no definition of it. Label fwd 1357 // definitions are indicated with a null substmt. 1358 if (L->getStmt() == 0) 1359 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1360} 1361 1362void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1363 if (S->decl_empty()) return; 1364 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1365 "Scope shouldn't contain decls!"); 1366 1367 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1368 I != E; ++I) { 1369 Decl *TmpD = (*I); 1370 assert(TmpD && "This decl didn't get pushed??"); 1371 1372 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1373 NamedDecl *D = cast<NamedDecl>(TmpD); 1374 1375 if (!D->getDeclName()) continue; 1376 1377 // Diagnose unused variables in this scope. 1378 if (!S->hasUnrecoverableErrorOccurred()) 1379 DiagnoseUnusedDecl(D); 1380 1381 // If this was a forward reference to a label, verify it was defined. 1382 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1383 CheckPoppedLabel(LD, *this); 1384 1385 // Remove this name from our lexical scope. 1386 IdResolver.RemoveDecl(D); 1387 } 1388 DiagnoseUnusedBackingIvarInAccessor(S); 1389} 1390 1391void Sema::ActOnStartFunctionDeclarator() { 1392 ++InFunctionDeclarator; 1393} 1394 1395void Sema::ActOnEndFunctionDeclarator() { 1396 assert(InFunctionDeclarator); 1397 --InFunctionDeclarator; 1398} 1399 1400/// \brief Look for an Objective-C class in the translation unit. 1401/// 1402/// \param Id The name of the Objective-C class we're looking for. If 1403/// typo-correction fixes this name, the Id will be updated 1404/// to the fixed name. 1405/// 1406/// \param IdLoc The location of the name in the translation unit. 1407/// 1408/// \param DoTypoCorrection If true, this routine will attempt typo correction 1409/// if there is no class with the given name. 1410/// 1411/// \returns The declaration of the named Objective-C class, or NULL if the 1412/// class could not be found. 1413ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1414 SourceLocation IdLoc, 1415 bool DoTypoCorrection) { 1416 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1417 // creation from this context. 1418 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1419 1420 if (!IDecl && DoTypoCorrection) { 1421 // Perform typo correction at the given location, but only if we 1422 // find an Objective-C class name. 1423 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1424 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1425 LookupOrdinaryName, TUScope, NULL, 1426 Validator)) { 1427 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1428 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1429 Id = IDecl->getIdentifier(); 1430 } 1431 } 1432 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1433 // This routine must always return a class definition, if any. 1434 if (Def && Def->getDefinition()) 1435 Def = Def->getDefinition(); 1436 return Def; 1437} 1438 1439/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1440/// from S, where a non-field would be declared. This routine copes 1441/// with the difference between C and C++ scoping rules in structs and 1442/// unions. For example, the following code is well-formed in C but 1443/// ill-formed in C++: 1444/// @code 1445/// struct S6 { 1446/// enum { BAR } e; 1447/// }; 1448/// 1449/// void test_S6() { 1450/// struct S6 a; 1451/// a.e = BAR; 1452/// } 1453/// @endcode 1454/// For the declaration of BAR, this routine will return a different 1455/// scope. The scope S will be the scope of the unnamed enumeration 1456/// within S6. In C++, this routine will return the scope associated 1457/// with S6, because the enumeration's scope is a transparent 1458/// context but structures can contain non-field names. In C, this 1459/// routine will return the translation unit scope, since the 1460/// enumeration's scope is a transparent context and structures cannot 1461/// contain non-field names. 1462Scope *Sema::getNonFieldDeclScope(Scope *S) { 1463 while (((S->getFlags() & Scope::DeclScope) == 0) || 1464 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1465 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1466 S = S->getParent(); 1467 return S; 1468} 1469 1470/// \brief Looks up the declaration of "struct objc_super" and 1471/// saves it for later use in building builtin declaration of 1472/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1473/// pre-existing declaration exists no action takes place. 1474static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1475 IdentifierInfo *II) { 1476 if (!II->isStr("objc_msgSendSuper")) 1477 return; 1478 ASTContext &Context = ThisSema.Context; 1479 1480 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1481 SourceLocation(), Sema::LookupTagName); 1482 ThisSema.LookupName(Result, S); 1483 if (Result.getResultKind() == LookupResult::Found) 1484 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1485 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1486} 1487 1488/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1489/// file scope. lazily create a decl for it. ForRedeclaration is true 1490/// if we're creating this built-in in anticipation of redeclaring the 1491/// built-in. 1492NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1493 Scope *S, bool ForRedeclaration, 1494 SourceLocation Loc) { 1495 LookupPredefedObjCSuperType(*this, S, II); 1496 1497 Builtin::ID BID = (Builtin::ID)bid; 1498 1499 ASTContext::GetBuiltinTypeError Error; 1500 QualType R = Context.GetBuiltinType(BID, Error); 1501 switch (Error) { 1502 case ASTContext::GE_None: 1503 // Okay 1504 break; 1505 1506 case ASTContext::GE_Missing_stdio: 1507 if (ForRedeclaration) 1508 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1509 << Context.BuiltinInfo.GetName(BID); 1510 return 0; 1511 1512 case ASTContext::GE_Missing_setjmp: 1513 if (ForRedeclaration) 1514 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1515 << Context.BuiltinInfo.GetName(BID); 1516 return 0; 1517 1518 case ASTContext::GE_Missing_ucontext: 1519 if (ForRedeclaration) 1520 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1521 << Context.BuiltinInfo.GetName(BID); 1522 return 0; 1523 } 1524 1525 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1526 Diag(Loc, diag::ext_implicit_lib_function_decl) 1527 << Context.BuiltinInfo.GetName(BID) 1528 << R; 1529 if (Context.BuiltinInfo.getHeaderName(BID) && 1530 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1531 != DiagnosticsEngine::Ignored) 1532 Diag(Loc, diag::note_please_include_header) 1533 << Context.BuiltinInfo.getHeaderName(BID) 1534 << Context.BuiltinInfo.GetName(BID); 1535 } 1536 1537 DeclContext *Parent = Context.getTranslationUnitDecl(); 1538 if (getLangOpts().CPlusPlus) { 1539 LinkageSpecDecl *CLinkageDecl = 1540 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1541 LinkageSpecDecl::lang_c, false); 1542 Parent->addDecl(CLinkageDecl); 1543 Parent = CLinkageDecl; 1544 } 1545 1546 FunctionDecl *New = FunctionDecl::Create(Context, 1547 Parent, 1548 Loc, Loc, II, R, /*TInfo=*/0, 1549 SC_Extern, 1550 false, 1551 /*hasPrototype=*/true); 1552 New->setImplicit(); 1553 1554 // Create Decl objects for each parameter, adding them to the 1555 // FunctionDecl. 1556 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1557 SmallVector<ParmVarDecl*, 16> Params; 1558 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1559 ParmVarDecl *parm = 1560 ParmVarDecl::Create(Context, New, SourceLocation(), 1561 SourceLocation(), 0, 1562 FT->getArgType(i), /*TInfo=*/0, 1563 SC_None, 0); 1564 parm->setScopeInfo(0, i); 1565 Params.push_back(parm); 1566 } 1567 New->setParams(Params); 1568 } 1569 1570 AddKnownFunctionAttributes(New); 1571 RegisterLocallyScopedExternCDecl(New, S); 1572 1573 // TUScope is the translation-unit scope to insert this function into. 1574 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1575 // relate Scopes to DeclContexts, and probably eliminate CurContext 1576 // entirely, but we're not there yet. 1577 DeclContext *SavedContext = CurContext; 1578 CurContext = Parent; 1579 PushOnScopeChains(New, TUScope); 1580 CurContext = SavedContext; 1581 return New; 1582} 1583 1584/// \brief Filter out any previous declarations that the given declaration 1585/// should not consider because they are not permitted to conflict, e.g., 1586/// because they come from hidden sub-modules and do not refer to the same 1587/// entity. 1588static void filterNonConflictingPreviousDecls(ASTContext &context, 1589 NamedDecl *decl, 1590 LookupResult &previous){ 1591 // This is only interesting when modules are enabled. 1592 if (!context.getLangOpts().Modules) 1593 return; 1594 1595 // Empty sets are uninteresting. 1596 if (previous.empty()) 1597 return; 1598 1599 LookupResult::Filter filter = previous.makeFilter(); 1600 while (filter.hasNext()) { 1601 NamedDecl *old = filter.next(); 1602 1603 // Non-hidden declarations are never ignored. 1604 if (!old->isHidden()) 1605 continue; 1606 1607 if (!old->isExternallyVisible()) 1608 filter.erase(); 1609 } 1610 1611 filter.done(); 1612} 1613 1614bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1615 QualType OldType; 1616 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1617 OldType = OldTypedef->getUnderlyingType(); 1618 else 1619 OldType = Context.getTypeDeclType(Old); 1620 QualType NewType = New->getUnderlyingType(); 1621 1622 if (NewType->isVariablyModifiedType()) { 1623 // Must not redefine a typedef with a variably-modified type. 1624 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1625 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1626 << Kind << NewType; 1627 if (Old->getLocation().isValid()) 1628 Diag(Old->getLocation(), diag::note_previous_definition); 1629 New->setInvalidDecl(); 1630 return true; 1631 } 1632 1633 if (OldType != NewType && 1634 !OldType->isDependentType() && 1635 !NewType->isDependentType() && 1636 !Context.hasSameType(OldType, NewType)) { 1637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1638 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1639 << Kind << NewType << OldType; 1640 if (Old->getLocation().isValid()) 1641 Diag(Old->getLocation(), diag::note_previous_definition); 1642 New->setInvalidDecl(); 1643 return true; 1644 } 1645 return false; 1646} 1647 1648/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1649/// same name and scope as a previous declaration 'Old'. Figure out 1650/// how to resolve this situation, merging decls or emitting 1651/// diagnostics as appropriate. If there was an error, set New to be invalid. 1652/// 1653void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1654 // If the new decl is known invalid already, don't bother doing any 1655 // merging checks. 1656 if (New->isInvalidDecl()) return; 1657 1658 // Allow multiple definitions for ObjC built-in typedefs. 1659 // FIXME: Verify the underlying types are equivalent! 1660 if (getLangOpts().ObjC1) { 1661 const IdentifierInfo *TypeID = New->getIdentifier(); 1662 switch (TypeID->getLength()) { 1663 default: break; 1664 case 2: 1665 { 1666 if (!TypeID->isStr("id")) 1667 break; 1668 QualType T = New->getUnderlyingType(); 1669 if (!T->isPointerType()) 1670 break; 1671 if (!T->isVoidPointerType()) { 1672 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1673 if (!PT->isStructureType()) 1674 break; 1675 } 1676 Context.setObjCIdRedefinitionType(T); 1677 // Install the built-in type for 'id', ignoring the current definition. 1678 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1679 return; 1680 } 1681 case 5: 1682 if (!TypeID->isStr("Class")) 1683 break; 1684 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1685 // Install the built-in type for 'Class', ignoring the current definition. 1686 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1687 return; 1688 case 3: 1689 if (!TypeID->isStr("SEL")) 1690 break; 1691 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1692 // Install the built-in type for 'SEL', ignoring the current definition. 1693 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1694 return; 1695 } 1696 // Fall through - the typedef name was not a builtin type. 1697 } 1698 1699 // Verify the old decl was also a type. 1700 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1701 if (!Old) { 1702 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1703 << New->getDeclName(); 1704 1705 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1706 if (OldD->getLocation().isValid()) 1707 Diag(OldD->getLocation(), diag::note_previous_definition); 1708 1709 return New->setInvalidDecl(); 1710 } 1711 1712 // If the old declaration is invalid, just give up here. 1713 if (Old->isInvalidDecl()) 1714 return New->setInvalidDecl(); 1715 1716 // If the typedef types are not identical, reject them in all languages and 1717 // with any extensions enabled. 1718 if (isIncompatibleTypedef(Old, New)) 1719 return; 1720 1721 // The types match. Link up the redeclaration chain and merge attributes if 1722 // the old declaration was a typedef. 1723 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1724 New->setPreviousDecl(Typedef); 1725 mergeDeclAttributes(New, Old); 1726 } 1727 1728 if (getLangOpts().MicrosoftExt) 1729 return; 1730 1731 if (getLangOpts().CPlusPlus) { 1732 // C++ [dcl.typedef]p2: 1733 // In a given non-class scope, a typedef specifier can be used to 1734 // redefine the name of any type declared in that scope to refer 1735 // to the type to which it already refers. 1736 if (!isa<CXXRecordDecl>(CurContext)) 1737 return; 1738 1739 // C++0x [dcl.typedef]p4: 1740 // In a given class scope, a typedef specifier can be used to redefine 1741 // any class-name declared in that scope that is not also a typedef-name 1742 // to refer to the type to which it already refers. 1743 // 1744 // This wording came in via DR424, which was a correction to the 1745 // wording in DR56, which accidentally banned code like: 1746 // 1747 // struct S { 1748 // typedef struct A { } A; 1749 // }; 1750 // 1751 // in the C++03 standard. We implement the C++0x semantics, which 1752 // allow the above but disallow 1753 // 1754 // struct S { 1755 // typedef int I; 1756 // typedef int I; 1757 // }; 1758 // 1759 // since that was the intent of DR56. 1760 if (!isa<TypedefNameDecl>(Old)) 1761 return; 1762 1763 Diag(New->getLocation(), diag::err_redefinition) 1764 << New->getDeclName(); 1765 Diag(Old->getLocation(), diag::note_previous_definition); 1766 return New->setInvalidDecl(); 1767 } 1768 1769 // Modules always permit redefinition of typedefs, as does C11. 1770 if (getLangOpts().Modules || getLangOpts().C11) 1771 return; 1772 1773 // If we have a redefinition of a typedef in C, emit a warning. This warning 1774 // is normally mapped to an error, but can be controlled with 1775 // -Wtypedef-redefinition. If either the original or the redefinition is 1776 // in a system header, don't emit this for compatibility with GCC. 1777 if (getDiagnostics().getSuppressSystemWarnings() && 1778 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1779 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1780 return; 1781 1782 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1783 << New->getDeclName(); 1784 Diag(Old->getLocation(), diag::note_previous_definition); 1785 return; 1786} 1787 1788/// DeclhasAttr - returns true if decl Declaration already has the target 1789/// attribute. 1790static bool 1791DeclHasAttr(const Decl *D, const Attr *A) { 1792 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1793 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1794 // responsible for making sure they are consistent. 1795 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1796 if (AA) 1797 return false; 1798 1799 // The following thread safety attributes can also be duplicated. 1800 switch (A->getKind()) { 1801 case attr::ExclusiveLocksRequired: 1802 case attr::SharedLocksRequired: 1803 case attr::LocksExcluded: 1804 case attr::ExclusiveLockFunction: 1805 case attr::SharedLockFunction: 1806 case attr::UnlockFunction: 1807 case attr::ExclusiveTrylockFunction: 1808 case attr::SharedTrylockFunction: 1809 case attr::GuardedBy: 1810 case attr::PtGuardedBy: 1811 case attr::AcquiredBefore: 1812 case attr::AcquiredAfter: 1813 return false; 1814 default: 1815 ; 1816 } 1817 1818 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1819 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1820 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1821 if ((*i)->getKind() == A->getKind()) { 1822 if (Ann) { 1823 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1824 return true; 1825 continue; 1826 } 1827 // FIXME: Don't hardcode this check 1828 if (OA && isa<OwnershipAttr>(*i)) 1829 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1830 return true; 1831 } 1832 1833 return false; 1834} 1835 1836static bool isAttributeTargetADefinition(Decl *D) { 1837 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1838 return VD->isThisDeclarationADefinition(); 1839 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1840 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1841 return true; 1842} 1843 1844/// Merge alignment attributes from \p Old to \p New, taking into account the 1845/// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1846/// 1847/// \return \c true if any attributes were added to \p New. 1848static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1849 // Look for alignas attributes on Old, and pick out whichever attribute 1850 // specifies the strictest alignment requirement. 1851 AlignedAttr *OldAlignasAttr = 0; 1852 AlignedAttr *OldStrictestAlignAttr = 0; 1853 unsigned OldAlign = 0; 1854 for (specific_attr_iterator<AlignedAttr> 1855 I = Old->specific_attr_begin<AlignedAttr>(), 1856 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1857 // FIXME: We have no way of representing inherited dependent alignments 1858 // in a case like: 1859 // template<int A, int B> struct alignas(A) X; 1860 // template<int A, int B> struct alignas(B) X {}; 1861 // For now, we just ignore any alignas attributes which are not on the 1862 // definition in such a case. 1863 if (I->isAlignmentDependent()) 1864 return false; 1865 1866 if (I->isAlignas()) 1867 OldAlignasAttr = *I; 1868 1869 unsigned Align = I->getAlignment(S.Context); 1870 if (Align > OldAlign) { 1871 OldAlign = Align; 1872 OldStrictestAlignAttr = *I; 1873 } 1874 } 1875 1876 // Look for alignas attributes on New. 1877 AlignedAttr *NewAlignasAttr = 0; 1878 unsigned NewAlign = 0; 1879 for (specific_attr_iterator<AlignedAttr> 1880 I = New->specific_attr_begin<AlignedAttr>(), 1881 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1882 if (I->isAlignmentDependent()) 1883 return false; 1884 1885 if (I->isAlignas()) 1886 NewAlignasAttr = *I; 1887 1888 unsigned Align = I->getAlignment(S.Context); 1889 if (Align > NewAlign) 1890 NewAlign = Align; 1891 } 1892 1893 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1894 // Both declarations have 'alignas' attributes. We require them to match. 1895 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1896 // fall short. (If two declarations both have alignas, they must both match 1897 // every definition, and so must match each other if there is a definition.) 1898 1899 // If either declaration only contains 'alignas(0)' specifiers, then it 1900 // specifies the natural alignment for the type. 1901 if (OldAlign == 0 || NewAlign == 0) { 1902 QualType Ty; 1903 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1904 Ty = VD->getType(); 1905 else 1906 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1907 1908 if (OldAlign == 0) 1909 OldAlign = S.Context.getTypeAlign(Ty); 1910 if (NewAlign == 0) 1911 NewAlign = S.Context.getTypeAlign(Ty); 1912 } 1913 1914 if (OldAlign != NewAlign) { 1915 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1916 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1917 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1918 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1919 } 1920 } 1921 1922 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1923 // C++11 [dcl.align]p6: 1924 // if any declaration of an entity has an alignment-specifier, 1925 // every defining declaration of that entity shall specify an 1926 // equivalent alignment. 1927 // C11 6.7.5/7: 1928 // If the definition of an object does not have an alignment 1929 // specifier, any other declaration of that object shall also 1930 // have no alignment specifier. 1931 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1932 << OldAlignasAttr->isC11(); 1933 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1934 << OldAlignasAttr->isC11(); 1935 } 1936 1937 bool AnyAdded = false; 1938 1939 // Ensure we have an attribute representing the strictest alignment. 1940 if (OldAlign > NewAlign) { 1941 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1942 Clone->setInherited(true); 1943 New->addAttr(Clone); 1944 AnyAdded = true; 1945 } 1946 1947 // Ensure we have an alignas attribute if the old declaration had one. 1948 if (OldAlignasAttr && !NewAlignasAttr && 1949 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1950 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1951 Clone->setInherited(true); 1952 New->addAttr(Clone); 1953 AnyAdded = true; 1954 } 1955 1956 return AnyAdded; 1957} 1958 1959static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1960 bool Override) { 1961 InheritableAttr *NewAttr = NULL; 1962 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1963 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1964 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1965 AA->getIntroduced(), AA->getDeprecated(), 1966 AA->getObsoleted(), AA->getUnavailable(), 1967 AA->getMessage(), Override, 1968 AttrSpellingListIndex); 1969 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1970 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1971 AttrSpellingListIndex); 1972 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1973 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1974 AttrSpellingListIndex); 1975 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1976 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1977 AttrSpellingListIndex); 1978 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1979 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1980 AttrSpellingListIndex); 1981 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1982 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1983 FA->getFormatIdx(), FA->getFirstArg(), 1984 AttrSpellingListIndex); 1985 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1986 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1987 AttrSpellingListIndex); 1988 else if (isa<AlignedAttr>(Attr)) 1989 // AlignedAttrs are handled separately, because we need to handle all 1990 // such attributes on a declaration at the same time. 1991 NewAttr = 0; 1992 else if (!DeclHasAttr(D, Attr)) 1993 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1994 1995 if (NewAttr) { 1996 NewAttr->setInherited(true); 1997 D->addAttr(NewAttr); 1998 return true; 1999 } 2000 2001 return false; 2002} 2003 2004static const Decl *getDefinition(const Decl *D) { 2005 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2006 return TD->getDefinition(); 2007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2008 const VarDecl *Def = VD->getDefinition(); 2009 if (Def) 2010 return Def; 2011 return VD->getActingDefinition(); 2012 } 2013 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2014 const FunctionDecl* Def; 2015 if (FD->isDefined(Def)) 2016 return Def; 2017 } 2018 return NULL; 2019} 2020 2021static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2022 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2023 I != E; ++I) { 2024 Attr *Attribute = *I; 2025 if (Attribute->getKind() == Kind) 2026 return true; 2027 } 2028 return false; 2029} 2030 2031/// checkNewAttributesAfterDef - If we already have a definition, check that 2032/// there are no new attributes in this declaration. 2033static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2034 if (!New->hasAttrs()) 2035 return; 2036 2037 const Decl *Def = getDefinition(Old); 2038 if (!Def || Def == New) 2039 return; 2040 2041 AttrVec &NewAttributes = New->getAttrs(); 2042 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2043 const Attr *NewAttribute = NewAttributes[I]; 2044 2045 if (isa<AliasAttr>(NewAttribute)) { 2046 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2047 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2048 else { 2049 VarDecl *VD = cast<VarDecl>(New); 2050 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2051 VarDecl::TentativeDefinition 2052 ? diag::err_alias_after_tentative 2053 : diag::err_redefinition; 2054 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2055 S.Diag(Def->getLocation(), diag::note_previous_definition); 2056 VD->setInvalidDecl(); 2057 } 2058 ++I; 2059 continue; 2060 } 2061 2062 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2063 // Tentative definitions are only interesting for the alias check above. 2064 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2065 ++I; 2066 continue; 2067 } 2068 } 2069 2070 if (hasAttribute(Def, NewAttribute->getKind())) { 2071 ++I; 2072 continue; // regular attr merging will take care of validating this. 2073 } 2074 2075 if (isa<C11NoReturnAttr>(NewAttribute)) { 2076 // C's _Noreturn is allowed to be added to a function after it is defined. 2077 ++I; 2078 continue; 2079 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2080 if (AA->isAlignas()) { 2081 // C++11 [dcl.align]p6: 2082 // if any declaration of an entity has an alignment-specifier, 2083 // every defining declaration of that entity shall specify an 2084 // equivalent alignment. 2085 // C11 6.7.5/7: 2086 // If the definition of an object does not have an alignment 2087 // specifier, any other declaration of that object shall also 2088 // have no alignment specifier. 2089 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2090 << AA->isC11(); 2091 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2092 << AA->isC11(); 2093 NewAttributes.erase(NewAttributes.begin() + I); 2094 --E; 2095 continue; 2096 } 2097 } 2098 2099 S.Diag(NewAttribute->getLocation(), 2100 diag::warn_attribute_precede_definition); 2101 S.Diag(Def->getLocation(), diag::note_previous_definition); 2102 NewAttributes.erase(NewAttributes.begin() + I); 2103 --E; 2104 } 2105} 2106 2107/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2108void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2109 AvailabilityMergeKind AMK) { 2110 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2111 UsedAttr *NewAttr = OldAttr->clone(Context); 2112 NewAttr->setInherited(true); 2113 New->addAttr(NewAttr); 2114 } 2115 2116 if (!Old->hasAttrs() && !New->hasAttrs()) 2117 return; 2118 2119 // attributes declared post-definition are currently ignored 2120 checkNewAttributesAfterDef(*this, New, Old); 2121 2122 if (!Old->hasAttrs()) 2123 return; 2124 2125 bool foundAny = New->hasAttrs(); 2126 2127 // Ensure that any moving of objects within the allocated map is done before 2128 // we process them. 2129 if (!foundAny) New->setAttrs(AttrVec()); 2130 2131 for (specific_attr_iterator<InheritableAttr> 2132 i = Old->specific_attr_begin<InheritableAttr>(), 2133 e = Old->specific_attr_end<InheritableAttr>(); 2134 i != e; ++i) { 2135 bool Override = false; 2136 // Ignore deprecated/unavailable/availability attributes if requested. 2137 if (isa<DeprecatedAttr>(*i) || 2138 isa<UnavailableAttr>(*i) || 2139 isa<AvailabilityAttr>(*i)) { 2140 switch (AMK) { 2141 case AMK_None: 2142 continue; 2143 2144 case AMK_Redeclaration: 2145 break; 2146 2147 case AMK_Override: 2148 Override = true; 2149 break; 2150 } 2151 } 2152 2153 // Already handled. 2154 if (isa<UsedAttr>(*i)) 2155 continue; 2156 2157 if (mergeDeclAttribute(*this, New, *i, Override)) 2158 foundAny = true; 2159 } 2160 2161 if (mergeAlignedAttrs(*this, New, Old)) 2162 foundAny = true; 2163 2164 if (!foundAny) New->dropAttrs(); 2165} 2166 2167/// mergeParamDeclAttributes - Copy attributes from the old parameter 2168/// to the new one. 2169static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2170 const ParmVarDecl *oldDecl, 2171 Sema &S) { 2172 // C++11 [dcl.attr.depend]p2: 2173 // The first declaration of a function shall specify the 2174 // carries_dependency attribute for its declarator-id if any declaration 2175 // of the function specifies the carries_dependency attribute. 2176 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2177 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2178 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2179 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2180 // Find the first declaration of the parameter. 2181 // FIXME: Should we build redeclaration chains for function parameters? 2182 const FunctionDecl *FirstFD = 2183 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2184 const ParmVarDecl *FirstVD = 2185 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2186 S.Diag(FirstVD->getLocation(), 2187 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2188 } 2189 2190 if (!oldDecl->hasAttrs()) 2191 return; 2192 2193 bool foundAny = newDecl->hasAttrs(); 2194 2195 // Ensure that any moving of objects within the allocated map is 2196 // done before we process them. 2197 if (!foundAny) newDecl->setAttrs(AttrVec()); 2198 2199 for (specific_attr_iterator<InheritableParamAttr> 2200 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2201 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2202 if (!DeclHasAttr(newDecl, *i)) { 2203 InheritableAttr *newAttr = 2204 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2205 newAttr->setInherited(true); 2206 newDecl->addAttr(newAttr); 2207 foundAny = true; 2208 } 2209 } 2210 2211 if (!foundAny) newDecl->dropAttrs(); 2212} 2213 2214namespace { 2215 2216/// Used in MergeFunctionDecl to keep track of function parameters in 2217/// C. 2218struct GNUCompatibleParamWarning { 2219 ParmVarDecl *OldParm; 2220 ParmVarDecl *NewParm; 2221 QualType PromotedType; 2222}; 2223 2224} 2225 2226/// getSpecialMember - get the special member enum for a method. 2227Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2228 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2229 if (Ctor->isDefaultConstructor()) 2230 return Sema::CXXDefaultConstructor; 2231 2232 if (Ctor->isCopyConstructor()) 2233 return Sema::CXXCopyConstructor; 2234 2235 if (Ctor->isMoveConstructor()) 2236 return Sema::CXXMoveConstructor; 2237 } else if (isa<CXXDestructorDecl>(MD)) { 2238 return Sema::CXXDestructor; 2239 } else if (MD->isCopyAssignmentOperator()) { 2240 return Sema::CXXCopyAssignment; 2241 } else if (MD->isMoveAssignmentOperator()) { 2242 return Sema::CXXMoveAssignment; 2243 } 2244 2245 return Sema::CXXInvalid; 2246} 2247 2248/// canRedefineFunction - checks if a function can be redefined. Currently, 2249/// only extern inline functions can be redefined, and even then only in 2250/// GNU89 mode. 2251static bool canRedefineFunction(const FunctionDecl *FD, 2252 const LangOptions& LangOpts) { 2253 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2254 !LangOpts.CPlusPlus && 2255 FD->isInlineSpecified() && 2256 FD->getStorageClass() == SC_Extern); 2257} 2258 2259const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2260 const AttributedType *AT = T->getAs<AttributedType>(); 2261 while (AT && !AT->isCallingConv()) 2262 AT = AT->getModifiedType()->getAs<AttributedType>(); 2263 return AT; 2264} 2265 2266template <typename T> 2267static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2268 const DeclContext *DC = Old->getDeclContext(); 2269 if (DC->isRecord()) 2270 return false; 2271 2272 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2273 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2274 return true; 2275 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2276 return true; 2277 return false; 2278} 2279 2280/// MergeFunctionDecl - We just parsed a function 'New' from 2281/// declarator D which has the same name and scope as a previous 2282/// declaration 'Old'. Figure out how to resolve this situation, 2283/// merging decls or emitting diagnostics as appropriate. 2284/// 2285/// In C++, New and Old must be declarations that are not 2286/// overloaded. Use IsOverload to determine whether New and Old are 2287/// overloaded, and to select the Old declaration that New should be 2288/// merged with. 2289/// 2290/// Returns true if there was an error, false otherwise. 2291bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S, 2292 bool MergeTypeWithOld) { 2293 // Verify the old decl was also a function. 2294 FunctionDecl *Old = 0; 2295 if (FunctionTemplateDecl *OldFunctionTemplate 2296 = dyn_cast<FunctionTemplateDecl>(OldD)) 2297 Old = OldFunctionTemplate->getTemplatedDecl(); 2298 else 2299 Old = dyn_cast<FunctionDecl>(OldD); 2300 if (!Old) { 2301 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2302 if (New->getFriendObjectKind()) { 2303 Diag(New->getLocation(), diag::err_using_decl_friend); 2304 Diag(Shadow->getTargetDecl()->getLocation(), 2305 diag::note_using_decl_target); 2306 Diag(Shadow->getUsingDecl()->getLocation(), 2307 diag::note_using_decl) << 0; 2308 return true; 2309 } 2310 2311 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2312 Diag(Shadow->getTargetDecl()->getLocation(), 2313 diag::note_using_decl_target); 2314 Diag(Shadow->getUsingDecl()->getLocation(), 2315 diag::note_using_decl) << 0; 2316 return true; 2317 } 2318 2319 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2320 << New->getDeclName(); 2321 Diag(OldD->getLocation(), diag::note_previous_definition); 2322 return true; 2323 } 2324 2325 // If the old declaration is invalid, just give up here. 2326 if (Old->isInvalidDecl()) 2327 return true; 2328 2329 // Determine whether the previous declaration was a definition, 2330 // implicit declaration, or a declaration. 2331 diag::kind PrevDiag; 2332 if (Old->isThisDeclarationADefinition()) 2333 PrevDiag = diag::note_previous_definition; 2334 else if (Old->isImplicit()) 2335 PrevDiag = diag::note_previous_implicit_declaration; 2336 else 2337 PrevDiag = diag::note_previous_declaration; 2338 2339 // Don't complain about this if we're in GNU89 mode and the old function 2340 // is an extern inline function. 2341 // Don't complain about specializations. They are not supposed to have 2342 // storage classes. 2343 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2344 New->getStorageClass() == SC_Static && 2345 Old->hasExternalFormalLinkage() && 2346 !New->getTemplateSpecializationInfo() && 2347 !canRedefineFunction(Old, getLangOpts())) { 2348 if (getLangOpts().MicrosoftExt) { 2349 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2350 Diag(Old->getLocation(), PrevDiag); 2351 } else { 2352 Diag(New->getLocation(), diag::err_static_non_static) << New; 2353 Diag(Old->getLocation(), PrevDiag); 2354 return true; 2355 } 2356 } 2357 2358 2359 // If a function is first declared with a calling convention, but is later 2360 // declared or defined without one, all following decls assume the calling 2361 // convention of the first. 2362 // 2363 // It's OK if a function is first declared without a calling convention, 2364 // but is later declared or defined with the default calling convention. 2365 // 2366 // To test if either decl has an explicit calling convention, we look for 2367 // AttributedType sugar nodes on the type as written. If they are missing or 2368 // were canonicalized away, we assume the calling convention was implicit. 2369 // 2370 // Note also that we DO NOT return at this point, because we still have 2371 // other tests to run. 2372 QualType OldQType = Context.getCanonicalType(Old->getType()); 2373 QualType NewQType = Context.getCanonicalType(New->getType()); 2374 const FunctionType *OldType = cast<FunctionType>(OldQType); 2375 const FunctionType *NewType = cast<FunctionType>(NewQType); 2376 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2377 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2378 bool RequiresAdjustment = false; 2379 2380 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2381 FunctionDecl *First = Old->getFirstDecl(); 2382 const FunctionType *FT = 2383 First->getType().getCanonicalType()->castAs<FunctionType>(); 2384 FunctionType::ExtInfo FI = FT->getExtInfo(); 2385 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2386 if (!NewCCExplicit) { 2387 // Inherit the CC from the previous declaration if it was specified 2388 // there but not here. 2389 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2390 RequiresAdjustment = true; 2391 } else { 2392 // Calling conventions aren't compatible, so complain. 2393 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2394 Diag(New->getLocation(), diag::err_cconv_change) 2395 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2396 << !FirstCCExplicit 2397 << (!FirstCCExplicit ? "" : 2398 FunctionType::getNameForCallConv(FI.getCC())); 2399 2400 // Put the note on the first decl, since it is the one that matters. 2401 Diag(First->getLocation(), diag::note_previous_declaration); 2402 return true; 2403 } 2404 } 2405 2406 // FIXME: diagnose the other way around? 2407 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2408 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2409 RequiresAdjustment = true; 2410 } 2411 2412 // Merge regparm attribute. 2413 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2414 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2415 if (NewTypeInfo.getHasRegParm()) { 2416 Diag(New->getLocation(), diag::err_regparm_mismatch) 2417 << NewType->getRegParmType() 2418 << OldType->getRegParmType(); 2419 Diag(Old->getLocation(), diag::note_previous_declaration); 2420 return true; 2421 } 2422 2423 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2424 RequiresAdjustment = true; 2425 } 2426 2427 // Merge ns_returns_retained attribute. 2428 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2429 if (NewTypeInfo.getProducesResult()) { 2430 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2431 Diag(Old->getLocation(), diag::note_previous_declaration); 2432 return true; 2433 } 2434 2435 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2436 RequiresAdjustment = true; 2437 } 2438 2439 if (RequiresAdjustment) { 2440 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2441 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2442 New->setType(QualType(AdjustedType, 0)); 2443 NewQType = Context.getCanonicalType(New->getType()); 2444 NewType = cast<FunctionType>(NewQType); 2445 } 2446 2447 // If this redeclaration makes the function inline, we may need to add it to 2448 // UndefinedButUsed. 2449 if (!Old->isInlined() && New->isInlined() && 2450 !New->hasAttr<GNUInlineAttr>() && 2451 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2452 Old->isUsed(false) && 2453 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2454 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2455 SourceLocation())); 2456 2457 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2458 // about it. 2459 if (New->hasAttr<GNUInlineAttr>() && 2460 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2461 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2462 } 2463 2464 if (getLangOpts().CPlusPlus) { 2465 // (C++98 13.1p2): 2466 // Certain function declarations cannot be overloaded: 2467 // -- Function declarations that differ only in the return type 2468 // cannot be overloaded. 2469 2470 // Go back to the type source info to compare the declared return types, 2471 // per C++1y [dcl.type.auto]p13: 2472 // Redeclarations or specializations of a function or function template 2473 // with a declared return type that uses a placeholder type shall also 2474 // use that placeholder, not a deduced type. 2475 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo() 2476 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2477 : OldType)->getResultType(); 2478 QualType NewDeclaredReturnType = (New->getTypeSourceInfo() 2479 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2480 : NewType)->getResultType(); 2481 QualType ResQT; 2482 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2483 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2484 New->isLocalExternDecl())) { 2485 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2486 OldDeclaredReturnType->isObjCObjectPointerType()) 2487 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2488 if (ResQT.isNull()) { 2489 if (New->isCXXClassMember() && New->isOutOfLine()) 2490 Diag(New->getLocation(), 2491 diag::err_member_def_does_not_match_ret_type) << New; 2492 else 2493 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2494 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2495 return true; 2496 } 2497 else 2498 NewQType = ResQT; 2499 } 2500 2501 QualType OldReturnType = OldType->getResultType(); 2502 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2503 if (OldReturnType != NewReturnType) { 2504 // If this function has a deduced return type and has already been 2505 // defined, copy the deduced value from the old declaration. 2506 AutoType *OldAT = Old->getResultType()->getContainedAutoType(); 2507 if (OldAT && OldAT->isDeduced()) { 2508 New->setType( 2509 SubstAutoType(New->getType(), 2510 OldAT->isDependentType() ? Context.DependentTy 2511 : OldAT->getDeducedType())); 2512 NewQType = Context.getCanonicalType( 2513 SubstAutoType(NewQType, 2514 OldAT->isDependentType() ? Context.DependentTy 2515 : OldAT->getDeducedType())); 2516 } 2517 } 2518 2519 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2520 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2521 if (OldMethod && NewMethod) { 2522 // Preserve triviality. 2523 NewMethod->setTrivial(OldMethod->isTrivial()); 2524 2525 // MSVC allows explicit template specialization at class scope: 2526 // 2 CXMethodDecls referring to the same function will be injected. 2527 // We don't want a redeclartion error. 2528 bool IsClassScopeExplicitSpecialization = 2529 OldMethod->isFunctionTemplateSpecialization() && 2530 NewMethod->isFunctionTemplateSpecialization(); 2531 bool isFriend = NewMethod->getFriendObjectKind(); 2532 2533 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2534 !IsClassScopeExplicitSpecialization) { 2535 // -- Member function declarations with the same name and the 2536 // same parameter types cannot be overloaded if any of them 2537 // is a static member function declaration. 2538 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2539 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2540 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2541 return true; 2542 } 2543 2544 // C++ [class.mem]p1: 2545 // [...] A member shall not be declared twice in the 2546 // member-specification, except that a nested class or member 2547 // class template can be declared and then later defined. 2548 if (ActiveTemplateInstantiations.empty()) { 2549 unsigned NewDiag; 2550 if (isa<CXXConstructorDecl>(OldMethod)) 2551 NewDiag = diag::err_constructor_redeclared; 2552 else if (isa<CXXDestructorDecl>(NewMethod)) 2553 NewDiag = diag::err_destructor_redeclared; 2554 else if (isa<CXXConversionDecl>(NewMethod)) 2555 NewDiag = diag::err_conv_function_redeclared; 2556 else 2557 NewDiag = diag::err_member_redeclared; 2558 2559 Diag(New->getLocation(), NewDiag); 2560 } else { 2561 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2562 << New << New->getType(); 2563 } 2564 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2565 2566 // Complain if this is an explicit declaration of a special 2567 // member that was initially declared implicitly. 2568 // 2569 // As an exception, it's okay to befriend such methods in order 2570 // to permit the implicit constructor/destructor/operator calls. 2571 } else if (OldMethod->isImplicit()) { 2572 if (isFriend) { 2573 NewMethod->setImplicit(); 2574 } else { 2575 Diag(NewMethod->getLocation(), 2576 diag::err_definition_of_implicitly_declared_member) 2577 << New << getSpecialMember(OldMethod); 2578 return true; 2579 } 2580 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2581 Diag(NewMethod->getLocation(), 2582 diag::err_definition_of_explicitly_defaulted_member) 2583 << getSpecialMember(OldMethod); 2584 return true; 2585 } 2586 } 2587 2588 // C++11 [dcl.attr.noreturn]p1: 2589 // The first declaration of a function shall specify the noreturn 2590 // attribute if any declaration of that function specifies the noreturn 2591 // attribute. 2592 if (New->hasAttr<CXX11NoReturnAttr>() && 2593 !Old->hasAttr<CXX11NoReturnAttr>()) { 2594 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2595 diag::err_noreturn_missing_on_first_decl); 2596 Diag(Old->getFirstDecl()->getLocation(), 2597 diag::note_noreturn_missing_first_decl); 2598 } 2599 2600 // C++11 [dcl.attr.depend]p2: 2601 // The first declaration of a function shall specify the 2602 // carries_dependency attribute for its declarator-id if any declaration 2603 // of the function specifies the carries_dependency attribute. 2604 if (New->hasAttr<CarriesDependencyAttr>() && 2605 !Old->hasAttr<CarriesDependencyAttr>()) { 2606 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2607 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2608 Diag(Old->getFirstDecl()->getLocation(), 2609 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2610 } 2611 2612 // (C++98 8.3.5p3): 2613 // All declarations for a function shall agree exactly in both the 2614 // return type and the parameter-type-list. 2615 // We also want to respect all the extended bits except noreturn. 2616 2617 // noreturn should now match unless the old type info didn't have it. 2618 QualType OldQTypeForComparison = OldQType; 2619 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2620 assert(OldQType == QualType(OldType, 0)); 2621 const FunctionType *OldTypeForComparison 2622 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2623 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2624 assert(OldQTypeForComparison.isCanonical()); 2625 } 2626 2627 if (haveIncompatibleLanguageLinkages(Old, New)) { 2628 // As a special case, retain the language linkage from previous 2629 // declarations of a friend function as an extension. 2630 // 2631 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2632 // and is useful because there's otherwise no way to specify language 2633 // linkage within class scope. 2634 // 2635 // Check cautiously as the friend object kind isn't yet complete. 2636 if (New->getFriendObjectKind() != Decl::FOK_None) { 2637 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2638 Diag(Old->getLocation(), PrevDiag); 2639 } else { 2640 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2641 Diag(Old->getLocation(), PrevDiag); 2642 return true; 2643 } 2644 } 2645 2646 if (OldQTypeForComparison == NewQType) 2647 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2648 2649 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2650 New->isLocalExternDecl()) { 2651 // It's OK if we couldn't merge types for a local function declaraton 2652 // if either the old or new type is dependent. We'll merge the types 2653 // when we instantiate the function. 2654 return false; 2655 } 2656 2657 // Fall through for conflicting redeclarations and redefinitions. 2658 } 2659 2660 // C: Function types need to be compatible, not identical. This handles 2661 // duplicate function decls like "void f(int); void f(enum X);" properly. 2662 if (!getLangOpts().CPlusPlus && 2663 Context.typesAreCompatible(OldQType, NewQType)) { 2664 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2665 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2666 const FunctionProtoType *OldProto = 0; 2667 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2668 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2669 // The old declaration provided a function prototype, but the 2670 // new declaration does not. Merge in the prototype. 2671 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2672 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2673 OldProto->arg_type_end()); 2674 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2675 ParamTypes, 2676 OldProto->getExtProtoInfo()); 2677 New->setType(NewQType); 2678 New->setHasInheritedPrototype(); 2679 2680 // Synthesize a parameter for each argument type. 2681 SmallVector<ParmVarDecl*, 16> Params; 2682 for (FunctionProtoType::arg_type_iterator 2683 ParamType = OldProto->arg_type_begin(), 2684 ParamEnd = OldProto->arg_type_end(); 2685 ParamType != ParamEnd; ++ParamType) { 2686 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2687 SourceLocation(), 2688 SourceLocation(), 0, 2689 *ParamType, /*TInfo=*/0, 2690 SC_None, 2691 0); 2692 Param->setScopeInfo(0, Params.size()); 2693 Param->setImplicit(); 2694 Params.push_back(Param); 2695 } 2696 2697 New->setParams(Params); 2698 } 2699 2700 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2701 } 2702 2703 // GNU C permits a K&R definition to follow a prototype declaration 2704 // if the declared types of the parameters in the K&R definition 2705 // match the types in the prototype declaration, even when the 2706 // promoted types of the parameters from the K&R definition differ 2707 // from the types in the prototype. GCC then keeps the types from 2708 // the prototype. 2709 // 2710 // If a variadic prototype is followed by a non-variadic K&R definition, 2711 // the K&R definition becomes variadic. This is sort of an edge case, but 2712 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2713 // C99 6.9.1p8. 2714 if (!getLangOpts().CPlusPlus && 2715 Old->hasPrototype() && !New->hasPrototype() && 2716 New->getType()->getAs<FunctionProtoType>() && 2717 Old->getNumParams() == New->getNumParams()) { 2718 SmallVector<QualType, 16> ArgTypes; 2719 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2720 const FunctionProtoType *OldProto 2721 = Old->getType()->getAs<FunctionProtoType>(); 2722 const FunctionProtoType *NewProto 2723 = New->getType()->getAs<FunctionProtoType>(); 2724 2725 // Determine whether this is the GNU C extension. 2726 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2727 NewProto->getResultType()); 2728 bool LooseCompatible = !MergedReturn.isNull(); 2729 for (unsigned Idx = 0, End = Old->getNumParams(); 2730 LooseCompatible && Idx != End; ++Idx) { 2731 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2732 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2733 if (Context.typesAreCompatible(OldParm->getType(), 2734 NewProto->getArgType(Idx))) { 2735 ArgTypes.push_back(NewParm->getType()); 2736 } else if (Context.typesAreCompatible(OldParm->getType(), 2737 NewParm->getType(), 2738 /*CompareUnqualified=*/true)) { 2739 GNUCompatibleParamWarning Warn 2740 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2741 Warnings.push_back(Warn); 2742 ArgTypes.push_back(NewParm->getType()); 2743 } else 2744 LooseCompatible = false; 2745 } 2746 2747 if (LooseCompatible) { 2748 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2749 Diag(Warnings[Warn].NewParm->getLocation(), 2750 diag::ext_param_promoted_not_compatible_with_prototype) 2751 << Warnings[Warn].PromotedType 2752 << Warnings[Warn].OldParm->getType(); 2753 if (Warnings[Warn].OldParm->getLocation().isValid()) 2754 Diag(Warnings[Warn].OldParm->getLocation(), 2755 diag::note_previous_declaration); 2756 } 2757 2758 if (MergeTypeWithOld) 2759 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2760 OldProto->getExtProtoInfo())); 2761 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2762 } 2763 2764 // Fall through to diagnose conflicting types. 2765 } 2766 2767 // A function that has already been declared has been redeclared or 2768 // defined with a different type; show an appropriate diagnostic. 2769 2770 // If the previous declaration was an implicitly-generated builtin 2771 // declaration, then at the very least we should use a specialized note. 2772 unsigned BuiltinID; 2773 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2774 // If it's actually a library-defined builtin function like 'malloc' 2775 // or 'printf', just warn about the incompatible redeclaration. 2776 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2777 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2778 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2779 << Old << Old->getType(); 2780 2781 // If this is a global redeclaration, just forget hereafter 2782 // about the "builtin-ness" of the function. 2783 // 2784 // Doing this for local extern declarations is problematic. If 2785 // the builtin declaration remains visible, a second invalid 2786 // local declaration will produce a hard error; if it doesn't 2787 // remain visible, a single bogus local redeclaration (which is 2788 // actually only a warning) could break all the downstream code. 2789 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2790 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2791 2792 return false; 2793 } 2794 2795 PrevDiag = diag::note_previous_builtin_declaration; 2796 } 2797 2798 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2799 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2800 return true; 2801} 2802 2803/// \brief Completes the merge of two function declarations that are 2804/// known to be compatible. 2805/// 2806/// This routine handles the merging of attributes and other 2807/// properties of function declarations from the old declaration to 2808/// the new declaration, once we know that New is in fact a 2809/// redeclaration of Old. 2810/// 2811/// \returns false 2812bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2813 Scope *S, bool MergeTypeWithOld) { 2814 // Merge the attributes 2815 mergeDeclAttributes(New, Old); 2816 2817 // Merge "pure" flag. 2818 if (Old->isPure()) 2819 New->setPure(); 2820 2821 // Merge "used" flag. 2822 if (Old->getMostRecentDecl()->isUsed(false)) 2823 New->setIsUsed(); 2824 2825 // Merge attributes from the parameters. These can mismatch with K&R 2826 // declarations. 2827 if (New->getNumParams() == Old->getNumParams()) 2828 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2829 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2830 *this); 2831 2832 if (getLangOpts().CPlusPlus) 2833 return MergeCXXFunctionDecl(New, Old, S); 2834 2835 // Merge the function types so the we get the composite types for the return 2836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2837 // was visible. 2838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2839 if (!Merged.isNull() && MergeTypeWithOld) 2840 New->setType(Merged); 2841 2842 return false; 2843} 2844 2845 2846void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2847 ObjCMethodDecl *oldMethod) { 2848 2849 // Merge the attributes, including deprecated/unavailable 2850 AvailabilityMergeKind MergeKind = 2851 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2852 : AMK_Override; 2853 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2854 2855 // Merge attributes from the parameters. 2856 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2857 oe = oldMethod->param_end(); 2858 for (ObjCMethodDecl::param_iterator 2859 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2860 ni != ne && oi != oe; ++ni, ++oi) 2861 mergeParamDeclAttributes(*ni, *oi, *this); 2862 2863 CheckObjCMethodOverride(newMethod, oldMethod); 2864} 2865 2866/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2867/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2868/// emitting diagnostics as appropriate. 2869/// 2870/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2871/// to here in AddInitializerToDecl. We can't check them before the initializer 2872/// is attached. 2873void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2874 bool MergeTypeWithOld) { 2875 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2876 return; 2877 2878 QualType MergedT; 2879 if (getLangOpts().CPlusPlus) { 2880 if (New->getType()->isUndeducedType()) { 2881 // We don't know what the new type is until the initializer is attached. 2882 return; 2883 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2884 // These could still be something that needs exception specs checked. 2885 return MergeVarDeclExceptionSpecs(New, Old); 2886 } 2887 // C++ [basic.link]p10: 2888 // [...] the types specified by all declarations referring to a given 2889 // object or function shall be identical, except that declarations for an 2890 // array object can specify array types that differ by the presence or 2891 // absence of a major array bound (8.3.4). 2892 else if (Old->getType()->isIncompleteArrayType() && 2893 New->getType()->isArrayType()) { 2894 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2895 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2896 if (Context.hasSameType(OldArray->getElementType(), 2897 NewArray->getElementType())) 2898 MergedT = New->getType(); 2899 } else if (Old->getType()->isArrayType() && 2900 New->getType()->isIncompleteArrayType()) { 2901 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2902 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2903 if (Context.hasSameType(OldArray->getElementType(), 2904 NewArray->getElementType())) 2905 MergedT = Old->getType(); 2906 } else if (New->getType()->isObjCObjectPointerType() && 2907 Old->getType()->isObjCObjectPointerType()) { 2908 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2909 Old->getType()); 2910 } 2911 } else { 2912 // C 6.2.7p2: 2913 // All declarations that refer to the same object or function shall have 2914 // compatible type. 2915 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2916 } 2917 if (MergedT.isNull()) { 2918 // It's OK if we couldn't merge types if either type is dependent, for a 2919 // block-scope variable. In other cases (static data members of class 2920 // templates, variable templates, ...), we require the types to be 2921 // equivalent. 2922 // FIXME: The C++ standard doesn't say anything about this. 2923 if ((New->getType()->isDependentType() || 2924 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2925 // If the old type was dependent, we can't merge with it, so the new type 2926 // becomes dependent for now. We'll reproduce the original type when we 2927 // instantiate the TypeSourceInfo for the variable. 2928 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2929 New->setType(Context.DependentTy); 2930 return; 2931 } 2932 2933 // FIXME: Even if this merging succeeds, some other non-visible declaration 2934 // of this variable might have an incompatible type. For instance: 2935 // 2936 // extern int arr[]; 2937 // void f() { extern int arr[2]; } 2938 // void g() { extern int arr[3]; } 2939 // 2940 // Neither C nor C++ requires a diagnostic for this, but we should still try 2941 // to diagnose it. 2942 Diag(New->getLocation(), diag::err_redefinition_different_type) 2943 << New->getDeclName() << New->getType() << Old->getType(); 2944 Diag(Old->getLocation(), diag::note_previous_definition); 2945 return New->setInvalidDecl(); 2946 } 2947 2948 // Don't actually update the type on the new declaration if the old 2949 // declaration was an extern declaration in a different scope. 2950 if (MergeTypeWithOld) 2951 New->setType(MergedT); 2952} 2953 2954static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2955 LookupResult &Previous) { 2956 // C11 6.2.7p4: 2957 // For an identifier with internal or external linkage declared 2958 // in a scope in which a prior declaration of that identifier is 2959 // visible, if the prior declaration specifies internal or 2960 // external linkage, the type of the identifier at the later 2961 // declaration becomes the composite type. 2962 // 2963 // If the variable isn't visible, we do not merge with its type. 2964 if (Previous.isShadowed()) 2965 return false; 2966 2967 if (S.getLangOpts().CPlusPlus) { 2968 // C++11 [dcl.array]p3: 2969 // If there is a preceding declaration of the entity in the same 2970 // scope in which the bound was specified, an omitted array bound 2971 // is taken to be the same as in that earlier declaration. 2972 return NewVD->isPreviousDeclInSameBlockScope() || 2973 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2974 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2975 } else { 2976 // If the old declaration was function-local, don't merge with its 2977 // type unless we're in the same function. 2978 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2979 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2980 } 2981} 2982 2983/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2984/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2985/// situation, merging decls or emitting diagnostics as appropriate. 2986/// 2987/// Tentative definition rules (C99 6.9.2p2) are checked by 2988/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2989/// definitions here, since the initializer hasn't been attached. 2990/// 2991void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2992 // If the new decl is already invalid, don't do any other checking. 2993 if (New->isInvalidDecl()) 2994 return; 2995 2996 // Verify the old decl was also a variable or variable template. 2997 VarDecl *Old = 0; 2998 if (Previous.isSingleResult() && 2999 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 3000 if (New->getDescribedVarTemplate()) 3001 Old = Old->getDescribedVarTemplate() ? Old : 0; 3002 else 3003 Old = Old->getDescribedVarTemplate() ? 0 : Old; 3004 } 3005 if (!Old) { 3006 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3007 << New->getDeclName(); 3008 Diag(Previous.getRepresentativeDecl()->getLocation(), 3009 diag::note_previous_definition); 3010 return New->setInvalidDecl(); 3011 } 3012 3013 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3014 return; 3015 3016 // C++ [class.mem]p1: 3017 // A member shall not be declared twice in the member-specification [...] 3018 // 3019 // Here, we need only consider static data members. 3020 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3021 Diag(New->getLocation(), diag::err_duplicate_member) 3022 << New->getIdentifier(); 3023 Diag(Old->getLocation(), diag::note_previous_declaration); 3024 New->setInvalidDecl(); 3025 } 3026 3027 mergeDeclAttributes(New, Old); 3028 // Warn if an already-declared variable is made a weak_import in a subsequent 3029 // declaration 3030 if (New->getAttr<WeakImportAttr>() && 3031 Old->getStorageClass() == SC_None && 3032 !Old->getAttr<WeakImportAttr>()) { 3033 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3034 Diag(Old->getLocation(), diag::note_previous_definition); 3035 // Remove weak_import attribute on new declaration. 3036 New->dropAttr<WeakImportAttr>(); 3037 } 3038 3039 // Merge the types. 3040 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3041 3042 if (New->isInvalidDecl()) 3043 return; 3044 3045 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3046 if (New->getStorageClass() == SC_Static && 3047 !New->isStaticDataMember() && 3048 Old->hasExternalFormalLinkage()) { 3049 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3050 Diag(Old->getLocation(), diag::note_previous_definition); 3051 return New->setInvalidDecl(); 3052 } 3053 // C99 6.2.2p4: 3054 // For an identifier declared with the storage-class specifier 3055 // extern in a scope in which a prior declaration of that 3056 // identifier is visible,23) if the prior declaration specifies 3057 // internal or external linkage, the linkage of the identifier at 3058 // the later declaration is the same as the linkage specified at 3059 // the prior declaration. If no prior declaration is visible, or 3060 // if the prior declaration specifies no linkage, then the 3061 // identifier has external linkage. 3062 if (New->hasExternalStorage() && Old->hasLinkage()) 3063 /* Okay */; 3064 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3065 !New->isStaticDataMember() && 3066 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3067 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3068 Diag(Old->getLocation(), diag::note_previous_definition); 3069 return New->setInvalidDecl(); 3070 } 3071 3072 // Check if extern is followed by non-extern and vice-versa. 3073 if (New->hasExternalStorage() && 3074 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3075 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3076 Diag(Old->getLocation(), diag::note_previous_definition); 3077 return New->setInvalidDecl(); 3078 } 3079 if (Old->hasLinkage() && New->isLocalVarDecl() && 3080 !New->hasExternalStorage()) { 3081 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3082 Diag(Old->getLocation(), diag::note_previous_definition); 3083 return New->setInvalidDecl(); 3084 } 3085 3086 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3087 3088 // FIXME: The test for external storage here seems wrong? We still 3089 // need to check for mismatches. 3090 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3091 // Don't complain about out-of-line definitions of static members. 3092 !(Old->getLexicalDeclContext()->isRecord() && 3093 !New->getLexicalDeclContext()->isRecord())) { 3094 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3095 Diag(Old->getLocation(), diag::note_previous_definition); 3096 return New->setInvalidDecl(); 3097 } 3098 3099 if (New->getTLSKind() != Old->getTLSKind()) { 3100 if (!Old->getTLSKind()) { 3101 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3102 Diag(Old->getLocation(), diag::note_previous_declaration); 3103 } else if (!New->getTLSKind()) { 3104 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3105 Diag(Old->getLocation(), diag::note_previous_declaration); 3106 } else { 3107 // Do not allow redeclaration to change the variable between requiring 3108 // static and dynamic initialization. 3109 // FIXME: GCC allows this, but uses the TLS keyword on the first 3110 // declaration to determine the kind. Do we need to be compatible here? 3111 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3112 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3113 Diag(Old->getLocation(), diag::note_previous_declaration); 3114 } 3115 } 3116 3117 // C++ doesn't have tentative definitions, so go right ahead and check here. 3118 const VarDecl *Def; 3119 if (getLangOpts().CPlusPlus && 3120 New->isThisDeclarationADefinition() == VarDecl::Definition && 3121 (Def = Old->getDefinition())) { 3122 Diag(New->getLocation(), diag::err_redefinition) << New; 3123 Diag(Def->getLocation(), diag::note_previous_definition); 3124 New->setInvalidDecl(); 3125 return; 3126 } 3127 3128 if (haveIncompatibleLanguageLinkages(Old, New)) { 3129 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3130 Diag(Old->getLocation(), diag::note_previous_definition); 3131 New->setInvalidDecl(); 3132 return; 3133 } 3134 3135 // Merge "used" flag. 3136 if (Old->getMostRecentDecl()->isUsed(false)) 3137 New->setIsUsed(); 3138 3139 // Keep a chain of previous declarations. 3140 New->setPreviousDecl(Old); 3141 3142 // Inherit access appropriately. 3143 New->setAccess(Old->getAccess()); 3144 3145 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) { 3146 if (New->isStaticDataMember() && New->isOutOfLine()) 3147 VTD->setAccess(New->getAccess()); 3148 } 3149} 3150 3151/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3152/// no declarator (e.g. "struct foo;") is parsed. 3153Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3154 DeclSpec &DS) { 3155 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3156} 3157 3158static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3159 if (!S.Context.getLangOpts().CPlusPlus) 3160 return; 3161 3162 if (isa<CXXRecordDecl>(Tag->getParent())) { 3163 // If this tag is the direct child of a class, number it if 3164 // it is anonymous. 3165 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3166 return; 3167 MangleNumberingContext &MCtx = 3168 S.Context.getManglingNumberContext(Tag->getParent()); 3169 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3170 return; 3171 } 3172 3173 // If this tag isn't a direct child of a class, number it if it is local. 3174 Decl *ManglingContextDecl; 3175 if (MangleNumberingContext *MCtx = 3176 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3177 ManglingContextDecl)) { 3178 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3179 } 3180} 3181 3182/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3183/// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3184/// parameters to cope with template friend declarations. 3185Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3186 DeclSpec &DS, 3187 MultiTemplateParamsArg TemplateParams, 3188 bool IsExplicitInstantiation) { 3189 Decl *TagD = 0; 3190 TagDecl *Tag = 0; 3191 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3192 DS.getTypeSpecType() == DeclSpec::TST_struct || 3193 DS.getTypeSpecType() == DeclSpec::TST_interface || 3194 DS.getTypeSpecType() == DeclSpec::TST_union || 3195 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3196 TagD = DS.getRepAsDecl(); 3197 3198 if (!TagD) // We probably had an error 3199 return 0; 3200 3201 // Note that the above type specs guarantee that the 3202 // type rep is a Decl, whereas in many of the others 3203 // it's a Type. 3204 if (isa<TagDecl>(TagD)) 3205 Tag = cast<TagDecl>(TagD); 3206 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3207 Tag = CTD->getTemplatedDecl(); 3208 } 3209 3210 if (Tag) { 3211 HandleTagNumbering(*this, Tag); 3212 Tag->setFreeStanding(); 3213 if (Tag->isInvalidDecl()) 3214 return Tag; 3215 } 3216 3217 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3218 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3219 // or incomplete types shall not be restrict-qualified." 3220 if (TypeQuals & DeclSpec::TQ_restrict) 3221 Diag(DS.getRestrictSpecLoc(), 3222 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3223 << DS.getSourceRange(); 3224 } 3225 3226 if (DS.isConstexprSpecified()) { 3227 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3228 // and definitions of functions and variables. 3229 if (Tag) 3230 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3231 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3232 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3233 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3234 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3235 else 3236 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3237 // Don't emit warnings after this error. 3238 return TagD; 3239 } 3240 3241 DiagnoseFunctionSpecifiers(DS); 3242 3243 if (DS.isFriendSpecified()) { 3244 // If we're dealing with a decl but not a TagDecl, assume that 3245 // whatever routines created it handled the friendship aspect. 3246 if (TagD && !Tag) 3247 return 0; 3248 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3249 } 3250 3251 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3252 bool IsExplicitSpecialization = 3253 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3254 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3255 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3256 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3257 // nested-name-specifier unless it is an explicit instantiation 3258 // or an explicit specialization. 3259 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3260 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3261 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3262 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3263 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3264 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3265 << SS.getRange(); 3266 return 0; 3267 } 3268 3269 // Track whether this decl-specifier declares anything. 3270 bool DeclaresAnything = true; 3271 3272 // Handle anonymous struct definitions. 3273 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3274 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3275 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3276 if (getLangOpts().CPlusPlus || 3277 Record->getDeclContext()->isRecord()) 3278 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3279 3280 DeclaresAnything = false; 3281 } 3282 } 3283 3284 // Check for Microsoft C extension: anonymous struct member. 3285 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3286 CurContext->isRecord() && 3287 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3288 // Handle 2 kinds of anonymous struct: 3289 // struct STRUCT; 3290 // and 3291 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3292 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3293 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3294 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3295 DS.getRepAsType().get()->isStructureType())) { 3296 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3297 << DS.getSourceRange(); 3298 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3299 } 3300 } 3301 3302 // Skip all the checks below if we have a type error. 3303 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3304 (TagD && TagD->isInvalidDecl())) 3305 return TagD; 3306 3307 if (getLangOpts().CPlusPlus && 3308 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3309 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3310 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3311 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3312 DeclaresAnything = false; 3313 3314 if (!DS.isMissingDeclaratorOk()) { 3315 // Customize diagnostic for a typedef missing a name. 3316 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3317 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3318 << DS.getSourceRange(); 3319 else 3320 DeclaresAnything = false; 3321 } 3322 3323 if (DS.isModulePrivateSpecified() && 3324 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3325 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3326 << Tag->getTagKind() 3327 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3328 3329 ActOnDocumentableDecl(TagD); 3330 3331 // C 6.7/2: 3332 // A declaration [...] shall declare at least a declarator [...], a tag, 3333 // or the members of an enumeration. 3334 // C++ [dcl.dcl]p3: 3335 // [If there are no declarators], and except for the declaration of an 3336 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3337 // names into the program, or shall redeclare a name introduced by a 3338 // previous declaration. 3339 if (!DeclaresAnything) { 3340 // In C, we allow this as a (popular) extension / bug. Don't bother 3341 // producing further diagnostics for redundant qualifiers after this. 3342 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3343 return TagD; 3344 } 3345 3346 // C++ [dcl.stc]p1: 3347 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3348 // init-declarator-list of the declaration shall not be empty. 3349 // C++ [dcl.fct.spec]p1: 3350 // If a cv-qualifier appears in a decl-specifier-seq, the 3351 // init-declarator-list of the declaration shall not be empty. 3352 // 3353 // Spurious qualifiers here appear to be valid in C. 3354 unsigned DiagID = diag::warn_standalone_specifier; 3355 if (getLangOpts().CPlusPlus) 3356 DiagID = diag::ext_standalone_specifier; 3357 3358 // Note that a linkage-specification sets a storage class, but 3359 // 'extern "C" struct foo;' is actually valid and not theoretically 3360 // useless. 3361 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3362 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3363 Diag(DS.getStorageClassSpecLoc(), DiagID) 3364 << DeclSpec::getSpecifierName(SCS); 3365 3366 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3367 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3368 << DeclSpec::getSpecifierName(TSCS); 3369 if (DS.getTypeQualifiers()) { 3370 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3371 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3372 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3373 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3374 // Restrict is covered above. 3375 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3376 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3377 } 3378 3379 // Warn about ignored type attributes, for example: 3380 // __attribute__((aligned)) struct A; 3381 // Attributes should be placed after tag to apply to type declaration. 3382 if (!DS.getAttributes().empty()) { 3383 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3384 if (TypeSpecType == DeclSpec::TST_class || 3385 TypeSpecType == DeclSpec::TST_struct || 3386 TypeSpecType == DeclSpec::TST_interface || 3387 TypeSpecType == DeclSpec::TST_union || 3388 TypeSpecType == DeclSpec::TST_enum) { 3389 AttributeList* attrs = DS.getAttributes().getList(); 3390 while (attrs) { 3391 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3392 << attrs->getName() 3393 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3394 TypeSpecType == DeclSpec::TST_struct ? 1 : 3395 TypeSpecType == DeclSpec::TST_union ? 2 : 3396 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3397 attrs = attrs->getNext(); 3398 } 3399 } 3400 } 3401 3402 return TagD; 3403} 3404 3405/// We are trying to inject an anonymous member into the given scope; 3406/// check if there's an existing declaration that can't be overloaded. 3407/// 3408/// \return true if this is a forbidden redeclaration 3409static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3410 Scope *S, 3411 DeclContext *Owner, 3412 DeclarationName Name, 3413 SourceLocation NameLoc, 3414 unsigned diagnostic) { 3415 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3416 Sema::ForRedeclaration); 3417 if (!SemaRef.LookupName(R, S)) return false; 3418 3419 if (R.getAsSingle<TagDecl>()) 3420 return false; 3421 3422 // Pick a representative declaration. 3423 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3424 assert(PrevDecl && "Expected a non-null Decl"); 3425 3426 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3427 return false; 3428 3429 SemaRef.Diag(NameLoc, diagnostic) << Name; 3430 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3431 3432 return true; 3433} 3434 3435/// InjectAnonymousStructOrUnionMembers - Inject the members of the 3436/// anonymous struct or union AnonRecord into the owning context Owner 3437/// and scope S. This routine will be invoked just after we realize 3438/// that an unnamed union or struct is actually an anonymous union or 3439/// struct, e.g., 3440/// 3441/// @code 3442/// union { 3443/// int i; 3444/// float f; 3445/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3446/// // f into the surrounding scope.x 3447/// @endcode 3448/// 3449/// This routine is recursive, injecting the names of nested anonymous 3450/// structs/unions into the owning context and scope as well. 3451static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3452 DeclContext *Owner, 3453 RecordDecl *AnonRecord, 3454 AccessSpecifier AS, 3455 SmallVectorImpl<NamedDecl *> &Chaining, 3456 bool MSAnonStruct) { 3457 unsigned diagKind 3458 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3459 : diag::err_anonymous_struct_member_redecl; 3460 3461 bool Invalid = false; 3462 3463 // Look every FieldDecl and IndirectFieldDecl with a name. 3464 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3465 DEnd = AnonRecord->decls_end(); 3466 D != DEnd; ++D) { 3467 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3468 cast<NamedDecl>(*D)->getDeclName()) { 3469 ValueDecl *VD = cast<ValueDecl>(*D); 3470 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3471 VD->getLocation(), diagKind)) { 3472 // C++ [class.union]p2: 3473 // The names of the members of an anonymous union shall be 3474 // distinct from the names of any other entity in the 3475 // scope in which the anonymous union is declared. 3476 Invalid = true; 3477 } else { 3478 // C++ [class.union]p2: 3479 // For the purpose of name lookup, after the anonymous union 3480 // definition, the members of the anonymous union are 3481 // considered to have been defined in the scope in which the 3482 // anonymous union is declared. 3483 unsigned OldChainingSize = Chaining.size(); 3484 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3485 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3486 PE = IF->chain_end(); PI != PE; ++PI) 3487 Chaining.push_back(*PI); 3488 else 3489 Chaining.push_back(VD); 3490 3491 assert(Chaining.size() >= 2); 3492 NamedDecl **NamedChain = 3493 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3494 for (unsigned i = 0; i < Chaining.size(); i++) 3495 NamedChain[i] = Chaining[i]; 3496 3497 IndirectFieldDecl* IndirectField = 3498 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3499 VD->getIdentifier(), VD->getType(), 3500 NamedChain, Chaining.size()); 3501 3502 IndirectField->setAccess(AS); 3503 IndirectField->setImplicit(); 3504 SemaRef.PushOnScopeChains(IndirectField, S); 3505 3506 // That includes picking up the appropriate access specifier. 3507 if (AS != AS_none) IndirectField->setAccess(AS); 3508 3509 Chaining.resize(OldChainingSize); 3510 } 3511 } 3512 } 3513 3514 return Invalid; 3515} 3516 3517/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3518/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3519/// illegal input values are mapped to SC_None. 3520static StorageClass 3521StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3522 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3523 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3524 "Parser allowed 'typedef' as storage class VarDecl."); 3525 switch (StorageClassSpec) { 3526 case DeclSpec::SCS_unspecified: return SC_None; 3527 case DeclSpec::SCS_extern: 3528 if (DS.isExternInLinkageSpec()) 3529 return SC_None; 3530 return SC_Extern; 3531 case DeclSpec::SCS_static: return SC_Static; 3532 case DeclSpec::SCS_auto: return SC_Auto; 3533 case DeclSpec::SCS_register: return SC_Register; 3534 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3535 // Illegal SCSs map to None: error reporting is up to the caller. 3536 case DeclSpec::SCS_mutable: // Fall through. 3537 case DeclSpec::SCS_typedef: return SC_None; 3538 } 3539 llvm_unreachable("unknown storage class specifier"); 3540} 3541 3542/// BuildAnonymousStructOrUnion - Handle the declaration of an 3543/// anonymous structure or union. Anonymous unions are a C++ feature 3544/// (C++ [class.union]) and a C11 feature; anonymous structures 3545/// are a C11 feature and GNU C++ extension. 3546Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3547 AccessSpecifier AS, 3548 RecordDecl *Record) { 3549 DeclContext *Owner = Record->getDeclContext(); 3550 3551 // Diagnose whether this anonymous struct/union is an extension. 3552 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3553 Diag(Record->getLocation(), diag::ext_anonymous_union); 3554 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3555 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3556 else if (!Record->isUnion() && !getLangOpts().C11) 3557 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3558 3559 // C and C++ require different kinds of checks for anonymous 3560 // structs/unions. 3561 bool Invalid = false; 3562 if (getLangOpts().CPlusPlus) { 3563 const char* PrevSpec = 0; 3564 unsigned DiagID; 3565 if (Record->isUnion()) { 3566 // C++ [class.union]p6: 3567 // Anonymous unions declared in a named namespace or in the 3568 // global namespace shall be declared static. 3569 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3570 (isa<TranslationUnitDecl>(Owner) || 3571 (isa<NamespaceDecl>(Owner) && 3572 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3573 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3574 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3575 3576 // Recover by adding 'static'. 3577 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3578 PrevSpec, DiagID); 3579 } 3580 // C++ [class.union]p6: 3581 // A storage class is not allowed in a declaration of an 3582 // anonymous union in a class scope. 3583 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3584 isa<RecordDecl>(Owner)) { 3585 Diag(DS.getStorageClassSpecLoc(), 3586 diag::err_anonymous_union_with_storage_spec) 3587 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3588 3589 // Recover by removing the storage specifier. 3590 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3591 SourceLocation(), 3592 PrevSpec, DiagID); 3593 } 3594 } 3595 3596 // Ignore const/volatile/restrict qualifiers. 3597 if (DS.getTypeQualifiers()) { 3598 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3599 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3600 << Record->isUnion() << "const" 3601 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3602 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3603 Diag(DS.getVolatileSpecLoc(), 3604 diag::ext_anonymous_struct_union_qualified) 3605 << Record->isUnion() << "volatile" 3606 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3607 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3608 Diag(DS.getRestrictSpecLoc(), 3609 diag::ext_anonymous_struct_union_qualified) 3610 << Record->isUnion() << "restrict" 3611 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3612 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3613 Diag(DS.getAtomicSpecLoc(), 3614 diag::ext_anonymous_struct_union_qualified) 3615 << Record->isUnion() << "_Atomic" 3616 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3617 3618 DS.ClearTypeQualifiers(); 3619 } 3620 3621 // C++ [class.union]p2: 3622 // The member-specification of an anonymous union shall only 3623 // define non-static data members. [Note: nested types and 3624 // functions cannot be declared within an anonymous union. ] 3625 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3626 MemEnd = Record->decls_end(); 3627 Mem != MemEnd; ++Mem) { 3628 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3629 // C++ [class.union]p3: 3630 // An anonymous union shall not have private or protected 3631 // members (clause 11). 3632 assert(FD->getAccess() != AS_none); 3633 if (FD->getAccess() != AS_public) { 3634 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3635 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3636 Invalid = true; 3637 } 3638 3639 // C++ [class.union]p1 3640 // An object of a class with a non-trivial constructor, a non-trivial 3641 // copy constructor, a non-trivial destructor, or a non-trivial copy 3642 // assignment operator cannot be a member of a union, nor can an 3643 // array of such objects. 3644 if (CheckNontrivialField(FD)) 3645 Invalid = true; 3646 } else if ((*Mem)->isImplicit()) { 3647 // Any implicit members are fine. 3648 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3649 // This is a type that showed up in an 3650 // elaborated-type-specifier inside the anonymous struct or 3651 // union, but which actually declares a type outside of the 3652 // anonymous struct or union. It's okay. 3653 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3654 if (!MemRecord->isAnonymousStructOrUnion() && 3655 MemRecord->getDeclName()) { 3656 // Visual C++ allows type definition in anonymous struct or union. 3657 if (getLangOpts().MicrosoftExt) 3658 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3659 << (int)Record->isUnion(); 3660 else { 3661 // This is a nested type declaration. 3662 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3663 << (int)Record->isUnion(); 3664 Invalid = true; 3665 } 3666 } else { 3667 // This is an anonymous type definition within another anonymous type. 3668 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3669 // not part of standard C++. 3670 Diag(MemRecord->getLocation(), 3671 diag::ext_anonymous_record_with_anonymous_type) 3672 << (int)Record->isUnion(); 3673 } 3674 } else if (isa<AccessSpecDecl>(*Mem)) { 3675 // Any access specifier is fine. 3676 } else { 3677 // We have something that isn't a non-static data 3678 // member. Complain about it. 3679 unsigned DK = diag::err_anonymous_record_bad_member; 3680 if (isa<TypeDecl>(*Mem)) 3681 DK = diag::err_anonymous_record_with_type; 3682 else if (isa<FunctionDecl>(*Mem)) 3683 DK = diag::err_anonymous_record_with_function; 3684 else if (isa<VarDecl>(*Mem)) 3685 DK = diag::err_anonymous_record_with_static; 3686 3687 // Visual C++ allows type definition in anonymous struct or union. 3688 if (getLangOpts().MicrosoftExt && 3689 DK == diag::err_anonymous_record_with_type) 3690 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3691 << (int)Record->isUnion(); 3692 else { 3693 Diag((*Mem)->getLocation(), DK) 3694 << (int)Record->isUnion(); 3695 Invalid = true; 3696 } 3697 } 3698 } 3699 } 3700 3701 if (!Record->isUnion() && !Owner->isRecord()) { 3702 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3703 << (int)getLangOpts().CPlusPlus; 3704 Invalid = true; 3705 } 3706 3707 // Mock up a declarator. 3708 Declarator Dc(DS, Declarator::MemberContext); 3709 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3710 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3711 3712 // Create a declaration for this anonymous struct/union. 3713 NamedDecl *Anon = 0; 3714 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3715 Anon = FieldDecl::Create(Context, OwningClass, 3716 DS.getLocStart(), 3717 Record->getLocation(), 3718 /*IdentifierInfo=*/0, 3719 Context.getTypeDeclType(Record), 3720 TInfo, 3721 /*BitWidth=*/0, /*Mutable=*/false, 3722 /*InitStyle=*/ICIS_NoInit); 3723 Anon->setAccess(AS); 3724 if (getLangOpts().CPlusPlus) 3725 FieldCollector->Add(cast<FieldDecl>(Anon)); 3726 } else { 3727 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3728 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3729 if (SCSpec == DeclSpec::SCS_mutable) { 3730 // mutable can only appear on non-static class members, so it's always 3731 // an error here 3732 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3733 Invalid = true; 3734 SC = SC_None; 3735 } 3736 3737 Anon = VarDecl::Create(Context, Owner, 3738 DS.getLocStart(), 3739 Record->getLocation(), /*IdentifierInfo=*/0, 3740 Context.getTypeDeclType(Record), 3741 TInfo, SC); 3742 3743 // Default-initialize the implicit variable. This initialization will be 3744 // trivial in almost all cases, except if a union member has an in-class 3745 // initializer: 3746 // union { int n = 0; }; 3747 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3748 } 3749 Anon->setImplicit(); 3750 3751 // Add the anonymous struct/union object to the current 3752 // context. We'll be referencing this object when we refer to one of 3753 // its members. 3754 Owner->addDecl(Anon); 3755 3756 // Inject the members of the anonymous struct/union into the owning 3757 // context and into the identifier resolver chain for name lookup 3758 // purposes. 3759 SmallVector<NamedDecl*, 2> Chain; 3760 Chain.push_back(Anon); 3761 3762 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3763 Chain, false)) 3764 Invalid = true; 3765 3766 // Mark this as an anonymous struct/union type. Note that we do not 3767 // do this until after we have already checked and injected the 3768 // members of this anonymous struct/union type, because otherwise 3769 // the members could be injected twice: once by DeclContext when it 3770 // builds its lookup table, and once by 3771 // InjectAnonymousStructOrUnionMembers. 3772 Record->setAnonymousStructOrUnion(true); 3773 3774 if (Invalid) 3775 Anon->setInvalidDecl(); 3776 3777 return Anon; 3778} 3779 3780/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3781/// Microsoft C anonymous structure. 3782/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3783/// Example: 3784/// 3785/// struct A { int a; }; 3786/// struct B { struct A; int b; }; 3787/// 3788/// void foo() { 3789/// B var; 3790/// var.a = 3; 3791/// } 3792/// 3793Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3794 RecordDecl *Record) { 3795 3796 // If there is no Record, get the record via the typedef. 3797 if (!Record) 3798 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3799 3800 // Mock up a declarator. 3801 Declarator Dc(DS, Declarator::TypeNameContext); 3802 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3803 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3804 3805 // Create a declaration for this anonymous struct. 3806 NamedDecl* Anon = FieldDecl::Create(Context, 3807 cast<RecordDecl>(CurContext), 3808 DS.getLocStart(), 3809 DS.getLocStart(), 3810 /*IdentifierInfo=*/0, 3811 Context.getTypeDeclType(Record), 3812 TInfo, 3813 /*BitWidth=*/0, /*Mutable=*/false, 3814 /*InitStyle=*/ICIS_NoInit); 3815 Anon->setImplicit(); 3816 3817 // Add the anonymous struct object to the current context. 3818 CurContext->addDecl(Anon); 3819 3820 // Inject the members of the anonymous struct into the current 3821 // context and into the identifier resolver chain for name lookup 3822 // purposes. 3823 SmallVector<NamedDecl*, 2> Chain; 3824 Chain.push_back(Anon); 3825 3826 RecordDecl *RecordDef = Record->getDefinition(); 3827 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3828 RecordDef, AS_none, 3829 Chain, true)) 3830 Anon->setInvalidDecl(); 3831 3832 return Anon; 3833} 3834 3835/// GetNameForDeclarator - Determine the full declaration name for the 3836/// given Declarator. 3837DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3838 return GetNameFromUnqualifiedId(D.getName()); 3839} 3840 3841/// \brief Retrieves the declaration name from a parsed unqualified-id. 3842DeclarationNameInfo 3843Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3844 DeclarationNameInfo NameInfo; 3845 NameInfo.setLoc(Name.StartLocation); 3846 3847 switch (Name.getKind()) { 3848 3849 case UnqualifiedId::IK_ImplicitSelfParam: 3850 case UnqualifiedId::IK_Identifier: 3851 NameInfo.setName(Name.Identifier); 3852 NameInfo.setLoc(Name.StartLocation); 3853 return NameInfo; 3854 3855 case UnqualifiedId::IK_OperatorFunctionId: 3856 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3857 Name.OperatorFunctionId.Operator)); 3858 NameInfo.setLoc(Name.StartLocation); 3859 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3860 = Name.OperatorFunctionId.SymbolLocations[0]; 3861 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3862 = Name.EndLocation.getRawEncoding(); 3863 return NameInfo; 3864 3865 case UnqualifiedId::IK_LiteralOperatorId: 3866 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3867 Name.Identifier)); 3868 NameInfo.setLoc(Name.StartLocation); 3869 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3870 return NameInfo; 3871 3872 case UnqualifiedId::IK_ConversionFunctionId: { 3873 TypeSourceInfo *TInfo; 3874 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3875 if (Ty.isNull()) 3876 return DeclarationNameInfo(); 3877 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3878 Context.getCanonicalType(Ty))); 3879 NameInfo.setLoc(Name.StartLocation); 3880 NameInfo.setNamedTypeInfo(TInfo); 3881 return NameInfo; 3882 } 3883 3884 case UnqualifiedId::IK_ConstructorName: { 3885 TypeSourceInfo *TInfo; 3886 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3887 if (Ty.isNull()) 3888 return DeclarationNameInfo(); 3889 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3890 Context.getCanonicalType(Ty))); 3891 NameInfo.setLoc(Name.StartLocation); 3892 NameInfo.setNamedTypeInfo(TInfo); 3893 return NameInfo; 3894 } 3895 3896 case UnqualifiedId::IK_ConstructorTemplateId: { 3897 // In well-formed code, we can only have a constructor 3898 // template-id that refers to the current context, so go there 3899 // to find the actual type being constructed. 3900 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3901 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3902 return DeclarationNameInfo(); 3903 3904 // Determine the type of the class being constructed. 3905 QualType CurClassType = Context.getTypeDeclType(CurClass); 3906 3907 // FIXME: Check two things: that the template-id names the same type as 3908 // CurClassType, and that the template-id does not occur when the name 3909 // was qualified. 3910 3911 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3912 Context.getCanonicalType(CurClassType))); 3913 NameInfo.setLoc(Name.StartLocation); 3914 // FIXME: should we retrieve TypeSourceInfo? 3915 NameInfo.setNamedTypeInfo(0); 3916 return NameInfo; 3917 } 3918 3919 case UnqualifiedId::IK_DestructorName: { 3920 TypeSourceInfo *TInfo; 3921 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3922 if (Ty.isNull()) 3923 return DeclarationNameInfo(); 3924 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3925 Context.getCanonicalType(Ty))); 3926 NameInfo.setLoc(Name.StartLocation); 3927 NameInfo.setNamedTypeInfo(TInfo); 3928 return NameInfo; 3929 } 3930 3931 case UnqualifiedId::IK_TemplateId: { 3932 TemplateName TName = Name.TemplateId->Template.get(); 3933 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3934 return Context.getNameForTemplate(TName, TNameLoc); 3935 } 3936 3937 } // switch (Name.getKind()) 3938 3939 llvm_unreachable("Unknown name kind"); 3940} 3941 3942static QualType getCoreType(QualType Ty) { 3943 do { 3944 if (Ty->isPointerType() || Ty->isReferenceType()) 3945 Ty = Ty->getPointeeType(); 3946 else if (Ty->isArrayType()) 3947 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3948 else 3949 return Ty.withoutLocalFastQualifiers(); 3950 } while (true); 3951} 3952 3953/// hasSimilarParameters - Determine whether the C++ functions Declaration 3954/// and Definition have "nearly" matching parameters. This heuristic is 3955/// used to improve diagnostics in the case where an out-of-line function 3956/// definition doesn't match any declaration within the class or namespace. 3957/// Also sets Params to the list of indices to the parameters that differ 3958/// between the declaration and the definition. If hasSimilarParameters 3959/// returns true and Params is empty, then all of the parameters match. 3960static bool hasSimilarParameters(ASTContext &Context, 3961 FunctionDecl *Declaration, 3962 FunctionDecl *Definition, 3963 SmallVectorImpl<unsigned> &Params) { 3964 Params.clear(); 3965 if (Declaration->param_size() != Definition->param_size()) 3966 return false; 3967 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3968 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3969 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3970 3971 // The parameter types are identical 3972 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3973 continue; 3974 3975 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3976 QualType DefParamBaseTy = getCoreType(DefParamTy); 3977 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3978 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3979 3980 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3981 (DeclTyName && DeclTyName == DefTyName)) 3982 Params.push_back(Idx); 3983 else // The two parameters aren't even close 3984 return false; 3985 } 3986 3987 return true; 3988} 3989 3990/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3991/// declarator needs to be rebuilt in the current instantiation. 3992/// Any bits of declarator which appear before the name are valid for 3993/// consideration here. That's specifically the type in the decl spec 3994/// and the base type in any member-pointer chunks. 3995static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3996 DeclarationName Name) { 3997 // The types we specifically need to rebuild are: 3998 // - typenames, typeofs, and decltypes 3999 // - types which will become injected class names 4000 // Of course, we also need to rebuild any type referencing such a 4001 // type. It's safest to just say "dependent", but we call out a 4002 // few cases here. 4003 4004 DeclSpec &DS = D.getMutableDeclSpec(); 4005 switch (DS.getTypeSpecType()) { 4006 case DeclSpec::TST_typename: 4007 case DeclSpec::TST_typeofType: 4008 case DeclSpec::TST_underlyingType: 4009 case DeclSpec::TST_atomic: { 4010 // Grab the type from the parser. 4011 TypeSourceInfo *TSI = 0; 4012 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4013 if (T.isNull() || !T->isDependentType()) break; 4014 4015 // Make sure there's a type source info. This isn't really much 4016 // of a waste; most dependent types should have type source info 4017 // attached already. 4018 if (!TSI) 4019 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4020 4021 // Rebuild the type in the current instantiation. 4022 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4023 if (!TSI) return true; 4024 4025 // Store the new type back in the decl spec. 4026 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4027 DS.UpdateTypeRep(LocType); 4028 break; 4029 } 4030 4031 case DeclSpec::TST_decltype: 4032 case DeclSpec::TST_typeofExpr: { 4033 Expr *E = DS.getRepAsExpr(); 4034 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4035 if (Result.isInvalid()) return true; 4036 DS.UpdateExprRep(Result.get()); 4037 break; 4038 } 4039 4040 default: 4041 // Nothing to do for these decl specs. 4042 break; 4043 } 4044 4045 // It doesn't matter what order we do this in. 4046 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4047 DeclaratorChunk &Chunk = D.getTypeObject(I); 4048 4049 // The only type information in the declarator which can come 4050 // before the declaration name is the base type of a member 4051 // pointer. 4052 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4053 continue; 4054 4055 // Rebuild the scope specifier in-place. 4056 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4057 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4058 return true; 4059 } 4060 4061 return false; 4062} 4063 4064Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4065 D.setFunctionDefinitionKind(FDK_Declaration); 4066 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4067 4068 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4069 Dcl && Dcl->getDeclContext()->isFileContext()) 4070 Dcl->setTopLevelDeclInObjCContainer(); 4071 4072 return Dcl; 4073} 4074 4075/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4076/// If T is the name of a class, then each of the following shall have a 4077/// name different from T: 4078/// - every static data member of class T; 4079/// - every member function of class T 4080/// - every member of class T that is itself a type; 4081/// \returns true if the declaration name violates these rules. 4082bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4083 DeclarationNameInfo NameInfo) { 4084 DeclarationName Name = NameInfo.getName(); 4085 4086 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4087 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4088 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4089 return true; 4090 } 4091 4092 return false; 4093} 4094 4095/// \brief Diagnose a declaration whose declarator-id has the given 4096/// nested-name-specifier. 4097/// 4098/// \param SS The nested-name-specifier of the declarator-id. 4099/// 4100/// \param DC The declaration context to which the nested-name-specifier 4101/// resolves. 4102/// 4103/// \param Name The name of the entity being declared. 4104/// 4105/// \param Loc The location of the name of the entity being declared. 4106/// 4107/// \returns true if we cannot safely recover from this error, false otherwise. 4108bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4109 DeclarationName Name, 4110 SourceLocation Loc) { 4111 DeclContext *Cur = CurContext; 4112 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4113 Cur = Cur->getParent(); 4114 4115 // C++ [dcl.meaning]p1: 4116 // A declarator-id shall not be qualified except for the definition 4117 // of a member function (9.3) or static data member (9.4) outside of 4118 // its class, the definition or explicit instantiation of a function 4119 // or variable member of a namespace outside of its namespace, or the 4120 // definition of an explicit specialization outside of its namespace, 4121 // or the declaration of a friend function that is a member of 4122 // another class or namespace (11.3). [...] 4123 4124 // The user provided a superfluous scope specifier that refers back to the 4125 // class or namespaces in which the entity is already declared. 4126 // 4127 // class X { 4128 // void X::f(); 4129 // }; 4130 if (Cur->Equals(DC)) { 4131 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 4132 : diag::err_member_extra_qualification) 4133 << Name << FixItHint::CreateRemoval(SS.getRange()); 4134 SS.clear(); 4135 return false; 4136 } 4137 4138 // Check whether the qualifying scope encloses the scope of the original 4139 // declaration. 4140 if (!Cur->Encloses(DC)) { 4141 if (Cur->isRecord()) 4142 Diag(Loc, diag::err_member_qualification) 4143 << Name << SS.getRange(); 4144 else if (isa<TranslationUnitDecl>(DC)) 4145 Diag(Loc, diag::err_invalid_declarator_global_scope) 4146 << Name << SS.getRange(); 4147 else if (isa<FunctionDecl>(Cur)) 4148 Diag(Loc, diag::err_invalid_declarator_in_function) 4149 << Name << SS.getRange(); 4150 else if (isa<BlockDecl>(Cur)) 4151 Diag(Loc, diag::err_invalid_declarator_in_block) 4152 << Name << SS.getRange(); 4153 else 4154 Diag(Loc, diag::err_invalid_declarator_scope) 4155 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4156 4157 return true; 4158 } 4159 4160 if (Cur->isRecord()) { 4161 // Cannot qualify members within a class. 4162 Diag(Loc, diag::err_member_qualification) 4163 << Name << SS.getRange(); 4164 SS.clear(); 4165 4166 // C++ constructors and destructors with incorrect scopes can break 4167 // our AST invariants by having the wrong underlying types. If 4168 // that's the case, then drop this declaration entirely. 4169 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4170 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4171 !Context.hasSameType(Name.getCXXNameType(), 4172 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4173 return true; 4174 4175 return false; 4176 } 4177 4178 // C++11 [dcl.meaning]p1: 4179 // [...] "The nested-name-specifier of the qualified declarator-id shall 4180 // not begin with a decltype-specifer" 4181 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4182 while (SpecLoc.getPrefix()) 4183 SpecLoc = SpecLoc.getPrefix(); 4184 if (dyn_cast_or_null<DecltypeType>( 4185 SpecLoc.getNestedNameSpecifier()->getAsType())) 4186 Diag(Loc, diag::err_decltype_in_declarator) 4187 << SpecLoc.getTypeLoc().getSourceRange(); 4188 4189 return false; 4190} 4191 4192NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4193 MultiTemplateParamsArg TemplateParamLists) { 4194 // TODO: consider using NameInfo for diagnostic. 4195 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4196 DeclarationName Name = NameInfo.getName(); 4197 4198 // All of these full declarators require an identifier. If it doesn't have 4199 // one, the ParsedFreeStandingDeclSpec action should be used. 4200 if (!Name) { 4201 if (!D.isInvalidType()) // Reject this if we think it is valid. 4202 Diag(D.getDeclSpec().getLocStart(), 4203 diag::err_declarator_need_ident) 4204 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4205 return 0; 4206 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4207 return 0; 4208 4209 // The scope passed in may not be a decl scope. Zip up the scope tree until 4210 // we find one that is. 4211 while ((S->getFlags() & Scope::DeclScope) == 0 || 4212 (S->getFlags() & Scope::TemplateParamScope) != 0) 4213 S = S->getParent(); 4214 4215 DeclContext *DC = CurContext; 4216 if (D.getCXXScopeSpec().isInvalid()) 4217 D.setInvalidType(); 4218 else if (D.getCXXScopeSpec().isSet()) { 4219 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4220 UPPC_DeclarationQualifier)) 4221 return 0; 4222 4223 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4224 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4225 if (!DC) { 4226 // If we could not compute the declaration context, it's because the 4227 // declaration context is dependent but does not refer to a class, 4228 // class template, or class template partial specialization. Complain 4229 // and return early, to avoid the coming semantic disaster. 4230 Diag(D.getIdentifierLoc(), 4231 diag::err_template_qualified_declarator_no_match) 4232 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4233 << D.getCXXScopeSpec().getRange(); 4234 return 0; 4235 } 4236 bool IsDependentContext = DC->isDependentContext(); 4237 4238 if (!IsDependentContext && 4239 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4240 return 0; 4241 4242 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4243 Diag(D.getIdentifierLoc(), 4244 diag::err_member_def_undefined_record) 4245 << Name << DC << D.getCXXScopeSpec().getRange(); 4246 D.setInvalidType(); 4247 } else if (!D.getDeclSpec().isFriendSpecified()) { 4248 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4249 Name, D.getIdentifierLoc())) { 4250 if (DC->isRecord()) 4251 return 0; 4252 4253 D.setInvalidType(); 4254 } 4255 } 4256 4257 // Check whether we need to rebuild the type of the given 4258 // declaration in the current instantiation. 4259 if (EnteringContext && IsDependentContext && 4260 TemplateParamLists.size() != 0) { 4261 ContextRAII SavedContext(*this, DC); 4262 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4263 D.setInvalidType(); 4264 } 4265 } 4266 4267 if (DiagnoseClassNameShadow(DC, NameInfo)) 4268 // If this is a typedef, we'll end up spewing multiple diagnostics. 4269 // Just return early; it's safer. 4270 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4271 return 0; 4272 4273 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4274 QualType R = TInfo->getType(); 4275 4276 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4277 UPPC_DeclarationType)) 4278 D.setInvalidType(); 4279 4280 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4281 ForRedeclaration); 4282 4283 // See if this is a redefinition of a variable in the same scope. 4284 if (!D.getCXXScopeSpec().isSet()) { 4285 bool IsLinkageLookup = false; 4286 bool CreateBuiltins = false; 4287 4288 // If the declaration we're planning to build will be a function 4289 // or object with linkage, then look for another declaration with 4290 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4291 // 4292 // If the declaration we're planning to build will be declared with 4293 // external linkage in the translation unit, create any builtin with 4294 // the same name. 4295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4296 /* Do nothing*/; 4297 else if (CurContext->isFunctionOrMethod() && 4298 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4299 R->isFunctionType())) { 4300 IsLinkageLookup = true; 4301 CreateBuiltins = 4302 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4303 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4304 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4305 CreateBuiltins = true; 4306 4307 if (IsLinkageLookup) 4308 Previous.clear(LookupRedeclarationWithLinkage); 4309 4310 LookupName(Previous, S, CreateBuiltins); 4311 } else { // Something like "int foo::x;" 4312 LookupQualifiedName(Previous, DC); 4313 4314 // C++ [dcl.meaning]p1: 4315 // When the declarator-id is qualified, the declaration shall refer to a 4316 // previously declared member of the class or namespace to which the 4317 // qualifier refers (or, in the case of a namespace, of an element of the 4318 // inline namespace set of that namespace (7.3.1)) or to a specialization 4319 // thereof; [...] 4320 // 4321 // Note that we already checked the context above, and that we do not have 4322 // enough information to make sure that Previous contains the declaration 4323 // we want to match. For example, given: 4324 // 4325 // class X { 4326 // void f(); 4327 // void f(float); 4328 // }; 4329 // 4330 // void X::f(int) { } // ill-formed 4331 // 4332 // In this case, Previous will point to the overload set 4333 // containing the two f's declared in X, but neither of them 4334 // matches. 4335 4336 // C++ [dcl.meaning]p1: 4337 // [...] the member shall not merely have been introduced by a 4338 // using-declaration in the scope of the class or namespace nominated by 4339 // the nested-name-specifier of the declarator-id. 4340 RemoveUsingDecls(Previous); 4341 } 4342 4343 if (Previous.isSingleResult() && 4344 Previous.getFoundDecl()->isTemplateParameter()) { 4345 // Maybe we will complain about the shadowed template parameter. 4346 if (!D.isInvalidType()) 4347 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4348 Previous.getFoundDecl()); 4349 4350 // Just pretend that we didn't see the previous declaration. 4351 Previous.clear(); 4352 } 4353 4354 // In C++, the previous declaration we find might be a tag type 4355 // (class or enum). In this case, the new declaration will hide the 4356 // tag type. Note that this does does not apply if we're declaring a 4357 // typedef (C++ [dcl.typedef]p4). 4358 if (Previous.isSingleTagDecl() && 4359 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4360 Previous.clear(); 4361 4362 // Check that there are no default arguments other than in the parameters 4363 // of a function declaration (C++ only). 4364 if (getLangOpts().CPlusPlus) 4365 CheckExtraCXXDefaultArguments(D); 4366 4367 NamedDecl *New; 4368 4369 bool AddToScope = true; 4370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4371 if (TemplateParamLists.size()) { 4372 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4373 return 0; 4374 } 4375 4376 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4377 } else if (R->isFunctionType()) { 4378 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4379 TemplateParamLists, 4380 AddToScope); 4381 } else { 4382 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4383 AddToScope); 4384 } 4385 4386 if (New == 0) 4387 return 0; 4388 4389 // If this has an identifier and is not an invalid redeclaration or 4390 // function template specialization, add it to the scope stack. 4391 if (New->getDeclName() && AddToScope && 4392 !(D.isRedeclaration() && New->isInvalidDecl())) { 4393 // Only make a locally-scoped extern declaration visible if it is the first 4394 // declaration of this entity. Qualified lookup for such an entity should 4395 // only find this declaration if there is no visible declaration of it. 4396 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4397 PushOnScopeChains(New, S, AddToContext); 4398 if (!AddToContext) 4399 CurContext->addHiddenDecl(New); 4400 } 4401 4402 return New; 4403} 4404 4405/// Helper method to turn variable array types into constant array 4406/// types in certain situations which would otherwise be errors (for 4407/// GCC compatibility). 4408static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4409 ASTContext &Context, 4410 bool &SizeIsNegative, 4411 llvm::APSInt &Oversized) { 4412 // This method tries to turn a variable array into a constant 4413 // array even when the size isn't an ICE. This is necessary 4414 // for compatibility with code that depends on gcc's buggy 4415 // constant expression folding, like struct {char x[(int)(char*)2];} 4416 SizeIsNegative = false; 4417 Oversized = 0; 4418 4419 if (T->isDependentType()) 4420 return QualType(); 4421 4422 QualifierCollector Qs; 4423 const Type *Ty = Qs.strip(T); 4424 4425 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4426 QualType Pointee = PTy->getPointeeType(); 4427 QualType FixedType = 4428 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4429 Oversized); 4430 if (FixedType.isNull()) return FixedType; 4431 FixedType = Context.getPointerType(FixedType); 4432 return Qs.apply(Context, FixedType); 4433 } 4434 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4435 QualType Inner = PTy->getInnerType(); 4436 QualType FixedType = 4437 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4438 Oversized); 4439 if (FixedType.isNull()) return FixedType; 4440 FixedType = Context.getParenType(FixedType); 4441 return Qs.apply(Context, FixedType); 4442 } 4443 4444 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4445 if (!VLATy) 4446 return QualType(); 4447 // FIXME: We should probably handle this case 4448 if (VLATy->getElementType()->isVariablyModifiedType()) 4449 return QualType(); 4450 4451 llvm::APSInt Res; 4452 if (!VLATy->getSizeExpr() || 4453 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4454 return QualType(); 4455 4456 // Check whether the array size is negative. 4457 if (Res.isSigned() && Res.isNegative()) { 4458 SizeIsNegative = true; 4459 return QualType(); 4460 } 4461 4462 // Check whether the array is too large to be addressed. 4463 unsigned ActiveSizeBits 4464 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4465 Res); 4466 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4467 Oversized = Res; 4468 return QualType(); 4469 } 4470 4471 return Context.getConstantArrayType(VLATy->getElementType(), 4472 Res, ArrayType::Normal, 0); 4473} 4474 4475static void 4476FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4477 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4478 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4479 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4480 DstPTL.getPointeeLoc()); 4481 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4482 return; 4483 } 4484 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4485 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4486 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4487 DstPTL.getInnerLoc()); 4488 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4489 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4490 return; 4491 } 4492 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4493 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4494 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4495 TypeLoc DstElemTL = DstATL.getElementLoc(); 4496 DstElemTL.initializeFullCopy(SrcElemTL); 4497 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4498 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4499 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4500} 4501 4502/// Helper method to turn variable array types into constant array 4503/// types in certain situations which would otherwise be errors (for 4504/// GCC compatibility). 4505static TypeSourceInfo* 4506TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4507 ASTContext &Context, 4508 bool &SizeIsNegative, 4509 llvm::APSInt &Oversized) { 4510 QualType FixedTy 4511 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4512 SizeIsNegative, Oversized); 4513 if (FixedTy.isNull()) 4514 return 0; 4515 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4516 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4517 FixedTInfo->getTypeLoc()); 4518 return FixedTInfo; 4519} 4520 4521/// \brief Register the given locally-scoped extern "C" declaration so 4522/// that it can be found later for redeclarations. We include any extern "C" 4523/// declaration that is not visible in the translation unit here, not just 4524/// function-scope declarations. 4525void 4526Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4527 if (!getLangOpts().CPlusPlus && 4528 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4529 // Don't need to track declarations in the TU in C. 4530 return; 4531 4532 // Note that we have a locally-scoped external with this name. 4533 // FIXME: There can be multiple such declarations if they are functions marked 4534 // __attribute__((overloadable)) declared in function scope in C. 4535 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4536} 4537 4538NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4539 if (ExternalSource) { 4540 // Load locally-scoped external decls from the external source. 4541 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4542 SmallVector<NamedDecl *, 4> Decls; 4543 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4544 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4545 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4546 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4547 if (Pos == LocallyScopedExternCDecls.end()) 4548 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4549 } 4550 } 4551 4552 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4553 return D ? D->getMostRecentDecl() : 0; 4554} 4555 4556/// \brief Diagnose function specifiers on a declaration of an identifier that 4557/// does not identify a function. 4558void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4559 // FIXME: We should probably indicate the identifier in question to avoid 4560 // confusion for constructs like "inline int a(), b;" 4561 if (DS.isInlineSpecified()) 4562 Diag(DS.getInlineSpecLoc(), 4563 diag::err_inline_non_function); 4564 4565 if (DS.isVirtualSpecified()) 4566 Diag(DS.getVirtualSpecLoc(), 4567 diag::err_virtual_non_function); 4568 4569 if (DS.isExplicitSpecified()) 4570 Diag(DS.getExplicitSpecLoc(), 4571 diag::err_explicit_non_function); 4572 4573 if (DS.isNoreturnSpecified()) 4574 Diag(DS.getNoreturnSpecLoc(), 4575 diag::err_noreturn_non_function); 4576} 4577 4578NamedDecl* 4579Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4580 TypeSourceInfo *TInfo, LookupResult &Previous) { 4581 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4582 if (D.getCXXScopeSpec().isSet()) { 4583 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4584 << D.getCXXScopeSpec().getRange(); 4585 D.setInvalidType(); 4586 // Pretend we didn't see the scope specifier. 4587 DC = CurContext; 4588 Previous.clear(); 4589 } 4590 4591 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4592 4593 if (D.getDeclSpec().isConstexprSpecified()) 4594 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4595 << 1; 4596 4597 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4598 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4599 << D.getName().getSourceRange(); 4600 return 0; 4601 } 4602 4603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4604 if (!NewTD) return 0; 4605 4606 // Handle attributes prior to checking for duplicates in MergeVarDecl 4607 ProcessDeclAttributes(S, NewTD, D); 4608 4609 CheckTypedefForVariablyModifiedType(S, NewTD); 4610 4611 bool Redeclaration = D.isRedeclaration(); 4612 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4613 D.setRedeclaration(Redeclaration); 4614 return ND; 4615} 4616 4617void 4618Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4619 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4620 // then it shall have block scope. 4621 // Note that variably modified types must be fixed before merging the decl so 4622 // that redeclarations will match. 4623 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4624 QualType T = TInfo->getType(); 4625 if (T->isVariablyModifiedType()) { 4626 getCurFunction()->setHasBranchProtectedScope(); 4627 4628 if (S->getFnParent() == 0) { 4629 bool SizeIsNegative; 4630 llvm::APSInt Oversized; 4631 TypeSourceInfo *FixedTInfo = 4632 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4633 SizeIsNegative, 4634 Oversized); 4635 if (FixedTInfo) { 4636 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4637 NewTD->setTypeSourceInfo(FixedTInfo); 4638 } else { 4639 if (SizeIsNegative) 4640 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4641 else if (T->isVariableArrayType()) 4642 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4643 else if (Oversized.getBoolValue()) 4644 Diag(NewTD->getLocation(), diag::err_array_too_large) 4645 << Oversized.toString(10); 4646 else 4647 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4648 NewTD->setInvalidDecl(); 4649 } 4650 } 4651 } 4652} 4653 4654 4655/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4656/// declares a typedef-name, either using the 'typedef' type specifier or via 4657/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4658NamedDecl* 4659Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4660 LookupResult &Previous, bool &Redeclaration) { 4661 // Merge the decl with the existing one if appropriate. If the decl is 4662 // in an outer scope, it isn't the same thing. 4663 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4664 /*ExplicitInstantiationOrSpecialization=*/false); 4665 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4666 if (!Previous.empty()) { 4667 Redeclaration = true; 4668 MergeTypedefNameDecl(NewTD, Previous); 4669 } 4670 4671 // If this is the C FILE type, notify the AST context. 4672 if (IdentifierInfo *II = NewTD->getIdentifier()) 4673 if (!NewTD->isInvalidDecl() && 4674 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4675 if (II->isStr("FILE")) 4676 Context.setFILEDecl(NewTD); 4677 else if (II->isStr("jmp_buf")) 4678 Context.setjmp_bufDecl(NewTD); 4679 else if (II->isStr("sigjmp_buf")) 4680 Context.setsigjmp_bufDecl(NewTD); 4681 else if (II->isStr("ucontext_t")) 4682 Context.setucontext_tDecl(NewTD); 4683 } 4684 4685 return NewTD; 4686} 4687 4688/// \brief Determines whether the given declaration is an out-of-scope 4689/// previous declaration. 4690/// 4691/// This routine should be invoked when name lookup has found a 4692/// previous declaration (PrevDecl) that is not in the scope where a 4693/// new declaration by the same name is being introduced. If the new 4694/// declaration occurs in a local scope, previous declarations with 4695/// linkage may still be considered previous declarations (C99 4696/// 6.2.2p4-5, C++ [basic.link]p6). 4697/// 4698/// \param PrevDecl the previous declaration found by name 4699/// lookup 4700/// 4701/// \param DC the context in which the new declaration is being 4702/// declared. 4703/// 4704/// \returns true if PrevDecl is an out-of-scope previous declaration 4705/// for a new delcaration with the same name. 4706static bool 4707isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4708 ASTContext &Context) { 4709 if (!PrevDecl) 4710 return false; 4711 4712 if (!PrevDecl->hasLinkage()) 4713 return false; 4714 4715 if (Context.getLangOpts().CPlusPlus) { 4716 // C++ [basic.link]p6: 4717 // If there is a visible declaration of an entity with linkage 4718 // having the same name and type, ignoring entities declared 4719 // outside the innermost enclosing namespace scope, the block 4720 // scope declaration declares that same entity and receives the 4721 // linkage of the previous declaration. 4722 DeclContext *OuterContext = DC->getRedeclContext(); 4723 if (!OuterContext->isFunctionOrMethod()) 4724 // This rule only applies to block-scope declarations. 4725 return false; 4726 4727 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4728 if (PrevOuterContext->isRecord()) 4729 // We found a member function: ignore it. 4730 return false; 4731 4732 // Find the innermost enclosing namespace for the new and 4733 // previous declarations. 4734 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4735 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4736 4737 // The previous declaration is in a different namespace, so it 4738 // isn't the same function. 4739 if (!OuterContext->Equals(PrevOuterContext)) 4740 return false; 4741 } 4742 4743 return true; 4744} 4745 4746static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4747 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4748 if (!SS.isSet()) return; 4749 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4750} 4751 4752bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4753 QualType type = decl->getType(); 4754 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4755 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4756 // Various kinds of declaration aren't allowed to be __autoreleasing. 4757 unsigned kind = -1U; 4758 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4759 if (var->hasAttr<BlocksAttr>()) 4760 kind = 0; // __block 4761 else if (!var->hasLocalStorage()) 4762 kind = 1; // global 4763 } else if (isa<ObjCIvarDecl>(decl)) { 4764 kind = 3; // ivar 4765 } else if (isa<FieldDecl>(decl)) { 4766 kind = 2; // field 4767 } 4768 4769 if (kind != -1U) { 4770 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4771 << kind; 4772 } 4773 } else if (lifetime == Qualifiers::OCL_None) { 4774 // Try to infer lifetime. 4775 if (!type->isObjCLifetimeType()) 4776 return false; 4777 4778 lifetime = type->getObjCARCImplicitLifetime(); 4779 type = Context.getLifetimeQualifiedType(type, lifetime); 4780 decl->setType(type); 4781 } 4782 4783 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4784 // Thread-local variables cannot have lifetime. 4785 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4786 var->getTLSKind()) { 4787 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4788 << var->getType(); 4789 return true; 4790 } 4791 } 4792 4793 return false; 4794} 4795 4796static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4797 // 'weak' only applies to declarations with external linkage. 4798 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4799 if (!ND.isExternallyVisible()) { 4800 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4801 ND.dropAttr<WeakAttr>(); 4802 } 4803 } 4804 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4805 if (ND.isExternallyVisible()) { 4806 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4807 ND.dropAttr<WeakRefAttr>(); 4808 } 4809 } 4810 4811 // 'selectany' only applies to externally visible varable declarations. 4812 // It does not apply to functions. 4813 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4814 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4815 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4816 ND.dropAttr<SelectAnyAttr>(); 4817 } 4818 } 4819} 4820 4821/// Given that we are within the definition of the given function, 4822/// will that definition behave like C99's 'inline', where the 4823/// definition is discarded except for optimization purposes? 4824static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4825 // Try to avoid calling GetGVALinkageForFunction. 4826 4827 // All cases of this require the 'inline' keyword. 4828 if (!FD->isInlined()) return false; 4829 4830 // This is only possible in C++ with the gnu_inline attribute. 4831 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4832 return false; 4833 4834 // Okay, go ahead and call the relatively-more-expensive function. 4835 4836#ifndef NDEBUG 4837 // AST quite reasonably asserts that it's working on a function 4838 // definition. We don't really have a way to tell it that we're 4839 // currently defining the function, so just lie to it in +Asserts 4840 // builds. This is an awful hack. 4841 FD->setLazyBody(1); 4842#endif 4843 4844 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4845 4846#ifndef NDEBUG 4847 FD->setLazyBody(0); 4848#endif 4849 4850 return isC99Inline; 4851} 4852 4853/// Determine whether a variable is extern "C" prior to attaching 4854/// an initializer. We can't just call isExternC() here, because that 4855/// will also compute and cache whether the declaration is externally 4856/// visible, which might change when we attach the initializer. 4857/// 4858/// This can only be used if the declaration is known to not be a 4859/// redeclaration of an internal linkage declaration. 4860/// 4861/// For instance: 4862/// 4863/// auto x = []{}; 4864/// 4865/// Attaching the initializer here makes this declaration not externally 4866/// visible, because its type has internal linkage. 4867/// 4868/// FIXME: This is a hack. 4869template<typename T> 4870static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4871 if (S.getLangOpts().CPlusPlus) { 4872 // In C++, the overloadable attribute negates the effects of extern "C". 4873 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4874 return false; 4875 } 4876 return D->isExternC(); 4877} 4878 4879static bool shouldConsiderLinkage(const VarDecl *VD) { 4880 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4881 if (DC->isFunctionOrMethod()) 4882 return VD->hasExternalStorage(); 4883 if (DC->isFileContext()) 4884 return true; 4885 if (DC->isRecord()) 4886 return false; 4887 llvm_unreachable("Unexpected context"); 4888} 4889 4890static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4891 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4892 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4893 return true; 4894 if (DC->isRecord()) 4895 return false; 4896 llvm_unreachable("Unexpected context"); 4897} 4898 4899/// Adjust the \c DeclContext for a function or variable that might be a 4900/// function-local external declaration. 4901bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4902 if (!DC->isFunctionOrMethod()) 4903 return false; 4904 4905 // If this is a local extern function or variable declared within a function 4906 // template, don't add it into the enclosing namespace scope until it is 4907 // instantiated; it might have a dependent type right now. 4908 if (DC->isDependentContext()) 4909 return true; 4910 4911 // C++11 [basic.link]p7: 4912 // When a block scope declaration of an entity with linkage is not found to 4913 // refer to some other declaration, then that entity is a member of the 4914 // innermost enclosing namespace. 4915 // 4916 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4917 // semantically-enclosing namespace, not a lexically-enclosing one. 4918 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4919 DC = DC->getParent(); 4920 return true; 4921} 4922 4923NamedDecl * 4924Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4925 TypeSourceInfo *TInfo, LookupResult &Previous, 4926 MultiTemplateParamsArg TemplateParamLists, 4927 bool &AddToScope) { 4928 QualType R = TInfo->getType(); 4929 DeclarationName Name = GetNameForDeclarator(D).getName(); 4930 4931 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4932 VarDecl::StorageClass SC = 4933 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4934 4935 DeclContext *OriginalDC = DC; 4936 bool IsLocalExternDecl = SC == SC_Extern && 4937 adjustContextForLocalExternDecl(DC); 4938 4939 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4940 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4941 // half array type (unless the cl_khr_fp16 extension is enabled). 4942 if (Context.getBaseElementType(R)->isHalfType()) { 4943 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4944 D.setInvalidType(); 4945 } 4946 } 4947 4948 if (SCSpec == DeclSpec::SCS_mutable) { 4949 // mutable can only appear on non-static class members, so it's always 4950 // an error here 4951 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4952 D.setInvalidType(); 4953 SC = SC_None; 4954 } 4955 4956 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 4957 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 4958 D.getDeclSpec().getStorageClassSpecLoc())) { 4959 // In C++11, the 'register' storage class specifier is deprecated. 4960 // Suppress the warning in system macros, it's used in macros in some 4961 // popular C system headers, such as in glibc's htonl() macro. 4962 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4963 diag::warn_deprecated_register) 4964 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4965 } 4966 4967 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4968 if (!II) { 4969 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4970 << Name; 4971 return 0; 4972 } 4973 4974 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4975 4976 if (!DC->isRecord() && S->getFnParent() == 0) { 4977 // C99 6.9p2: The storage-class specifiers auto and register shall not 4978 // appear in the declaration specifiers in an external declaration. 4979 if (SC == SC_Auto || SC == SC_Register) { 4980 // If this is a register variable with an asm label specified, then this 4981 // is a GNU extension. 4982 if (SC == SC_Register && D.getAsmLabel()) 4983 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4984 else 4985 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4986 D.setInvalidType(); 4987 } 4988 } 4989 4990 if (getLangOpts().OpenCL) { 4991 // Set up the special work-group-local storage class for variables in the 4992 // OpenCL __local address space. 4993 if (R.getAddressSpace() == LangAS::opencl_local) { 4994 SC = SC_OpenCLWorkGroupLocal; 4995 } 4996 4997 // OpenCL v1.2 s6.9.b p4: 4998 // The sampler type cannot be used with the __local and __global address 4999 // space qualifiers. 5000 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5001 R.getAddressSpace() == LangAS::opencl_global)) { 5002 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5003 } 5004 5005 // OpenCL 1.2 spec, p6.9 r: 5006 // The event type cannot be used to declare a program scope variable. 5007 // The event type cannot be used with the __local, __constant and __global 5008 // address space qualifiers. 5009 if (R->isEventT()) { 5010 if (S->getParent() == 0) { 5011 Diag(D.getLocStart(), diag::err_event_t_global_var); 5012 D.setInvalidType(); 5013 } 5014 5015 if (R.getAddressSpace()) { 5016 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5017 D.setInvalidType(); 5018 } 5019 } 5020 } 5021 5022 bool IsExplicitSpecialization = false; 5023 bool IsVariableTemplateSpecialization = false; 5024 bool IsPartialSpecialization = false; 5025 bool IsVariableTemplate = false; 5026 VarTemplateDecl *PrevVarTemplate = 0; 5027 VarDecl *NewVD = 0; 5028 VarTemplateDecl *NewTemplate = 0; 5029 if (!getLangOpts().CPlusPlus) { 5030 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5031 D.getIdentifierLoc(), II, 5032 R, TInfo, SC); 5033 5034 if (D.isInvalidType()) 5035 NewVD->setInvalidDecl(); 5036 } else { 5037 bool Invalid = false; 5038 5039 if (DC->isRecord() && !CurContext->isRecord()) { 5040 // This is an out-of-line definition of a static data member. 5041 switch (SC) { 5042 case SC_None: 5043 break; 5044 case SC_Static: 5045 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5046 diag::err_static_out_of_line) 5047 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5048 break; 5049 case SC_Auto: 5050 case SC_Register: 5051 case SC_Extern: 5052 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5053 // to names of variables declared in a block or to function parameters. 5054 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5055 // of class members 5056 5057 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5058 diag::err_storage_class_for_static_member) 5059 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5060 break; 5061 case SC_PrivateExtern: 5062 llvm_unreachable("C storage class in c++!"); 5063 case SC_OpenCLWorkGroupLocal: 5064 llvm_unreachable("OpenCL storage class in c++!"); 5065 } 5066 } 5067 5068 if (SC == SC_Static && CurContext->isRecord()) { 5069 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5070 if (RD->isLocalClass()) 5071 Diag(D.getIdentifierLoc(), 5072 diag::err_static_data_member_not_allowed_in_local_class) 5073 << Name << RD->getDeclName(); 5074 5075 // C++98 [class.union]p1: If a union contains a static data member, 5076 // the program is ill-formed. C++11 drops this restriction. 5077 if (RD->isUnion()) 5078 Diag(D.getIdentifierLoc(), 5079 getLangOpts().CPlusPlus11 5080 ? diag::warn_cxx98_compat_static_data_member_in_union 5081 : diag::ext_static_data_member_in_union) << Name; 5082 // We conservatively disallow static data members in anonymous structs. 5083 else if (!RD->getDeclName()) 5084 Diag(D.getIdentifierLoc(), 5085 diag::err_static_data_member_not_allowed_in_anon_struct) 5086 << Name << RD->isUnion(); 5087 } 5088 } 5089 5090 NamedDecl *PrevDecl = 0; 5091 if (Previous.begin() != Previous.end()) 5092 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5093 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl); 5094 5095 // Match up the template parameter lists with the scope specifier, then 5096 // determine whether we have a template or a template specialization. 5097 TemplateParameterList *TemplateParams = 5098 MatchTemplateParametersToScopeSpecifier( 5099 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5100 D.getCXXScopeSpec(), TemplateParamLists, 5101 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5102 if (TemplateParams) { 5103 if (!TemplateParams->size() && 5104 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5105 // There is an extraneous 'template<>' for this variable. Complain 5106 // about it, but allow the declaration of the variable. 5107 Diag(TemplateParams->getTemplateLoc(), 5108 diag::err_template_variable_noparams) 5109 << II 5110 << SourceRange(TemplateParams->getTemplateLoc(), 5111 TemplateParams->getRAngleLoc()); 5112 } else { 5113 // Only C++1y supports variable templates (N3651). 5114 Diag(D.getIdentifierLoc(), 5115 getLangOpts().CPlusPlus1y 5116 ? diag::warn_cxx11_compat_variable_template 5117 : diag::ext_variable_template); 5118 5119 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5120 // This is an explicit specialization or a partial specialization. 5121 // Check that we can declare a specialization here 5122 5123 IsVariableTemplateSpecialization = true; 5124 IsPartialSpecialization = TemplateParams->size() > 0; 5125 5126 } else { // if (TemplateParams->size() > 0) 5127 // This is a template declaration. 5128 IsVariableTemplate = true; 5129 5130 // Check that we can declare a template here. 5131 if (CheckTemplateDeclScope(S, TemplateParams)) 5132 return 0; 5133 5134 // If there is a previous declaration with the same name, check 5135 // whether this is a valid redeclaration. 5136 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S)) 5137 PrevDecl = PrevVarTemplate = 0; 5138 5139 if (PrevVarTemplate) { 5140 // Ensure that the template parameter lists are compatible. 5141 if (!TemplateParameterListsAreEqual( 5142 TemplateParams, PrevVarTemplate->getTemplateParameters(), 5143 /*Complain=*/true, TPL_TemplateMatch)) 5144 return 0; 5145 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 5146 // Maybe we will complain about the shadowed template parameter. 5147 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5148 5149 // Just pretend that we didn't see the previous declaration. 5150 PrevDecl = 0; 5151 } else if (PrevDecl) { 5152 // C++ [temp]p5: 5153 // ... a template name declared in namespace scope or in class 5154 // scope shall be unique in that scope. 5155 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind) 5156 << Name; 5157 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5158 return 0; 5159 } 5160 5161 // Check the template parameter list of this declaration, possibly 5162 // merging in the template parameter list from the previous variable 5163 // template declaration. 5164 if (CheckTemplateParameterList( 5165 TemplateParams, 5166 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5167 : 0, 5168 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5169 DC->isDependentContext()) 5170 ? TPC_ClassTemplateMember 5171 : TPC_VarTemplate)) 5172 Invalid = true; 5173 5174 if (D.getCXXScopeSpec().isSet()) { 5175 // If the name of the template was qualified, we must be defining 5176 // the template out-of-line. 5177 if (!D.getCXXScopeSpec().isInvalid() && !Invalid && 5178 !PrevVarTemplate) { 5179 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match) 5180 << Name << DC << /*IsDefinition*/true 5181 << D.getCXXScopeSpec().getRange(); 5182 Invalid = true; 5183 } 5184 } 5185 } 5186 } 5187 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5188 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5189 5190 // We have encountered something that the user meant to be a 5191 // specialization (because it has explicitly-specified template 5192 // arguments) but that was not introduced with a "template<>" (or had 5193 // too few of them). 5194 // FIXME: Differentiate between attempts for explicit instantiations 5195 // (starting with "template") and the rest. 5196 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5197 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5198 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5199 "template<> "); 5200 IsVariableTemplateSpecialization = true; 5201 } 5202 5203 if (IsVariableTemplateSpecialization) { 5204 if (!PrevVarTemplate) { 5205 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 5206 << IsPartialSpecialization; 5207 return 0; 5208 } 5209 5210 SourceLocation TemplateKWLoc = 5211 TemplateParamLists.size() > 0 5212 ? TemplateParamLists[0]->getTemplateLoc() 5213 : SourceLocation(); 5214 DeclResult Res = ActOnVarTemplateSpecialization( 5215 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5216 IsPartialSpecialization); 5217 if (Res.isInvalid()) 5218 return 0; 5219 NewVD = cast<VarDecl>(Res.get()); 5220 AddToScope = false; 5221 } else 5222 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5223 D.getIdentifierLoc(), II, R, TInfo, SC); 5224 5225 // If this is supposed to be a variable template, create it as such. 5226 if (IsVariableTemplate) { 5227 NewTemplate = 5228 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5229 TemplateParams, NewVD, PrevVarTemplate); 5230 NewVD->setDescribedVarTemplate(NewTemplate); 5231 } 5232 5233 // If this decl has an auto type in need of deduction, make a note of the 5234 // Decl so we can diagnose uses of it in its own initializer. 5235 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5236 ParsingInitForAutoVars.insert(NewVD); 5237 5238 if (D.isInvalidType() || Invalid) { 5239 NewVD->setInvalidDecl(); 5240 if (NewTemplate) 5241 NewTemplate->setInvalidDecl(); 5242 } 5243 5244 SetNestedNameSpecifier(NewVD, D); 5245 5246 // FIXME: Do we need D.getCXXScopeSpec().isSet()? 5247 if (TemplateParams && TemplateParamLists.size() > 1 && 5248 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) { 5249 NewVD->setTemplateParameterListsInfo( 5250 Context, TemplateParamLists.size() - 1, TemplateParamLists.data()); 5251 } else if (IsVariableTemplateSpecialization || 5252 (!TemplateParams && TemplateParamLists.size() > 0 && 5253 (D.getCXXScopeSpec().isSet()))) { 5254 NewVD->setTemplateParameterListsInfo(Context, 5255 TemplateParamLists.size(), 5256 TemplateParamLists.data()); 5257 } 5258 5259 if (D.getDeclSpec().isConstexprSpecified()) 5260 NewVD->setConstexpr(true); 5261 } 5262 5263 // Set the lexical context. If the declarator has a C++ scope specifier, the 5264 // lexical context will be different from the semantic context. 5265 NewVD->setLexicalDeclContext(CurContext); 5266 if (NewTemplate) 5267 NewTemplate->setLexicalDeclContext(CurContext); 5268 5269 if (IsLocalExternDecl) 5270 NewVD->setLocalExternDecl(); 5271 5272 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5273 if (NewVD->hasLocalStorage()) { 5274 // C++11 [dcl.stc]p4: 5275 // When thread_local is applied to a variable of block scope the 5276 // storage-class-specifier static is implied if it does not appear 5277 // explicitly. 5278 // Core issue: 'static' is not implied if the variable is declared 5279 // 'extern'. 5280 if (SCSpec == DeclSpec::SCS_unspecified && 5281 TSCS == DeclSpec::TSCS_thread_local && 5282 DC->isFunctionOrMethod()) 5283 NewVD->setTSCSpec(TSCS); 5284 else 5285 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5286 diag::err_thread_non_global) 5287 << DeclSpec::getSpecifierName(TSCS); 5288 } else if (!Context.getTargetInfo().isTLSSupported()) 5289 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5290 diag::err_thread_unsupported); 5291 else 5292 NewVD->setTSCSpec(TSCS); 5293 } 5294 5295 // C99 6.7.4p3 5296 // An inline definition of a function with external linkage shall 5297 // not contain a definition of a modifiable object with static or 5298 // thread storage duration... 5299 // We only apply this when the function is required to be defined 5300 // elsewhere, i.e. when the function is not 'extern inline'. Note 5301 // that a local variable with thread storage duration still has to 5302 // be marked 'static'. Also note that it's possible to get these 5303 // semantics in C++ using __attribute__((gnu_inline)). 5304 if (SC == SC_Static && S->getFnParent() != 0 && 5305 !NewVD->getType().isConstQualified()) { 5306 FunctionDecl *CurFD = getCurFunctionDecl(); 5307 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5308 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5309 diag::warn_static_local_in_extern_inline); 5310 MaybeSuggestAddingStaticToDecl(CurFD); 5311 } 5312 } 5313 5314 if (D.getDeclSpec().isModulePrivateSpecified()) { 5315 if (IsVariableTemplateSpecialization) 5316 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5317 << (IsPartialSpecialization ? 1 : 0) 5318 << FixItHint::CreateRemoval( 5319 D.getDeclSpec().getModulePrivateSpecLoc()); 5320 else if (IsExplicitSpecialization) 5321 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5322 << 2 5323 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5324 else if (NewVD->hasLocalStorage()) 5325 Diag(NewVD->getLocation(), diag::err_module_private_local) 5326 << 0 << NewVD->getDeclName() 5327 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5328 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5329 else { 5330 NewVD->setModulePrivate(); 5331 if (NewTemplate) 5332 NewTemplate->setModulePrivate(); 5333 } 5334 } 5335 5336 // Handle attributes prior to checking for duplicates in MergeVarDecl 5337 ProcessDeclAttributes(S, NewVD, D); 5338 5339 if (NewVD->hasAttrs()) 5340 CheckAlignasUnderalignment(NewVD); 5341 5342 if (getLangOpts().CUDA) { 5343 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5344 // storage [duration]." 5345 if (SC == SC_None && S->getFnParent() != 0 && 5346 (NewVD->hasAttr<CUDASharedAttr>() || 5347 NewVD->hasAttr<CUDAConstantAttr>())) { 5348 NewVD->setStorageClass(SC_Static); 5349 } 5350 } 5351 5352 // In auto-retain/release, infer strong retension for variables of 5353 // retainable type. 5354 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5355 NewVD->setInvalidDecl(); 5356 5357 // Handle GNU asm-label extension (encoded as an attribute). 5358 if (Expr *E = (Expr*)D.getAsmLabel()) { 5359 // The parser guarantees this is a string. 5360 StringLiteral *SE = cast<StringLiteral>(E); 5361 StringRef Label = SE->getString(); 5362 if (S->getFnParent() != 0) { 5363 switch (SC) { 5364 case SC_None: 5365 case SC_Auto: 5366 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5367 break; 5368 case SC_Register: 5369 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5370 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5371 break; 5372 case SC_Static: 5373 case SC_Extern: 5374 case SC_PrivateExtern: 5375 case SC_OpenCLWorkGroupLocal: 5376 break; 5377 } 5378 } 5379 5380 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5381 Context, Label)); 5382 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5383 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5384 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5385 if (I != ExtnameUndeclaredIdentifiers.end()) { 5386 NewVD->addAttr(I->second); 5387 ExtnameUndeclaredIdentifiers.erase(I); 5388 } 5389 } 5390 5391 // Diagnose shadowed variables before filtering for scope. 5392 if (!D.getCXXScopeSpec().isSet()) 5393 CheckShadow(S, NewVD, Previous); 5394 5395 // Don't consider existing declarations that are in a different 5396 // scope and are out-of-semantic-context declarations (if the new 5397 // declaration has linkage). 5398 FilterLookupForScope( 5399 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5400 IsExplicitSpecialization || IsVariableTemplateSpecialization); 5401 5402 // Check whether the previous declaration is in the same block scope. This 5403 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5404 if (getLangOpts().CPlusPlus && 5405 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5406 NewVD->setPreviousDeclInSameBlockScope( 5407 Previous.isSingleResult() && !Previous.isShadowed() && 5408 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5409 5410 if (!getLangOpts().CPlusPlus) { 5411 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5412 } else { 5413 // Merge the decl with the existing one if appropriate. 5414 if (!Previous.empty()) { 5415 if (Previous.isSingleResult() && 5416 isa<FieldDecl>(Previous.getFoundDecl()) && 5417 D.getCXXScopeSpec().isSet()) { 5418 // The user tried to define a non-static data member 5419 // out-of-line (C++ [dcl.meaning]p1). 5420 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5421 << D.getCXXScopeSpec().getRange(); 5422 Previous.clear(); 5423 NewVD->setInvalidDecl(); 5424 } 5425 } else if (D.getCXXScopeSpec().isSet()) { 5426 // No previous declaration in the qualifying scope. 5427 Diag(D.getIdentifierLoc(), diag::err_no_member) 5428 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5429 << D.getCXXScopeSpec().getRange(); 5430 NewVD->setInvalidDecl(); 5431 } 5432 5433 if (!IsVariableTemplateSpecialization) { 5434 if (PrevVarTemplate) { 5435 LookupResult PrevDecl(*this, GetNameForDeclarator(D), 5436 LookupOrdinaryName, ForRedeclaration); 5437 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl()); 5438 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl)); 5439 } else 5440 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5441 } 5442 5443 // This is an explicit specialization of a static data member. Check it. 5444 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5445 CheckMemberSpecialization(NewVD, Previous)) 5446 NewVD->setInvalidDecl(); 5447 } 5448 5449 ProcessPragmaWeak(S, NewVD); 5450 checkAttributesAfterMerging(*this, *NewVD); 5451 5452 // If this is the first declaration of an extern C variable, update 5453 // the map of such variables. 5454 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5455 isIncompleteDeclExternC(*this, NewVD)) 5456 RegisterLocallyScopedExternCDecl(NewVD, S); 5457 5458 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5459 Decl *ManglingContextDecl; 5460 if (MangleNumberingContext *MCtx = 5461 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5462 ManglingContextDecl)) { 5463 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5464 } 5465 } 5466 5467 // If we are providing an explicit specialization of a static variable 5468 // template, make a note of that. 5469 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5470 PrevVarTemplate->setMemberSpecialization(); 5471 5472 if (NewTemplate) { 5473 ActOnDocumentableDecl(NewTemplate); 5474 return NewTemplate; 5475 } 5476 5477 return NewVD; 5478} 5479 5480/// \brief Diagnose variable or built-in function shadowing. Implements 5481/// -Wshadow. 5482/// 5483/// This method is called whenever a VarDecl is added to a "useful" 5484/// scope. 5485/// 5486/// \param S the scope in which the shadowing name is being declared 5487/// \param R the lookup of the name 5488/// 5489void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5490 // Return if warning is ignored. 5491 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5492 DiagnosticsEngine::Ignored) 5493 return; 5494 5495 // Don't diagnose declarations at file scope. 5496 if (D->hasGlobalStorage()) 5497 return; 5498 5499 DeclContext *NewDC = D->getDeclContext(); 5500 5501 // Only diagnose if we're shadowing an unambiguous field or variable. 5502 if (R.getResultKind() != LookupResult::Found) 5503 return; 5504 5505 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5506 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5507 return; 5508 5509 // Fields are not shadowed by variables in C++ static methods. 5510 if (isa<FieldDecl>(ShadowedDecl)) 5511 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5512 if (MD->isStatic()) 5513 return; 5514 5515 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5516 if (shadowedVar->isExternC()) { 5517 // For shadowing external vars, make sure that we point to the global 5518 // declaration, not a locally scoped extern declaration. 5519 for (VarDecl::redecl_iterator 5520 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5521 I != E; ++I) 5522 if (I->isFileVarDecl()) { 5523 ShadowedDecl = *I; 5524 break; 5525 } 5526 } 5527 5528 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5529 5530 // Only warn about certain kinds of shadowing for class members. 5531 if (NewDC && NewDC->isRecord()) { 5532 // In particular, don't warn about shadowing non-class members. 5533 if (!OldDC->isRecord()) 5534 return; 5535 5536 // TODO: should we warn about static data members shadowing 5537 // static data members from base classes? 5538 5539 // TODO: don't diagnose for inaccessible shadowed members. 5540 // This is hard to do perfectly because we might friend the 5541 // shadowing context, but that's just a false negative. 5542 } 5543 5544 // Determine what kind of declaration we're shadowing. 5545 unsigned Kind; 5546 if (isa<RecordDecl>(OldDC)) { 5547 if (isa<FieldDecl>(ShadowedDecl)) 5548 Kind = 3; // field 5549 else 5550 Kind = 2; // static data member 5551 } else if (OldDC->isFileContext()) 5552 Kind = 1; // global 5553 else 5554 Kind = 0; // local 5555 5556 DeclarationName Name = R.getLookupName(); 5557 5558 // Emit warning and note. 5559 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5560 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5561} 5562 5563/// \brief Check -Wshadow without the advantage of a previous lookup. 5564void Sema::CheckShadow(Scope *S, VarDecl *D) { 5565 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5566 DiagnosticsEngine::Ignored) 5567 return; 5568 5569 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5570 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5571 LookupName(R, S); 5572 CheckShadow(S, D, R); 5573} 5574 5575/// Check for conflict between this global or extern "C" declaration and 5576/// previous global or extern "C" declarations. This is only used in C++. 5577template<typename T> 5578static bool checkGlobalOrExternCConflict( 5579 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5580 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5581 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5582 5583 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5584 // The common case: this global doesn't conflict with any extern "C" 5585 // declaration. 5586 return false; 5587 } 5588 5589 if (Prev) { 5590 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5591 // Both the old and new declarations have C language linkage. This is a 5592 // redeclaration. 5593 Previous.clear(); 5594 Previous.addDecl(Prev); 5595 return true; 5596 } 5597 5598 // This is a global, non-extern "C" declaration, and there is a previous 5599 // non-global extern "C" declaration. Diagnose if this is a variable 5600 // declaration. 5601 if (!isa<VarDecl>(ND)) 5602 return false; 5603 } else { 5604 // The declaration is extern "C". Check for any declaration in the 5605 // translation unit which might conflict. 5606 if (IsGlobal) { 5607 // We have already performed the lookup into the translation unit. 5608 IsGlobal = false; 5609 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5610 I != E; ++I) { 5611 if (isa<VarDecl>(*I)) { 5612 Prev = *I; 5613 break; 5614 } 5615 } 5616 } else { 5617 DeclContext::lookup_result R = 5618 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5619 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5620 I != E; ++I) { 5621 if (isa<VarDecl>(*I)) { 5622 Prev = *I; 5623 break; 5624 } 5625 // FIXME: If we have any other entity with this name in global scope, 5626 // the declaration is ill-formed, but that is a defect: it breaks the 5627 // 'stat' hack, for instance. Only variables can have mangled name 5628 // clashes with extern "C" declarations, so only they deserve a 5629 // diagnostic. 5630 } 5631 } 5632 5633 if (!Prev) 5634 return false; 5635 } 5636 5637 // Use the first declaration's location to ensure we point at something which 5638 // is lexically inside an extern "C" linkage-spec. 5639 assert(Prev && "should have found a previous declaration to diagnose"); 5640 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5641 Prev = FD->getFirstDecl(); 5642 else 5643 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5644 5645 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5646 << IsGlobal << ND; 5647 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5648 << IsGlobal; 5649 return false; 5650} 5651 5652/// Apply special rules for handling extern "C" declarations. Returns \c true 5653/// if we have found that this is a redeclaration of some prior entity. 5654/// 5655/// Per C++ [dcl.link]p6: 5656/// Two declarations [for a function or variable] with C language linkage 5657/// with the same name that appear in different scopes refer to the same 5658/// [entity]. An entity with C language linkage shall not be declared with 5659/// the same name as an entity in global scope. 5660template<typename T> 5661static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5662 LookupResult &Previous) { 5663 if (!S.getLangOpts().CPlusPlus) { 5664 // In C, when declaring a global variable, look for a corresponding 'extern' 5665 // variable declared in function scope. We don't need this in C++, because 5666 // we find local extern decls in the surrounding file-scope DeclContext. 5667 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5668 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5669 Previous.clear(); 5670 Previous.addDecl(Prev); 5671 return true; 5672 } 5673 } 5674 return false; 5675 } 5676 5677 // A declaration in the translation unit can conflict with an extern "C" 5678 // declaration. 5679 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5680 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5681 5682 // An extern "C" declaration can conflict with a declaration in the 5683 // translation unit or can be a redeclaration of an extern "C" declaration 5684 // in another scope. 5685 if (isIncompleteDeclExternC(S,ND)) 5686 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5687 5688 // Neither global nor extern "C": nothing to do. 5689 return false; 5690} 5691 5692void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5693 // If the decl is already known invalid, don't check it. 5694 if (NewVD->isInvalidDecl()) 5695 return; 5696 5697 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5698 QualType T = TInfo->getType(); 5699 5700 // Defer checking an 'auto' type until its initializer is attached. 5701 if (T->isUndeducedType()) 5702 return; 5703 5704 if (T->isObjCObjectType()) { 5705 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5706 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5707 T = Context.getObjCObjectPointerType(T); 5708 NewVD->setType(T); 5709 } 5710 5711 // Emit an error if an address space was applied to decl with local storage. 5712 // This includes arrays of objects with address space qualifiers, but not 5713 // automatic variables that point to other address spaces. 5714 // ISO/IEC TR 18037 S5.1.2 5715 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5716 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5717 NewVD->setInvalidDecl(); 5718 return; 5719 } 5720 5721 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5722 // __constant address space. 5723 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5724 && T.getAddressSpace() != LangAS::opencl_constant 5725 && !T->isSamplerT()){ 5726 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5727 NewVD->setInvalidDecl(); 5728 return; 5729 } 5730 5731 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5732 // scope. 5733 if ((getLangOpts().OpenCLVersion >= 120) 5734 && NewVD->isStaticLocal()) { 5735 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5736 NewVD->setInvalidDecl(); 5737 return; 5738 } 5739 5740 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5741 && !NewVD->hasAttr<BlocksAttr>()) { 5742 if (getLangOpts().getGC() != LangOptions::NonGC) 5743 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5744 else { 5745 assert(!getLangOpts().ObjCAutoRefCount); 5746 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5747 } 5748 } 5749 5750 bool isVM = T->isVariablyModifiedType(); 5751 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5752 NewVD->hasAttr<BlocksAttr>()) 5753 getCurFunction()->setHasBranchProtectedScope(); 5754 5755 if ((isVM && NewVD->hasLinkage()) || 5756 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5757 bool SizeIsNegative; 5758 llvm::APSInt Oversized; 5759 TypeSourceInfo *FixedTInfo = 5760 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5761 SizeIsNegative, Oversized); 5762 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5763 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5764 // FIXME: This won't give the correct result for 5765 // int a[10][n]; 5766 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5767 5768 if (NewVD->isFileVarDecl()) 5769 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5770 << SizeRange; 5771 else if (NewVD->isStaticLocal()) 5772 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5773 << SizeRange; 5774 else 5775 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5776 << SizeRange; 5777 NewVD->setInvalidDecl(); 5778 return; 5779 } 5780 5781 if (FixedTInfo == 0) { 5782 if (NewVD->isFileVarDecl()) 5783 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5784 else 5785 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5786 NewVD->setInvalidDecl(); 5787 return; 5788 } 5789 5790 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5791 NewVD->setType(FixedTInfo->getType()); 5792 NewVD->setTypeSourceInfo(FixedTInfo); 5793 } 5794 5795 if (T->isVoidType()) { 5796 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5797 // of objects and functions. 5798 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5799 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5800 << T; 5801 NewVD->setInvalidDecl(); 5802 return; 5803 } 5804 } 5805 5806 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5807 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5808 NewVD->setInvalidDecl(); 5809 return; 5810 } 5811 5812 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5813 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5814 NewVD->setInvalidDecl(); 5815 return; 5816 } 5817 5818 if (NewVD->isConstexpr() && !T->isDependentType() && 5819 RequireLiteralType(NewVD->getLocation(), T, 5820 diag::err_constexpr_var_non_literal)) { 5821 // Can't perform this check until the type is deduced. 5822 NewVD->setInvalidDecl(); 5823 return; 5824 } 5825} 5826 5827/// \brief Perform semantic checking on a newly-created variable 5828/// declaration. 5829/// 5830/// This routine performs all of the type-checking required for a 5831/// variable declaration once it has been built. It is used both to 5832/// check variables after they have been parsed and their declarators 5833/// have been translated into a declaration, and to check variables 5834/// that have been instantiated from a template. 5835/// 5836/// Sets NewVD->isInvalidDecl() if an error was encountered. 5837/// 5838/// Returns true if the variable declaration is a redeclaration. 5839bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5840 CheckVariableDeclarationType(NewVD); 5841 5842 // If the decl is already known invalid, don't check it. 5843 if (NewVD->isInvalidDecl()) 5844 return false; 5845 5846 // If we did not find anything by this name, look for a non-visible 5847 // extern "C" declaration with the same name. 5848 if (Previous.empty() && 5849 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5850 Previous.setShadowed(); 5851 5852 // Filter out any non-conflicting previous declarations. 5853 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5854 5855 if (!Previous.empty()) { 5856 MergeVarDecl(NewVD, Previous); 5857 return true; 5858 } 5859 return false; 5860} 5861 5862/// \brief Data used with FindOverriddenMethod 5863struct FindOverriddenMethodData { 5864 Sema *S; 5865 CXXMethodDecl *Method; 5866}; 5867 5868/// \brief Member lookup function that determines whether a given C++ 5869/// method overrides a method in a base class, to be used with 5870/// CXXRecordDecl::lookupInBases(). 5871static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5872 CXXBasePath &Path, 5873 void *UserData) { 5874 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5875 5876 FindOverriddenMethodData *Data 5877 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5878 5879 DeclarationName Name = Data->Method->getDeclName(); 5880 5881 // FIXME: Do we care about other names here too? 5882 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5883 // We really want to find the base class destructor here. 5884 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5885 CanQualType CT = Data->S->Context.getCanonicalType(T); 5886 5887 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5888 } 5889 5890 for (Path.Decls = BaseRecord->lookup(Name); 5891 !Path.Decls.empty(); 5892 Path.Decls = Path.Decls.slice(1)) { 5893 NamedDecl *D = Path.Decls.front(); 5894 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5895 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5896 return true; 5897 } 5898 } 5899 5900 return false; 5901} 5902 5903namespace { 5904 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5905} 5906/// \brief Report an error regarding overriding, along with any relevant 5907/// overriden methods. 5908/// 5909/// \param DiagID the primary error to report. 5910/// \param MD the overriding method. 5911/// \param OEK which overrides to include as notes. 5912static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5913 OverrideErrorKind OEK = OEK_All) { 5914 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5915 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5916 E = MD->end_overridden_methods(); 5917 I != E; ++I) { 5918 // This check (& the OEK parameter) could be replaced by a predicate, but 5919 // without lambdas that would be overkill. This is still nicer than writing 5920 // out the diag loop 3 times. 5921 if ((OEK == OEK_All) || 5922 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5923 (OEK == OEK_Deleted && (*I)->isDeleted())) 5924 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5925 } 5926} 5927 5928/// AddOverriddenMethods - See if a method overrides any in the base classes, 5929/// and if so, check that it's a valid override and remember it. 5930bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5931 // Look for virtual methods in base classes that this method might override. 5932 CXXBasePaths Paths; 5933 FindOverriddenMethodData Data; 5934 Data.Method = MD; 5935 Data.S = this; 5936 bool hasDeletedOverridenMethods = false; 5937 bool hasNonDeletedOverridenMethods = false; 5938 bool AddedAny = false; 5939 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5940 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5941 E = Paths.found_decls_end(); I != E; ++I) { 5942 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5943 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5944 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5945 !CheckOverridingFunctionAttributes(MD, OldMD) && 5946 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5947 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5948 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5949 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5950 AddedAny = true; 5951 } 5952 } 5953 } 5954 } 5955 5956 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5957 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5958 } 5959 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5960 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5961 } 5962 5963 return AddedAny; 5964} 5965 5966namespace { 5967 // Struct for holding all of the extra arguments needed by 5968 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5969 struct ActOnFDArgs { 5970 Scope *S; 5971 Declarator &D; 5972 MultiTemplateParamsArg TemplateParamLists; 5973 bool AddToScope; 5974 }; 5975} 5976 5977namespace { 5978 5979// Callback to only accept typo corrections that have a non-zero edit distance. 5980// Also only accept corrections that have the same parent decl. 5981class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5982 public: 5983 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5984 CXXRecordDecl *Parent) 5985 : Context(Context), OriginalFD(TypoFD), 5986 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5987 5988 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5989 if (candidate.getEditDistance() == 0) 5990 return false; 5991 5992 SmallVector<unsigned, 1> MismatchedParams; 5993 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5994 CDeclEnd = candidate.end(); 5995 CDecl != CDeclEnd; ++CDecl) { 5996 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5997 5998 if (FD && !FD->hasBody() && 5999 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6000 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6001 CXXRecordDecl *Parent = MD->getParent(); 6002 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6003 return true; 6004 } else if (!ExpectedParent) { 6005 return true; 6006 } 6007 } 6008 } 6009 6010 return false; 6011 } 6012 6013 private: 6014 ASTContext &Context; 6015 FunctionDecl *OriginalFD; 6016 CXXRecordDecl *ExpectedParent; 6017}; 6018 6019} 6020 6021/// \brief Generate diagnostics for an invalid function redeclaration. 6022/// 6023/// This routine handles generating the diagnostic messages for an invalid 6024/// function redeclaration, including finding possible similar declarations 6025/// or performing typo correction if there are no previous declarations with 6026/// the same name. 6027/// 6028/// Returns a NamedDecl iff typo correction was performed and substituting in 6029/// the new declaration name does not cause new errors. 6030static NamedDecl *DiagnoseInvalidRedeclaration( 6031 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6032 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6033 DeclarationName Name = NewFD->getDeclName(); 6034 DeclContext *NewDC = NewFD->getDeclContext(); 6035 SmallVector<unsigned, 1> MismatchedParams; 6036 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6037 TypoCorrection Correction; 6038 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6039 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6040 : diag::err_member_decl_does_not_match; 6041 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6042 IsLocalFriend ? Sema::LookupLocalFriendName 6043 : Sema::LookupOrdinaryName, 6044 Sema::ForRedeclaration); 6045 6046 NewFD->setInvalidDecl(); 6047 if (IsLocalFriend) 6048 SemaRef.LookupName(Prev, S); 6049 else 6050 SemaRef.LookupQualifiedName(Prev, NewDC); 6051 assert(!Prev.isAmbiguous() && 6052 "Cannot have an ambiguity in previous-declaration lookup"); 6053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6054 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6055 MD ? MD->getParent() : 0); 6056 if (!Prev.empty()) { 6057 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6058 Func != FuncEnd; ++Func) { 6059 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6060 if (FD && 6061 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6062 // Add 1 to the index so that 0 can mean the mismatch didn't 6063 // involve a parameter 6064 unsigned ParamNum = 6065 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6066 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6067 } 6068 } 6069 // If the qualified name lookup yielded nothing, try typo correction 6070 } else if ((Correction = SemaRef.CorrectTypo( 6071 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6072 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6073 IsLocalFriend ? 0 : NewDC))) { 6074 // Set up everything for the call to ActOnFunctionDeclarator 6075 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6076 ExtraArgs.D.getIdentifierLoc()); 6077 Previous.clear(); 6078 Previous.setLookupName(Correction.getCorrection()); 6079 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6080 CDeclEnd = Correction.end(); 6081 CDecl != CDeclEnd; ++CDecl) { 6082 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6083 if (FD && !FD->hasBody() && 6084 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6085 Previous.addDecl(FD); 6086 } 6087 } 6088 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6089 6090 NamedDecl *Result; 6091 // Retry building the function declaration with the new previous 6092 // declarations, and with errors suppressed. 6093 { 6094 // Trap errors. 6095 Sema::SFINAETrap Trap(SemaRef); 6096 6097 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6098 // pieces need to verify the typo-corrected C++ declaration and hopefully 6099 // eliminate the need for the parameter pack ExtraArgs. 6100 Result = SemaRef.ActOnFunctionDeclarator( 6101 ExtraArgs.S, ExtraArgs.D, 6102 Correction.getCorrectionDecl()->getDeclContext(), 6103 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6104 ExtraArgs.AddToScope); 6105 6106 if (Trap.hasErrorOccurred()) 6107 Result = 0; 6108 } 6109 6110 if (Result) { 6111 // Determine which correction we picked. 6112 Decl *Canonical = Result->getCanonicalDecl(); 6113 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6114 I != E; ++I) 6115 if ((*I)->getCanonicalDecl() == Canonical) 6116 Correction.setCorrectionDecl(*I); 6117 6118 SemaRef.diagnoseTypo( 6119 Correction, 6120 SemaRef.PDiag(IsLocalFriend 6121 ? diag::err_no_matching_local_friend_suggest 6122 : diag::err_member_decl_does_not_match_suggest) 6123 << Name << NewDC << IsDefinition); 6124 return Result; 6125 } 6126 6127 // Pretend the typo correction never occurred 6128 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6129 ExtraArgs.D.getIdentifierLoc()); 6130 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6131 Previous.clear(); 6132 Previous.setLookupName(Name); 6133 } 6134 6135 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6136 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6137 6138 bool NewFDisConst = false; 6139 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6140 NewFDisConst = NewMD->isConst(); 6141 6142 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6143 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6144 NearMatch != NearMatchEnd; ++NearMatch) { 6145 FunctionDecl *FD = NearMatch->first; 6146 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6147 bool FDisConst = MD && MD->isConst(); 6148 bool IsMember = MD || !IsLocalFriend; 6149 6150 // FIXME: These notes are poorly worded for the local friend case. 6151 if (unsigned Idx = NearMatch->second) { 6152 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6153 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6154 if (Loc.isInvalid()) Loc = FD->getLocation(); 6155 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6156 : diag::note_local_decl_close_param_match) 6157 << Idx << FDParam->getType() 6158 << NewFD->getParamDecl(Idx - 1)->getType(); 6159 } else if (FDisConst != NewFDisConst) { 6160 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6161 << NewFDisConst << FD->getSourceRange().getEnd(); 6162 } else 6163 SemaRef.Diag(FD->getLocation(), 6164 IsMember ? diag::note_member_def_close_match 6165 : diag::note_local_decl_close_match); 6166 } 6167 return 0; 6168} 6169 6170static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6171 Declarator &D) { 6172 switch (D.getDeclSpec().getStorageClassSpec()) { 6173 default: llvm_unreachable("Unknown storage class!"); 6174 case DeclSpec::SCS_auto: 6175 case DeclSpec::SCS_register: 6176 case DeclSpec::SCS_mutable: 6177 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6178 diag::err_typecheck_sclass_func); 6179 D.setInvalidType(); 6180 break; 6181 case DeclSpec::SCS_unspecified: break; 6182 case DeclSpec::SCS_extern: 6183 if (D.getDeclSpec().isExternInLinkageSpec()) 6184 return SC_None; 6185 return SC_Extern; 6186 case DeclSpec::SCS_static: { 6187 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6188 // C99 6.7.1p5: 6189 // The declaration of an identifier for a function that has 6190 // block scope shall have no explicit storage-class specifier 6191 // other than extern 6192 // See also (C++ [dcl.stc]p4). 6193 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6194 diag::err_static_block_func); 6195 break; 6196 } else 6197 return SC_Static; 6198 } 6199 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6200 } 6201 6202 // No explicit storage class has already been returned 6203 return SC_None; 6204} 6205 6206static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6207 DeclContext *DC, QualType &R, 6208 TypeSourceInfo *TInfo, 6209 FunctionDecl::StorageClass SC, 6210 bool &IsVirtualOkay) { 6211 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6212 DeclarationName Name = NameInfo.getName(); 6213 6214 FunctionDecl *NewFD = 0; 6215 bool isInline = D.getDeclSpec().isInlineSpecified(); 6216 6217 if (!SemaRef.getLangOpts().CPlusPlus) { 6218 // Determine whether the function was written with a 6219 // prototype. This true when: 6220 // - there is a prototype in the declarator, or 6221 // - the type R of the function is some kind of typedef or other reference 6222 // to a type name (which eventually refers to a function type). 6223 bool HasPrototype = 6224 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6225 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6226 6227 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6228 D.getLocStart(), NameInfo, R, 6229 TInfo, SC, isInline, 6230 HasPrototype, false); 6231 if (D.isInvalidType()) 6232 NewFD->setInvalidDecl(); 6233 6234 // Set the lexical context. 6235 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6236 6237 return NewFD; 6238 } 6239 6240 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6241 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6242 6243 // Check that the return type is not an abstract class type. 6244 // For record types, this is done by the AbstractClassUsageDiagnoser once 6245 // the class has been completely parsed. 6246 if (!DC->isRecord() && 6247 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 6248 R->getAs<FunctionType>()->getResultType(), 6249 diag::err_abstract_type_in_decl, 6250 SemaRef.AbstractReturnType)) 6251 D.setInvalidType(); 6252 6253 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6254 // This is a C++ constructor declaration. 6255 assert(DC->isRecord() && 6256 "Constructors can only be declared in a member context"); 6257 6258 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6259 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6260 D.getLocStart(), NameInfo, 6261 R, TInfo, isExplicit, isInline, 6262 /*isImplicitlyDeclared=*/false, 6263 isConstexpr); 6264 6265 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6266 // This is a C++ destructor declaration. 6267 if (DC->isRecord()) { 6268 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6269 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6270 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6271 SemaRef.Context, Record, 6272 D.getLocStart(), 6273 NameInfo, R, TInfo, isInline, 6274 /*isImplicitlyDeclared=*/false); 6275 6276 // If the class is complete, then we now create the implicit exception 6277 // specification. If the class is incomplete or dependent, we can't do 6278 // it yet. 6279 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6280 Record->getDefinition() && !Record->isBeingDefined() && 6281 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6282 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6283 } 6284 6285 // The Microsoft ABI requires that we perform the destructor body 6286 // checks (i.e. operator delete() lookup) at every declaration, as 6287 // any translation unit may need to emit a deleting destructor. 6288 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6289 !Record->isDependentType() && Record->getDefinition() && 6290 !Record->isBeingDefined()) { 6291 SemaRef.CheckDestructor(NewDD); 6292 } 6293 6294 IsVirtualOkay = true; 6295 return NewDD; 6296 6297 } else { 6298 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6299 D.setInvalidType(); 6300 6301 // Create a FunctionDecl to satisfy the function definition parsing 6302 // code path. 6303 return FunctionDecl::Create(SemaRef.Context, DC, 6304 D.getLocStart(), 6305 D.getIdentifierLoc(), Name, R, TInfo, 6306 SC, isInline, 6307 /*hasPrototype=*/true, isConstexpr); 6308 } 6309 6310 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6311 if (!DC->isRecord()) { 6312 SemaRef.Diag(D.getIdentifierLoc(), 6313 diag::err_conv_function_not_member); 6314 return 0; 6315 } 6316 6317 SemaRef.CheckConversionDeclarator(D, R, SC); 6318 IsVirtualOkay = true; 6319 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6320 D.getLocStart(), NameInfo, 6321 R, TInfo, isInline, isExplicit, 6322 isConstexpr, SourceLocation()); 6323 6324 } else if (DC->isRecord()) { 6325 // If the name of the function is the same as the name of the record, 6326 // then this must be an invalid constructor that has a return type. 6327 // (The parser checks for a return type and makes the declarator a 6328 // constructor if it has no return type). 6329 if (Name.getAsIdentifierInfo() && 6330 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6331 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6332 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6333 << SourceRange(D.getIdentifierLoc()); 6334 return 0; 6335 } 6336 6337 // This is a C++ method declaration. 6338 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6339 cast<CXXRecordDecl>(DC), 6340 D.getLocStart(), NameInfo, R, 6341 TInfo, SC, isInline, 6342 isConstexpr, SourceLocation()); 6343 IsVirtualOkay = !Ret->isStatic(); 6344 return Ret; 6345 } else { 6346 // Determine whether the function was written with a 6347 // prototype. This true when: 6348 // - we're in C++ (where every function has a prototype), 6349 return FunctionDecl::Create(SemaRef.Context, DC, 6350 D.getLocStart(), 6351 NameInfo, R, TInfo, SC, isInline, 6352 true/*HasPrototype*/, isConstexpr); 6353 } 6354} 6355 6356void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6357 // In C++, the empty parameter-type-list must be spelled "void"; a 6358 // typedef of void is not permitted. 6359 if (getLangOpts().CPlusPlus && 6360 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6361 bool IsTypeAlias = false; 6362 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6363 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6364 else if (const TemplateSpecializationType *TST = 6365 Param->getType()->getAs<TemplateSpecializationType>()) 6366 IsTypeAlias = TST->isTypeAlias(); 6367 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6368 << IsTypeAlias; 6369 } 6370} 6371 6372enum OpenCLParamType { 6373 ValidKernelParam, 6374 PtrPtrKernelParam, 6375 PtrKernelParam, 6376 InvalidKernelParam, 6377 RecordKernelParam 6378}; 6379 6380static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6381 if (PT->isPointerType()) { 6382 QualType PointeeType = PT->getPointeeType(); 6383 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6384 } 6385 6386 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6387 // be used as builtin types. 6388 6389 if (PT->isImageType()) 6390 return PtrKernelParam; 6391 6392 if (PT->isBooleanType()) 6393 return InvalidKernelParam; 6394 6395 if (PT->isEventT()) 6396 return InvalidKernelParam; 6397 6398 if (PT->isHalfType()) 6399 return InvalidKernelParam; 6400 6401 if (PT->isRecordType()) 6402 return RecordKernelParam; 6403 6404 return ValidKernelParam; 6405} 6406 6407static void checkIsValidOpenCLKernelParameter( 6408 Sema &S, 6409 Declarator &D, 6410 ParmVarDecl *Param, 6411 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6412 QualType PT = Param->getType(); 6413 6414 // Cache the valid types we encounter to avoid rechecking structs that are 6415 // used again 6416 if (ValidTypes.count(PT.getTypePtr())) 6417 return; 6418 6419 switch (getOpenCLKernelParameterType(PT)) { 6420 case PtrPtrKernelParam: 6421 // OpenCL v1.2 s6.9.a: 6422 // A kernel function argument cannot be declared as a 6423 // pointer to a pointer type. 6424 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6425 D.setInvalidType(); 6426 return; 6427 6428 // OpenCL v1.2 s6.9.k: 6429 // Arguments to kernel functions in a program cannot be declared with the 6430 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6431 // uintptr_t or a struct and/or union that contain fields declared to be 6432 // one of these built-in scalar types. 6433 6434 case InvalidKernelParam: 6435 // OpenCL v1.2 s6.8 n: 6436 // A kernel function argument cannot be declared 6437 // of event_t type. 6438 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6439 D.setInvalidType(); 6440 return; 6441 6442 case PtrKernelParam: 6443 case ValidKernelParam: 6444 ValidTypes.insert(PT.getTypePtr()); 6445 return; 6446 6447 case RecordKernelParam: 6448 break; 6449 } 6450 6451 // Track nested structs we will inspect 6452 SmallVector<const Decl *, 4> VisitStack; 6453 6454 // Track where we are in the nested structs. Items will migrate from 6455 // VisitStack to HistoryStack as we do the DFS for bad field. 6456 SmallVector<const FieldDecl *, 4> HistoryStack; 6457 HistoryStack.push_back((const FieldDecl *) 0); 6458 6459 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6460 VisitStack.push_back(PD); 6461 6462 assert(VisitStack.back() && "First decl null?"); 6463 6464 do { 6465 const Decl *Next = VisitStack.pop_back_val(); 6466 if (!Next) { 6467 assert(!HistoryStack.empty()); 6468 // Found a marker, we have gone up a level 6469 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6470 ValidTypes.insert(Hist->getType().getTypePtr()); 6471 6472 continue; 6473 } 6474 6475 // Adds everything except the original parameter declaration (which is not a 6476 // field itself) to the history stack. 6477 const RecordDecl *RD; 6478 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6479 HistoryStack.push_back(Field); 6480 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6481 } else { 6482 RD = cast<RecordDecl>(Next); 6483 } 6484 6485 // Add a null marker so we know when we've gone back up a level 6486 VisitStack.push_back((const Decl *) 0); 6487 6488 for (RecordDecl::field_iterator I = RD->field_begin(), 6489 E = RD->field_end(); I != E; ++I) { 6490 const FieldDecl *FD = *I; 6491 QualType QT = FD->getType(); 6492 6493 if (ValidTypes.count(QT.getTypePtr())) 6494 continue; 6495 6496 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6497 if (ParamType == ValidKernelParam) 6498 continue; 6499 6500 if (ParamType == RecordKernelParam) { 6501 VisitStack.push_back(FD); 6502 continue; 6503 } 6504 6505 // OpenCL v1.2 s6.9.p: 6506 // Arguments to kernel functions that are declared to be a struct or union 6507 // do not allow OpenCL objects to be passed as elements of the struct or 6508 // union. 6509 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6510 S.Diag(Param->getLocation(), 6511 diag::err_record_with_pointers_kernel_param) 6512 << PT->isUnionType() 6513 << PT; 6514 } else { 6515 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6516 } 6517 6518 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6519 << PD->getDeclName(); 6520 6521 // We have an error, now let's go back up through history and show where 6522 // the offending field came from 6523 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6524 E = HistoryStack.end(); I != E; ++I) { 6525 const FieldDecl *OuterField = *I; 6526 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6527 << OuterField->getType(); 6528 } 6529 6530 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6531 << QT->isPointerType() 6532 << QT; 6533 D.setInvalidType(); 6534 return; 6535 } 6536 } while (!VisitStack.empty()); 6537} 6538 6539NamedDecl* 6540Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6541 TypeSourceInfo *TInfo, LookupResult &Previous, 6542 MultiTemplateParamsArg TemplateParamLists, 6543 bool &AddToScope) { 6544 QualType R = TInfo->getType(); 6545 6546 assert(R.getTypePtr()->isFunctionType()); 6547 6548 // TODO: consider using NameInfo for diagnostic. 6549 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6550 DeclarationName Name = NameInfo.getName(); 6551 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6552 6553 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6554 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6555 diag::err_invalid_thread) 6556 << DeclSpec::getSpecifierName(TSCS); 6557 6558 if (D.isFirstDeclarationOfMember()) 6559 adjustMemberFunctionCC(R, D.isStaticMember()); 6560 6561 bool isFriend = false; 6562 FunctionTemplateDecl *FunctionTemplate = 0; 6563 bool isExplicitSpecialization = false; 6564 bool isFunctionTemplateSpecialization = false; 6565 6566 bool isDependentClassScopeExplicitSpecialization = false; 6567 bool HasExplicitTemplateArgs = false; 6568 TemplateArgumentListInfo TemplateArgs; 6569 6570 bool isVirtualOkay = false; 6571 6572 DeclContext *OriginalDC = DC; 6573 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6574 6575 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6576 isVirtualOkay); 6577 if (!NewFD) return 0; 6578 6579 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6580 NewFD->setTopLevelDeclInObjCContainer(); 6581 6582 // Set the lexical context. If this is a function-scope declaration, or has a 6583 // C++ scope specifier, or is the object of a friend declaration, the lexical 6584 // context will be different from the semantic context. 6585 NewFD->setLexicalDeclContext(CurContext); 6586 6587 if (IsLocalExternDecl) 6588 NewFD->setLocalExternDecl(); 6589 6590 if (getLangOpts().CPlusPlus) { 6591 bool isInline = D.getDeclSpec().isInlineSpecified(); 6592 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6593 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6594 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6595 isFriend = D.getDeclSpec().isFriendSpecified(); 6596 if (isFriend && !isInline && D.isFunctionDefinition()) { 6597 // C++ [class.friend]p5 6598 // A function can be defined in a friend declaration of a 6599 // class . . . . Such a function is implicitly inline. 6600 NewFD->setImplicitlyInline(); 6601 } 6602 6603 // If this is a method defined in an __interface, and is not a constructor 6604 // or an overloaded operator, then set the pure flag (isVirtual will already 6605 // return true). 6606 if (const CXXRecordDecl *Parent = 6607 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6608 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6609 NewFD->setPure(true); 6610 } 6611 6612 SetNestedNameSpecifier(NewFD, D); 6613 isExplicitSpecialization = false; 6614 isFunctionTemplateSpecialization = false; 6615 if (D.isInvalidType()) 6616 NewFD->setInvalidDecl(); 6617 6618 // Match up the template parameter lists with the scope specifier, then 6619 // determine whether we have a template or a template specialization. 6620 bool Invalid = false; 6621 if (TemplateParameterList *TemplateParams = 6622 MatchTemplateParametersToScopeSpecifier( 6623 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6624 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6625 isExplicitSpecialization, Invalid)) { 6626 if (TemplateParams->size() > 0) { 6627 // This is a function template 6628 6629 // Check that we can declare a template here. 6630 if (CheckTemplateDeclScope(S, TemplateParams)) 6631 return 0; 6632 6633 // A destructor cannot be a template. 6634 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6635 Diag(NewFD->getLocation(), diag::err_destructor_template); 6636 return 0; 6637 } 6638 6639 // If we're adding a template to a dependent context, we may need to 6640 // rebuilding some of the types used within the template parameter list, 6641 // now that we know what the current instantiation is. 6642 if (DC->isDependentContext()) { 6643 ContextRAII SavedContext(*this, DC); 6644 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6645 Invalid = true; 6646 } 6647 6648 6649 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6650 NewFD->getLocation(), 6651 Name, TemplateParams, 6652 NewFD); 6653 FunctionTemplate->setLexicalDeclContext(CurContext); 6654 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6655 6656 // For source fidelity, store the other template param lists. 6657 if (TemplateParamLists.size() > 1) { 6658 NewFD->setTemplateParameterListsInfo(Context, 6659 TemplateParamLists.size() - 1, 6660 TemplateParamLists.data()); 6661 } 6662 } else { 6663 // This is a function template specialization. 6664 isFunctionTemplateSpecialization = true; 6665 // For source fidelity, store all the template param lists. 6666 NewFD->setTemplateParameterListsInfo(Context, 6667 TemplateParamLists.size(), 6668 TemplateParamLists.data()); 6669 6670 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6671 if (isFriend) { 6672 // We want to remove the "template<>", found here. 6673 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6674 6675 // If we remove the template<> and the name is not a 6676 // template-id, we're actually silently creating a problem: 6677 // the friend declaration will refer to an untemplated decl, 6678 // and clearly the user wants a template specialization. So 6679 // we need to insert '<>' after the name. 6680 SourceLocation InsertLoc; 6681 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6682 InsertLoc = D.getName().getSourceRange().getEnd(); 6683 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6684 } 6685 6686 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6687 << Name << RemoveRange 6688 << FixItHint::CreateRemoval(RemoveRange) 6689 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6690 } 6691 } 6692 } 6693 else { 6694 // All template param lists were matched against the scope specifier: 6695 // this is NOT (an explicit specialization of) a template. 6696 if (TemplateParamLists.size() > 0) 6697 // For source fidelity, store all the template param lists. 6698 NewFD->setTemplateParameterListsInfo(Context, 6699 TemplateParamLists.size(), 6700 TemplateParamLists.data()); 6701 } 6702 6703 if (Invalid) { 6704 NewFD->setInvalidDecl(); 6705 if (FunctionTemplate) 6706 FunctionTemplate->setInvalidDecl(); 6707 } 6708 6709 // C++ [dcl.fct.spec]p5: 6710 // The virtual specifier shall only be used in declarations of 6711 // nonstatic class member functions that appear within a 6712 // member-specification of a class declaration; see 10.3. 6713 // 6714 if (isVirtual && !NewFD->isInvalidDecl()) { 6715 if (!isVirtualOkay) { 6716 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6717 diag::err_virtual_non_function); 6718 } else if (!CurContext->isRecord()) { 6719 // 'virtual' was specified outside of the class. 6720 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6721 diag::err_virtual_out_of_class) 6722 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6723 } else if (NewFD->getDescribedFunctionTemplate()) { 6724 // C++ [temp.mem]p3: 6725 // A member function template shall not be virtual. 6726 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6727 diag::err_virtual_member_function_template) 6728 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6729 } else { 6730 // Okay: Add virtual to the method. 6731 NewFD->setVirtualAsWritten(true); 6732 } 6733 6734 if (getLangOpts().CPlusPlus1y && 6735 NewFD->getResultType()->isUndeducedType()) 6736 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6737 } 6738 6739 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() && 6740 NewFD->getResultType()->isUndeducedType()) { 6741 // If the function template is referenced directly (for instance, as a 6742 // member of the current instantiation), pretend it has a dependent type. 6743 // This is not really justified by the standard, but is the only sane 6744 // thing to do. 6745 const FunctionProtoType *FPT = 6746 NewFD->getType()->castAs<FunctionProtoType>(); 6747 QualType Result = SubstAutoType(FPT->getResultType(), 6748 Context.DependentTy); 6749 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(), 6750 FPT->getExtProtoInfo())); 6751 } 6752 6753 // C++ [dcl.fct.spec]p3: 6754 // The inline specifier shall not appear on a block scope function 6755 // declaration. 6756 if (isInline && !NewFD->isInvalidDecl()) { 6757 if (CurContext->isFunctionOrMethod()) { 6758 // 'inline' is not allowed on block scope function declaration. 6759 Diag(D.getDeclSpec().getInlineSpecLoc(), 6760 diag::err_inline_declaration_block_scope) << Name 6761 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6762 } 6763 } 6764 6765 // C++ [dcl.fct.spec]p6: 6766 // The explicit specifier shall be used only in the declaration of a 6767 // constructor or conversion function within its class definition; 6768 // see 12.3.1 and 12.3.2. 6769 if (isExplicit && !NewFD->isInvalidDecl()) { 6770 if (!CurContext->isRecord()) { 6771 // 'explicit' was specified outside of the class. 6772 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6773 diag::err_explicit_out_of_class) 6774 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6775 } else if (!isa<CXXConstructorDecl>(NewFD) && 6776 !isa<CXXConversionDecl>(NewFD)) { 6777 // 'explicit' was specified on a function that wasn't a constructor 6778 // or conversion function. 6779 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6780 diag::err_explicit_non_ctor_or_conv_function) 6781 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6782 } 6783 } 6784 6785 if (isConstexpr) { 6786 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6787 // are implicitly inline. 6788 NewFD->setImplicitlyInline(); 6789 6790 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6791 // be either constructors or to return a literal type. Therefore, 6792 // destructors cannot be declared constexpr. 6793 if (isa<CXXDestructorDecl>(NewFD)) 6794 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6795 } 6796 6797 // If __module_private__ was specified, mark the function accordingly. 6798 if (D.getDeclSpec().isModulePrivateSpecified()) { 6799 if (isFunctionTemplateSpecialization) { 6800 SourceLocation ModulePrivateLoc 6801 = D.getDeclSpec().getModulePrivateSpecLoc(); 6802 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6803 << 0 6804 << FixItHint::CreateRemoval(ModulePrivateLoc); 6805 } else { 6806 NewFD->setModulePrivate(); 6807 if (FunctionTemplate) 6808 FunctionTemplate->setModulePrivate(); 6809 } 6810 } 6811 6812 if (isFriend) { 6813 if (FunctionTemplate) { 6814 FunctionTemplate->setObjectOfFriendDecl(); 6815 FunctionTemplate->setAccess(AS_public); 6816 } 6817 NewFD->setObjectOfFriendDecl(); 6818 NewFD->setAccess(AS_public); 6819 } 6820 6821 // If a function is defined as defaulted or deleted, mark it as such now. 6822 switch (D.getFunctionDefinitionKind()) { 6823 case FDK_Declaration: 6824 case FDK_Definition: 6825 break; 6826 6827 case FDK_Defaulted: 6828 NewFD->setDefaulted(); 6829 break; 6830 6831 case FDK_Deleted: 6832 NewFD->setDeletedAsWritten(); 6833 break; 6834 } 6835 6836 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6837 D.isFunctionDefinition()) { 6838 // C++ [class.mfct]p2: 6839 // A member function may be defined (8.4) in its class definition, in 6840 // which case it is an inline member function (7.1.2) 6841 NewFD->setImplicitlyInline(); 6842 } 6843 6844 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6845 !CurContext->isRecord()) { 6846 // C++ [class.static]p1: 6847 // A data or function member of a class may be declared static 6848 // in a class definition, in which case it is a static member of 6849 // the class. 6850 6851 // Complain about the 'static' specifier if it's on an out-of-line 6852 // member function definition. 6853 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6854 diag::err_static_out_of_line) 6855 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6856 } 6857 6858 // C++11 [except.spec]p15: 6859 // A deallocation function with no exception-specification is treated 6860 // as if it were specified with noexcept(true). 6861 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6862 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6863 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6864 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6865 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6866 EPI.ExceptionSpecType = EST_BasicNoexcept; 6867 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6868 FPT->getArgTypes(), EPI)); 6869 } 6870 6871 // C++11 [replacement.functions]p3: 6872 // The program's definitions shall not be specified as inline. 6873 // 6874 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 6875 if (isInline && NewFD->isReplaceableGlobalAllocationFunction()) 6876 Diag(D.getDeclSpec().getInlineSpecLoc(), 6877 diag::err_operator_new_delete_declared_inline) 6878 << NewFD->getDeclName(); 6879 } 6880 6881 // Filter out previous declarations that don't match the scope. 6882 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6883 isExplicitSpecialization || 6884 isFunctionTemplateSpecialization); 6885 6886 // Handle GNU asm-label extension (encoded as an attribute). 6887 if (Expr *E = (Expr*) D.getAsmLabel()) { 6888 // The parser guarantees this is a string. 6889 StringLiteral *SE = cast<StringLiteral>(E); 6890 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6891 SE->getString())); 6892 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6893 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6894 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6895 if (I != ExtnameUndeclaredIdentifiers.end()) { 6896 NewFD->addAttr(I->second); 6897 ExtnameUndeclaredIdentifiers.erase(I); 6898 } 6899 } 6900 6901 // Copy the parameter declarations from the declarator D to the function 6902 // declaration NewFD, if they are available. First scavenge them into Params. 6903 SmallVector<ParmVarDecl*, 16> Params; 6904 if (D.isFunctionDeclarator()) { 6905 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6906 6907 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6908 // function that takes no arguments, not a function that takes a 6909 // single void argument. 6910 // We let through "const void" here because Sema::GetTypeForDeclarator 6911 // already checks for that case. 6912 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6913 FTI.ArgInfo[0].Param && 6914 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6915 // Empty arg list, don't push any params. 6916 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6917 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6918 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6919 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6920 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6921 Param->setDeclContext(NewFD); 6922 Params.push_back(Param); 6923 6924 if (Param->isInvalidDecl()) 6925 NewFD->setInvalidDecl(); 6926 } 6927 } 6928 6929 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6930 // When we're declaring a function with a typedef, typeof, etc as in the 6931 // following example, we'll need to synthesize (unnamed) 6932 // parameters for use in the declaration. 6933 // 6934 // @code 6935 // typedef void fn(int); 6936 // fn f; 6937 // @endcode 6938 6939 // Synthesize a parameter for each argument type. 6940 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6941 AE = FT->arg_type_end(); AI != AE; ++AI) { 6942 ParmVarDecl *Param = 6943 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6944 Param->setScopeInfo(0, Params.size()); 6945 Params.push_back(Param); 6946 } 6947 } else { 6948 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6949 "Should not need args for typedef of non-prototype fn"); 6950 } 6951 6952 // Finally, we know we have the right number of parameters, install them. 6953 NewFD->setParams(Params); 6954 6955 // Find all anonymous symbols defined during the declaration of this function 6956 // and add to NewFD. This lets us track decls such 'enum Y' in: 6957 // 6958 // void f(enum Y {AA} x) {} 6959 // 6960 // which would otherwise incorrectly end up in the translation unit scope. 6961 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6962 DeclsInPrototypeScope.clear(); 6963 6964 if (D.getDeclSpec().isNoreturnSpecified()) 6965 NewFD->addAttr( 6966 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6967 Context)); 6968 6969 // Functions returning a variably modified type violate C99 6.7.5.2p2 6970 // because all functions have linkage. 6971 if (!NewFD->isInvalidDecl() && 6972 NewFD->getResultType()->isVariablyModifiedType()) { 6973 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6974 NewFD->setInvalidDecl(); 6975 } 6976 6977 // Handle attributes. 6978 ProcessDeclAttributes(S, NewFD, D); 6979 6980 QualType RetType = NewFD->getResultType(); 6981 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6982 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6983 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6984 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6985 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6986 // Attach the attribute to the new decl. Don't apply the attribute if it 6987 // returns an instance of the class (e.g. assignment operators). 6988 if (!MD || MD->getParent() != Ret) { 6989 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6990 Context)); 6991 } 6992 } 6993 6994 if (!getLangOpts().CPlusPlus) { 6995 // Perform semantic checking on the function declaration. 6996 bool isExplicitSpecialization=false; 6997 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 6998 CheckMain(NewFD, D.getDeclSpec()); 6999 7000 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7001 CheckMSVCRTEntryPoint(NewFD); 7002 7003 if (!NewFD->isInvalidDecl()) 7004 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7005 isExplicitSpecialization)); 7006 else if (!Previous.empty()) 7007 // Make graceful recovery from an invalid redeclaration. 7008 D.setRedeclaration(true); 7009 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7010 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7011 "previous declaration set still overloaded"); 7012 } else { 7013 // If the declarator is a template-id, translate the parser's template 7014 // argument list into our AST format. 7015 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7016 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7017 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7018 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7019 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7020 TemplateId->NumArgs); 7021 translateTemplateArguments(TemplateArgsPtr, 7022 TemplateArgs); 7023 7024 HasExplicitTemplateArgs = true; 7025 7026 if (NewFD->isInvalidDecl()) { 7027 HasExplicitTemplateArgs = false; 7028 } else if (FunctionTemplate) { 7029 // Function template with explicit template arguments. 7030 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7031 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7032 7033 HasExplicitTemplateArgs = false; 7034 } else if (!isFunctionTemplateSpecialization && 7035 !D.getDeclSpec().isFriendSpecified()) { 7036 // We have encountered something that the user meant to be a 7037 // specialization (because it has explicitly-specified template 7038 // arguments) but that was not introduced with a "template<>" (or had 7039 // too few of them). 7040 // FIXME: Differentiate between attempts for explicit instantiations 7041 // (starting with "template") and the rest. 7042 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7043 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7044 << FixItHint::CreateInsertion( 7045 D.getDeclSpec().getLocStart(), 7046 "template<> "); 7047 isFunctionTemplateSpecialization = true; 7048 } else { 7049 // "friend void foo<>(int);" is an implicit specialization decl. 7050 isFunctionTemplateSpecialization = true; 7051 } 7052 } else if (isFriend && isFunctionTemplateSpecialization) { 7053 // This combination is only possible in a recovery case; the user 7054 // wrote something like: 7055 // template <> friend void foo(int); 7056 // which we're recovering from as if the user had written: 7057 // friend void foo<>(int); 7058 // Go ahead and fake up a template id. 7059 HasExplicitTemplateArgs = true; 7060 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7061 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7062 } 7063 7064 // If it's a friend (and only if it's a friend), it's possible 7065 // that either the specialized function type or the specialized 7066 // template is dependent, and therefore matching will fail. In 7067 // this case, don't check the specialization yet. 7068 bool InstantiationDependent = false; 7069 if (isFunctionTemplateSpecialization && isFriend && 7070 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7071 TemplateSpecializationType::anyDependentTemplateArguments( 7072 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7073 InstantiationDependent))) { 7074 assert(HasExplicitTemplateArgs && 7075 "friend function specialization without template args"); 7076 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7077 Previous)) 7078 NewFD->setInvalidDecl(); 7079 } else if (isFunctionTemplateSpecialization) { 7080 if (CurContext->isDependentContext() && CurContext->isRecord() 7081 && !isFriend) { 7082 isDependentClassScopeExplicitSpecialization = true; 7083 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7084 diag::ext_function_specialization_in_class : 7085 diag::err_function_specialization_in_class) 7086 << NewFD->getDeclName(); 7087 } else if (CheckFunctionTemplateSpecialization(NewFD, 7088 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7089 Previous)) 7090 NewFD->setInvalidDecl(); 7091 7092 // C++ [dcl.stc]p1: 7093 // A storage-class-specifier shall not be specified in an explicit 7094 // specialization (14.7.3) 7095 FunctionTemplateSpecializationInfo *Info = 7096 NewFD->getTemplateSpecializationInfo(); 7097 if (Info && SC != SC_None) { 7098 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7099 Diag(NewFD->getLocation(), 7100 diag::err_explicit_specialization_inconsistent_storage_class) 7101 << SC 7102 << FixItHint::CreateRemoval( 7103 D.getDeclSpec().getStorageClassSpecLoc()); 7104 7105 else 7106 Diag(NewFD->getLocation(), 7107 diag::ext_explicit_specialization_storage_class) 7108 << FixItHint::CreateRemoval( 7109 D.getDeclSpec().getStorageClassSpecLoc()); 7110 } 7111 7112 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7113 if (CheckMemberSpecialization(NewFD, Previous)) 7114 NewFD->setInvalidDecl(); 7115 } 7116 7117 // Perform semantic checking on the function declaration. 7118 if (!isDependentClassScopeExplicitSpecialization) { 7119 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7120 CheckMain(NewFD, D.getDeclSpec()); 7121 7122 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7123 CheckMSVCRTEntryPoint(NewFD); 7124 7125 if (NewFD->isInvalidDecl()) { 7126 // If this is a class member, mark the class invalid immediately. 7127 // This avoids some consistency errors later. 7128 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 7129 methodDecl->getParent()->setInvalidDecl(); 7130 } else 7131 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7132 isExplicitSpecialization)); 7133 } 7134 7135 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7136 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7137 "previous declaration set still overloaded"); 7138 7139 NamedDecl *PrincipalDecl = (FunctionTemplate 7140 ? cast<NamedDecl>(FunctionTemplate) 7141 : NewFD); 7142 7143 if (isFriend && D.isRedeclaration()) { 7144 AccessSpecifier Access = AS_public; 7145 if (!NewFD->isInvalidDecl()) 7146 Access = NewFD->getPreviousDecl()->getAccess(); 7147 7148 NewFD->setAccess(Access); 7149 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7150 } 7151 7152 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7153 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7154 PrincipalDecl->setNonMemberOperator(); 7155 7156 // If we have a function template, check the template parameter 7157 // list. This will check and merge default template arguments. 7158 if (FunctionTemplate) { 7159 FunctionTemplateDecl *PrevTemplate = 7160 FunctionTemplate->getPreviousDecl(); 7161 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7162 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7163 D.getDeclSpec().isFriendSpecified() 7164 ? (D.isFunctionDefinition() 7165 ? TPC_FriendFunctionTemplateDefinition 7166 : TPC_FriendFunctionTemplate) 7167 : (D.getCXXScopeSpec().isSet() && 7168 DC && DC->isRecord() && 7169 DC->isDependentContext()) 7170 ? TPC_ClassTemplateMember 7171 : TPC_FunctionTemplate); 7172 } 7173 7174 if (NewFD->isInvalidDecl()) { 7175 // Ignore all the rest of this. 7176 } else if (!D.isRedeclaration()) { 7177 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7178 AddToScope }; 7179 // Fake up an access specifier if it's supposed to be a class member. 7180 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7181 NewFD->setAccess(AS_public); 7182 7183 // Qualified decls generally require a previous declaration. 7184 if (D.getCXXScopeSpec().isSet()) { 7185 // ...with the major exception of templated-scope or 7186 // dependent-scope friend declarations. 7187 7188 // TODO: we currently also suppress this check in dependent 7189 // contexts because (1) the parameter depth will be off when 7190 // matching friend templates and (2) we might actually be 7191 // selecting a friend based on a dependent factor. But there 7192 // are situations where these conditions don't apply and we 7193 // can actually do this check immediately. 7194 if (isFriend && 7195 (TemplateParamLists.size() || 7196 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7197 CurContext->isDependentContext())) { 7198 // ignore these 7199 } else { 7200 // The user tried to provide an out-of-line definition for a 7201 // function that is a member of a class or namespace, but there 7202 // was no such member function declared (C++ [class.mfct]p2, 7203 // C++ [namespace.memdef]p2). For example: 7204 // 7205 // class X { 7206 // void f() const; 7207 // }; 7208 // 7209 // void X::f() { } // ill-formed 7210 // 7211 // Complain about this problem, and attempt to suggest close 7212 // matches (e.g., those that differ only in cv-qualifiers and 7213 // whether the parameter types are references). 7214 7215 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7216 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7217 AddToScope = ExtraArgs.AddToScope; 7218 return Result; 7219 } 7220 } 7221 7222 // Unqualified local friend declarations are required to resolve 7223 // to something. 7224 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7225 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7226 *this, Previous, NewFD, ExtraArgs, true, S)) { 7227 AddToScope = ExtraArgs.AddToScope; 7228 return Result; 7229 } 7230 } 7231 7232 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 7233 !isFriend && !isFunctionTemplateSpecialization && 7234 !isExplicitSpecialization) { 7235 // An out-of-line member function declaration must also be a 7236 // definition (C++ [dcl.meaning]p1). 7237 // Note that this is not the case for explicit specializations of 7238 // function templates or member functions of class templates, per 7239 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7240 // extension for compatibility with old SWIG code which likes to 7241 // generate them. 7242 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7243 << D.getCXXScopeSpec().getRange(); 7244 } 7245 } 7246 7247 ProcessPragmaWeak(S, NewFD); 7248 checkAttributesAfterMerging(*this, *NewFD); 7249 7250 AddKnownFunctionAttributes(NewFD); 7251 7252 if (NewFD->hasAttr<OverloadableAttr>() && 7253 !NewFD->getType()->getAs<FunctionProtoType>()) { 7254 Diag(NewFD->getLocation(), 7255 diag::err_attribute_overloadable_no_prototype) 7256 << NewFD; 7257 7258 // Turn this into a variadic function with no parameters. 7259 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7260 FunctionProtoType::ExtProtoInfo EPI( 7261 Context.getDefaultCallingConvention(true, false)); 7262 EPI.Variadic = true; 7263 EPI.ExtInfo = FT->getExtInfo(); 7264 7265 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI); 7266 NewFD->setType(R); 7267 } 7268 7269 // If there's a #pragma GCC visibility in scope, and this isn't a class 7270 // member, set the visibility of this function. 7271 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7272 AddPushedVisibilityAttribute(NewFD); 7273 7274 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7275 // marking the function. 7276 AddCFAuditedAttribute(NewFD); 7277 7278 // If this is the first declaration of an extern C variable, update 7279 // the map of such variables. 7280 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7281 isIncompleteDeclExternC(*this, NewFD)) 7282 RegisterLocallyScopedExternCDecl(NewFD, S); 7283 7284 // Set this FunctionDecl's range up to the right paren. 7285 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7286 7287 if (getLangOpts().CPlusPlus) { 7288 if (FunctionTemplate) { 7289 if (NewFD->isInvalidDecl()) 7290 FunctionTemplate->setInvalidDecl(); 7291 return FunctionTemplate; 7292 } 7293 } 7294 7295 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7296 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7297 if ((getLangOpts().OpenCLVersion >= 120) 7298 && (SC == SC_Static)) { 7299 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7300 D.setInvalidType(); 7301 } 7302 7303 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7304 if (!NewFD->getResultType()->isVoidType()) { 7305 Diag(D.getIdentifierLoc(), 7306 diag::err_expected_kernel_void_return_type); 7307 D.setInvalidType(); 7308 } 7309 7310 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7311 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7312 PE = NewFD->param_end(); PI != PE; ++PI) { 7313 ParmVarDecl *Param = *PI; 7314 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7315 } 7316 } 7317 7318 MarkUnusedFileScopedDecl(NewFD); 7319 7320 if (getLangOpts().CUDA) 7321 if (IdentifierInfo *II = NewFD->getIdentifier()) 7322 if (!NewFD->isInvalidDecl() && 7323 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7324 if (II->isStr("cudaConfigureCall")) { 7325 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 7326 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7327 7328 Context.setcudaConfigureCallDecl(NewFD); 7329 } 7330 } 7331 7332 // Here we have an function template explicit specialization at class scope. 7333 // The actually specialization will be postponed to template instatiation 7334 // time via the ClassScopeFunctionSpecializationDecl node. 7335 if (isDependentClassScopeExplicitSpecialization) { 7336 ClassScopeFunctionSpecializationDecl *NewSpec = 7337 ClassScopeFunctionSpecializationDecl::Create( 7338 Context, CurContext, SourceLocation(), 7339 cast<CXXMethodDecl>(NewFD), 7340 HasExplicitTemplateArgs, TemplateArgs); 7341 CurContext->addDecl(NewSpec); 7342 AddToScope = false; 7343 } 7344 7345 return NewFD; 7346} 7347 7348/// \brief Perform semantic checking of a new function declaration. 7349/// 7350/// Performs semantic analysis of the new function declaration 7351/// NewFD. This routine performs all semantic checking that does not 7352/// require the actual declarator involved in the declaration, and is 7353/// used both for the declaration of functions as they are parsed 7354/// (called via ActOnDeclarator) and for the declaration of functions 7355/// that have been instantiated via C++ template instantiation (called 7356/// via InstantiateDecl). 7357/// 7358/// \param IsExplicitSpecialization whether this new function declaration is 7359/// an explicit specialization of the previous declaration. 7360/// 7361/// This sets NewFD->isInvalidDecl() to true if there was an error. 7362/// 7363/// \returns true if the function declaration is a redeclaration. 7364bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7365 LookupResult &Previous, 7366 bool IsExplicitSpecialization) { 7367 assert(!NewFD->getResultType()->isVariablyModifiedType() 7368 && "Variably modified return types are not handled here"); 7369 7370 // Determine whether the type of this function should be merged with 7371 // a previous visible declaration. This never happens for functions in C++, 7372 // and always happens in C if the previous declaration was visible. 7373 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7374 !Previous.isShadowed(); 7375 7376 // Filter out any non-conflicting previous declarations. 7377 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7378 7379 bool Redeclaration = false; 7380 NamedDecl *OldDecl = 0; 7381 7382 // Merge or overload the declaration with an existing declaration of 7383 // the same name, if appropriate. 7384 if (!Previous.empty()) { 7385 // Determine whether NewFD is an overload of PrevDecl or 7386 // a declaration that requires merging. If it's an overload, 7387 // there's no more work to do here; we'll just add the new 7388 // function to the scope. 7389 if (!AllowOverloadingOfFunction(Previous, Context)) { 7390 NamedDecl *Candidate = Previous.getFoundDecl(); 7391 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7392 Redeclaration = true; 7393 OldDecl = Candidate; 7394 } 7395 } else { 7396 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7397 /*NewIsUsingDecl*/ false)) { 7398 case Ovl_Match: 7399 Redeclaration = true; 7400 break; 7401 7402 case Ovl_NonFunction: 7403 Redeclaration = true; 7404 break; 7405 7406 case Ovl_Overload: 7407 Redeclaration = false; 7408 break; 7409 } 7410 7411 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7412 // If a function name is overloadable in C, then every function 7413 // with that name must be marked "overloadable". 7414 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7415 << Redeclaration << NewFD; 7416 NamedDecl *OverloadedDecl = 0; 7417 if (Redeclaration) 7418 OverloadedDecl = OldDecl; 7419 else if (!Previous.empty()) 7420 OverloadedDecl = Previous.getRepresentativeDecl(); 7421 if (OverloadedDecl) 7422 Diag(OverloadedDecl->getLocation(), 7423 diag::note_attribute_overloadable_prev_overload); 7424 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7425 Context)); 7426 } 7427 } 7428 } 7429 7430 // Check for a previous extern "C" declaration with this name. 7431 if (!Redeclaration && 7432 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7433 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7434 if (!Previous.empty()) { 7435 // This is an extern "C" declaration with the same name as a previous 7436 // declaration, and thus redeclares that entity... 7437 Redeclaration = true; 7438 OldDecl = Previous.getFoundDecl(); 7439 MergeTypeWithPrevious = false; 7440 7441 // ... except in the presence of __attribute__((overloadable)). 7442 if (OldDecl->hasAttr<OverloadableAttr>()) { 7443 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7444 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7445 << Redeclaration << NewFD; 7446 Diag(Previous.getFoundDecl()->getLocation(), 7447 diag::note_attribute_overloadable_prev_overload); 7448 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7449 Context)); 7450 } 7451 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7452 Redeclaration = false; 7453 OldDecl = 0; 7454 } 7455 } 7456 } 7457 } 7458 7459 // C++11 [dcl.constexpr]p8: 7460 // A constexpr specifier for a non-static member function that is not 7461 // a constructor declares that member function to be const. 7462 // 7463 // This needs to be delayed until we know whether this is an out-of-line 7464 // definition of a static member function. 7465 // 7466 // This rule is not present in C++1y, so we produce a backwards 7467 // compatibility warning whenever it happens in C++11. 7468 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7469 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7470 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7471 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7472 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 7473 if (FunctionTemplateDecl *OldTD = 7474 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 7475 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 7476 if (!OldMD || !OldMD->isStatic()) { 7477 const FunctionProtoType *FPT = 7478 MD->getType()->castAs<FunctionProtoType>(); 7479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7480 EPI.TypeQuals |= Qualifiers::Const; 7481 MD->setType(Context.getFunctionType(FPT->getResultType(), 7482 FPT->getArgTypes(), EPI)); 7483 7484 // Warn that we did this, if we're not performing template instantiation. 7485 // In that case, we'll have warned already when the template was defined. 7486 if (ActiveTemplateInstantiations.empty()) { 7487 SourceLocation AddConstLoc; 7488 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7489 .IgnoreParens().getAs<FunctionTypeLoc>()) 7490 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7491 7492 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7493 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7494 } 7495 } 7496 } 7497 7498 if (Redeclaration) { 7499 // NewFD and OldDecl represent declarations that need to be 7500 // merged. 7501 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7502 NewFD->setInvalidDecl(); 7503 return Redeclaration; 7504 } 7505 7506 Previous.clear(); 7507 Previous.addDecl(OldDecl); 7508 7509 if (FunctionTemplateDecl *OldTemplateDecl 7510 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7511 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7512 FunctionTemplateDecl *NewTemplateDecl 7513 = NewFD->getDescribedFunctionTemplate(); 7514 assert(NewTemplateDecl && "Template/non-template mismatch"); 7515 if (CXXMethodDecl *Method 7516 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7517 Method->setAccess(OldTemplateDecl->getAccess()); 7518 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7519 } 7520 7521 // If this is an explicit specialization of a member that is a function 7522 // template, mark it as a member specialization. 7523 if (IsExplicitSpecialization && 7524 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7525 NewTemplateDecl->setMemberSpecialization(); 7526 assert(OldTemplateDecl->isMemberSpecialization()); 7527 } 7528 7529 } else { 7530 // This needs to happen first so that 'inline' propagates. 7531 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7532 7533 if (isa<CXXMethodDecl>(NewFD)) { 7534 // A valid redeclaration of a C++ method must be out-of-line, 7535 // but (unfortunately) it's not necessarily a definition 7536 // because of templates, which means that the previous 7537 // declaration is not necessarily from the class definition. 7538 7539 // For just setting the access, that doesn't matter. 7540 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7541 NewFD->setAccess(oldMethod->getAccess()); 7542 7543 // Update the key-function state if necessary for this ABI. 7544 if (NewFD->isInlined() && 7545 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7546 // setNonKeyFunction needs to work with the original 7547 // declaration from the class definition, and isVirtual() is 7548 // just faster in that case, so map back to that now. 7549 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7550 if (oldMethod->isVirtual()) { 7551 Context.setNonKeyFunction(oldMethod); 7552 } 7553 } 7554 } 7555 } 7556 } 7557 7558 // Semantic checking for this function declaration (in isolation). 7559 if (getLangOpts().CPlusPlus) { 7560 // C++-specific checks. 7561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7562 CheckConstructor(Constructor); 7563 } else if (CXXDestructorDecl *Destructor = 7564 dyn_cast<CXXDestructorDecl>(NewFD)) { 7565 CXXRecordDecl *Record = Destructor->getParent(); 7566 QualType ClassType = Context.getTypeDeclType(Record); 7567 7568 // FIXME: Shouldn't we be able to perform this check even when the class 7569 // type is dependent? Both gcc and edg can handle that. 7570 if (!ClassType->isDependentType()) { 7571 DeclarationName Name 7572 = Context.DeclarationNames.getCXXDestructorName( 7573 Context.getCanonicalType(ClassType)); 7574 if (NewFD->getDeclName() != Name) { 7575 Diag(NewFD->getLocation(), diag::err_destructor_name); 7576 NewFD->setInvalidDecl(); 7577 return Redeclaration; 7578 } 7579 } 7580 } else if (CXXConversionDecl *Conversion 7581 = dyn_cast<CXXConversionDecl>(NewFD)) { 7582 ActOnConversionDeclarator(Conversion); 7583 } 7584 7585 // Find any virtual functions that this function overrides. 7586 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7587 if (!Method->isFunctionTemplateSpecialization() && 7588 !Method->getDescribedFunctionTemplate() && 7589 Method->isCanonicalDecl()) { 7590 if (AddOverriddenMethods(Method->getParent(), Method)) { 7591 // If the function was marked as "static", we have a problem. 7592 if (NewFD->getStorageClass() == SC_Static) { 7593 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7594 } 7595 } 7596 } 7597 7598 if (Method->isStatic()) 7599 checkThisInStaticMemberFunctionType(Method); 7600 } 7601 7602 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7603 if (NewFD->isOverloadedOperator() && 7604 CheckOverloadedOperatorDeclaration(NewFD)) { 7605 NewFD->setInvalidDecl(); 7606 return Redeclaration; 7607 } 7608 7609 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7610 if (NewFD->getLiteralIdentifier() && 7611 CheckLiteralOperatorDeclaration(NewFD)) { 7612 NewFD->setInvalidDecl(); 7613 return Redeclaration; 7614 } 7615 7616 // In C++, check default arguments now that we have merged decls. Unless 7617 // the lexical context is the class, because in this case this is done 7618 // during delayed parsing anyway. 7619 if (!CurContext->isRecord()) 7620 CheckCXXDefaultArguments(NewFD); 7621 7622 // If this function declares a builtin function, check the type of this 7623 // declaration against the expected type for the builtin. 7624 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7625 ASTContext::GetBuiltinTypeError Error; 7626 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7627 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7628 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7629 // The type of this function differs from the type of the builtin, 7630 // so forget about the builtin entirely. 7631 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7632 } 7633 } 7634 7635 // If this function is declared as being extern "C", then check to see if 7636 // the function returns a UDT (class, struct, or union type) that is not C 7637 // compatible, and if it does, warn the user. 7638 // But, issue any diagnostic on the first declaration only. 7639 if (NewFD->isExternC() && Previous.empty()) { 7640 QualType R = NewFD->getResultType(); 7641 if (R->isIncompleteType() && !R->isVoidType()) 7642 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7643 << NewFD << R; 7644 else if (!R.isPODType(Context) && !R->isVoidType() && 7645 !R->isObjCObjectPointerType()) 7646 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7647 } 7648 } 7649 return Redeclaration; 7650} 7651 7652static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7653 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7654 if (!TSI) 7655 return SourceRange(); 7656 7657 TypeLoc TL = TSI->getTypeLoc(); 7658 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7659 if (!FunctionTL) 7660 return SourceRange(); 7661 7662 TypeLoc ResultTL = FunctionTL.getResultLoc(); 7663 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7664 return ResultTL.getSourceRange(); 7665 7666 return SourceRange(); 7667} 7668 7669void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7670 // C++11 [basic.start.main]p3: A program that declares main to be inline, 7671 // static or constexpr is ill-formed. 7672 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7673 // appear in a declaration of main. 7674 // static main is not an error under C99, but we should warn about it. 7675 // We accept _Noreturn main as an extension. 7676 if (FD->getStorageClass() == SC_Static) 7677 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7678 ? diag::err_static_main : diag::warn_static_main) 7679 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7680 if (FD->isInlineSpecified()) 7681 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7682 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7683 if (DS.isNoreturnSpecified()) { 7684 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7685 SourceRange NoreturnRange(NoreturnLoc, 7686 PP.getLocForEndOfToken(NoreturnLoc)); 7687 Diag(NoreturnLoc, diag::ext_noreturn_main); 7688 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7689 << FixItHint::CreateRemoval(NoreturnRange); 7690 } 7691 if (FD->isConstexpr()) { 7692 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7693 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7694 FD->setConstexpr(false); 7695 } 7696 7697 QualType T = FD->getType(); 7698 assert(T->isFunctionType() && "function decl is not of function type"); 7699 const FunctionType* FT = T->castAs<FunctionType>(); 7700 7701 // All the standards say that main() should should return 'int'. 7702 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 7703 // In C and C++, main magically returns 0 if you fall off the end; 7704 // set the flag which tells us that. 7705 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7706 FD->setHasImplicitReturnZero(true); 7707 7708 // In C with GNU extensions we allow main() to have non-integer return 7709 // type, but we should warn about the extension, and we disable the 7710 // implicit-return-zero rule. 7711 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7712 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7713 7714 SourceRange ResultRange = getResultSourceRange(FD); 7715 if (ResultRange.isValid()) 7716 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7717 << FixItHint::CreateReplacement(ResultRange, "int"); 7718 7719 // Otherwise, this is just a flat-out error. 7720 } else { 7721 SourceRange ResultRange = getResultSourceRange(FD); 7722 if (ResultRange.isValid()) 7723 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7724 << FixItHint::CreateReplacement(ResultRange, "int"); 7725 else 7726 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7727 7728 FD->setInvalidDecl(true); 7729 } 7730 7731 // Treat protoless main() as nullary. 7732 if (isa<FunctionNoProtoType>(FT)) return; 7733 7734 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7735 unsigned nparams = FTP->getNumArgs(); 7736 assert(FD->getNumParams() == nparams); 7737 7738 bool HasExtraParameters = (nparams > 3); 7739 7740 // Darwin passes an undocumented fourth argument of type char**. If 7741 // other platforms start sprouting these, the logic below will start 7742 // getting shifty. 7743 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7744 HasExtraParameters = false; 7745 7746 if (HasExtraParameters) { 7747 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7748 FD->setInvalidDecl(true); 7749 nparams = 3; 7750 } 7751 7752 // FIXME: a lot of the following diagnostics would be improved 7753 // if we had some location information about types. 7754 7755 QualType CharPP = 7756 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7757 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7758 7759 for (unsigned i = 0; i < nparams; ++i) { 7760 QualType AT = FTP->getArgType(i); 7761 7762 bool mismatch = true; 7763 7764 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7765 mismatch = false; 7766 else if (Expected[i] == CharPP) { 7767 // As an extension, the following forms are okay: 7768 // char const ** 7769 // char const * const * 7770 // char * const * 7771 7772 QualifierCollector qs; 7773 const PointerType* PT; 7774 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7775 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7776 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7777 Context.CharTy)) { 7778 qs.removeConst(); 7779 mismatch = !qs.empty(); 7780 } 7781 } 7782 7783 if (mismatch) { 7784 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7785 // TODO: suggest replacing given type with expected type 7786 FD->setInvalidDecl(true); 7787 } 7788 } 7789 7790 if (nparams == 1 && !FD->isInvalidDecl()) { 7791 Diag(FD->getLocation(), diag::warn_main_one_arg); 7792 } 7793 7794 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7795 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7796 FD->setInvalidDecl(); 7797 } 7798} 7799 7800void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7801 QualType T = FD->getType(); 7802 assert(T->isFunctionType() && "function decl is not of function type"); 7803 const FunctionType *FT = T->castAs<FunctionType>(); 7804 7805 // Set an implicit return of 'zero' if the function can return some integral, 7806 // enumeration, pointer or nullptr type. 7807 if (FT->getResultType()->isIntegralOrEnumerationType() || 7808 FT->getResultType()->isAnyPointerType() || 7809 FT->getResultType()->isNullPtrType()) 7810 // DllMain is exempt because a return value of zero means it failed. 7811 if (FD->getName() != "DllMain") 7812 FD->setHasImplicitReturnZero(true); 7813 7814 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7815 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7816 FD->setInvalidDecl(); 7817 } 7818} 7819 7820bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7821 // FIXME: Need strict checking. In C89, we need to check for 7822 // any assignment, increment, decrement, function-calls, or 7823 // commas outside of a sizeof. In C99, it's the same list, 7824 // except that the aforementioned are allowed in unevaluated 7825 // expressions. Everything else falls under the 7826 // "may accept other forms of constant expressions" exception. 7827 // (We never end up here for C++, so the constant expression 7828 // rules there don't matter.) 7829 if (Init->isConstantInitializer(Context, false)) 7830 return false; 7831 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7832 << Init->getSourceRange(); 7833 return true; 7834} 7835 7836namespace { 7837 // Visits an initialization expression to see if OrigDecl is evaluated in 7838 // its own initialization and throws a warning if it does. 7839 class SelfReferenceChecker 7840 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7841 Sema &S; 7842 Decl *OrigDecl; 7843 bool isRecordType; 7844 bool isPODType; 7845 bool isReferenceType; 7846 7847 public: 7848 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7849 7850 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7851 S(S), OrigDecl(OrigDecl) { 7852 isPODType = false; 7853 isRecordType = false; 7854 isReferenceType = false; 7855 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7856 isPODType = VD->getType().isPODType(S.Context); 7857 isRecordType = VD->getType()->isRecordType(); 7858 isReferenceType = VD->getType()->isReferenceType(); 7859 } 7860 } 7861 7862 // For most expressions, the cast is directly above the DeclRefExpr. 7863 // For conditional operators, the cast can be outside the conditional 7864 // operator if both expressions are DeclRefExpr's. 7865 void HandleValue(Expr *E) { 7866 if (isReferenceType) 7867 return; 7868 E = E->IgnoreParenImpCasts(); 7869 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7870 HandleDeclRefExpr(DRE); 7871 return; 7872 } 7873 7874 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7875 HandleValue(CO->getTrueExpr()); 7876 HandleValue(CO->getFalseExpr()); 7877 return; 7878 } 7879 7880 if (isa<MemberExpr>(E)) { 7881 Expr *Base = E->IgnoreParenImpCasts(); 7882 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7883 // Check for static member variables and don't warn on them. 7884 if (!isa<FieldDecl>(ME->getMemberDecl())) 7885 return; 7886 Base = ME->getBase()->IgnoreParenImpCasts(); 7887 } 7888 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7889 HandleDeclRefExpr(DRE); 7890 return; 7891 } 7892 } 7893 7894 // Reference types are handled here since all uses of references are 7895 // bad, not just r-value uses. 7896 void VisitDeclRefExpr(DeclRefExpr *E) { 7897 if (isReferenceType) 7898 HandleDeclRefExpr(E); 7899 } 7900 7901 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7902 if (E->getCastKind() == CK_LValueToRValue || 7903 (isRecordType && E->getCastKind() == CK_NoOp)) 7904 HandleValue(E->getSubExpr()); 7905 7906 Inherited::VisitImplicitCastExpr(E); 7907 } 7908 7909 void VisitMemberExpr(MemberExpr *E) { 7910 // Don't warn on arrays since they can be treated as pointers. 7911 if (E->getType()->canDecayToPointerType()) return; 7912 7913 // Warn when a non-static method call is followed by non-static member 7914 // field accesses, which is followed by a DeclRefExpr. 7915 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7916 bool Warn = (MD && !MD->isStatic()); 7917 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7918 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7919 if (!isa<FieldDecl>(ME->getMemberDecl())) 7920 Warn = false; 7921 Base = ME->getBase()->IgnoreParenImpCasts(); 7922 } 7923 7924 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7925 if (Warn) 7926 HandleDeclRefExpr(DRE); 7927 return; 7928 } 7929 7930 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7931 // Visit that expression. 7932 Visit(Base); 7933 } 7934 7935 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7936 if (E->getNumArgs() > 0) 7937 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7938 HandleDeclRefExpr(DRE); 7939 7940 Inherited::VisitCXXOperatorCallExpr(E); 7941 } 7942 7943 void VisitUnaryOperator(UnaryOperator *E) { 7944 // For POD record types, addresses of its own members are well-defined. 7945 if (E->getOpcode() == UO_AddrOf && isRecordType && 7946 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7947 if (!isPODType) 7948 HandleValue(E->getSubExpr()); 7949 return; 7950 } 7951 Inherited::VisitUnaryOperator(E); 7952 } 7953 7954 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7955 7956 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7957 Decl* ReferenceDecl = DRE->getDecl(); 7958 if (OrigDecl != ReferenceDecl) return; 7959 unsigned diag; 7960 if (isReferenceType) { 7961 diag = diag::warn_uninit_self_reference_in_reference_init; 7962 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7963 diag = diag::warn_static_self_reference_in_init; 7964 } else { 7965 diag = diag::warn_uninit_self_reference_in_init; 7966 } 7967 7968 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7969 S.PDiag(diag) 7970 << DRE->getNameInfo().getName() 7971 << OrigDecl->getLocation() 7972 << DRE->getSourceRange()); 7973 } 7974 }; 7975 7976 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7977 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7978 bool DirectInit) { 7979 // Parameters arguments are occassionially constructed with itself, 7980 // for instance, in recursive functions. Skip them. 7981 if (isa<ParmVarDecl>(OrigDecl)) 7982 return; 7983 7984 E = E->IgnoreParens(); 7985 7986 // Skip checking T a = a where T is not a record or reference type. 7987 // Doing so is a way to silence uninitialized warnings. 7988 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7989 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7990 if (ICE->getCastKind() == CK_LValueToRValue) 7991 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7992 if (DRE->getDecl() == OrigDecl) 7993 return; 7994 7995 SelfReferenceChecker(S, OrigDecl).Visit(E); 7996 } 7997} 7998 7999/// AddInitializerToDecl - Adds the initializer Init to the 8000/// declaration dcl. If DirectInit is true, this is C++ direct 8001/// initialization rather than copy initialization. 8002void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8003 bool DirectInit, bool TypeMayContainAuto) { 8004 // If there is no declaration, there was an error parsing it. Just ignore 8005 // the initializer. 8006 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8007 return; 8008 8009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8010 // With declarators parsed the way they are, the parser cannot 8011 // distinguish between a normal initializer and a pure-specifier. 8012 // Thus this grotesque test. 8013 IntegerLiteral *IL; 8014 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8015 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8016 CheckPureMethod(Method, Init->getSourceRange()); 8017 else { 8018 Diag(Method->getLocation(), diag::err_member_function_initialization) 8019 << Method->getDeclName() << Init->getSourceRange(); 8020 Method->setInvalidDecl(); 8021 } 8022 return; 8023 } 8024 8025 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8026 if (!VDecl) { 8027 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8028 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8029 RealDecl->setInvalidDecl(); 8030 return; 8031 } 8032 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8033 8034 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8035 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8036 Expr *DeduceInit = Init; 8037 // Initializer could be a C++ direct-initializer. Deduction only works if it 8038 // contains exactly one expression. 8039 if (CXXDirectInit) { 8040 if (CXXDirectInit->getNumExprs() == 0) { 8041 // It isn't possible to write this directly, but it is possible to 8042 // end up in this situation with "auto x(some_pack...);" 8043 Diag(CXXDirectInit->getLocStart(), 8044 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8045 : diag::err_auto_var_init_no_expression) 8046 << VDecl->getDeclName() << VDecl->getType() 8047 << VDecl->getSourceRange(); 8048 RealDecl->setInvalidDecl(); 8049 return; 8050 } else if (CXXDirectInit->getNumExprs() > 1) { 8051 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8052 VDecl->isInitCapture() 8053 ? diag::err_init_capture_multiple_expressions 8054 : diag::err_auto_var_init_multiple_expressions) 8055 << VDecl->getDeclName() << VDecl->getType() 8056 << VDecl->getSourceRange(); 8057 RealDecl->setInvalidDecl(); 8058 return; 8059 } else { 8060 DeduceInit = CXXDirectInit->getExpr(0); 8061 } 8062 } 8063 8064 // Expressions default to 'id' when we're in a debugger. 8065 bool DefaultedToAuto = false; 8066 if (getLangOpts().DebuggerCastResultToId && 8067 Init->getType() == Context.UnknownAnyTy) { 8068 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8069 if (Result.isInvalid()) { 8070 VDecl->setInvalidDecl(); 8071 return; 8072 } 8073 Init = Result.take(); 8074 DefaultedToAuto = true; 8075 } 8076 8077 QualType DeducedType; 8078 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8079 DAR_Failed) 8080 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8081 if (DeducedType.isNull()) { 8082 RealDecl->setInvalidDecl(); 8083 return; 8084 } 8085 VDecl->setType(DeducedType); 8086 assert(VDecl->isLinkageValid()); 8087 8088 // In ARC, infer lifetime. 8089 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8090 VDecl->setInvalidDecl(); 8091 8092 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8093 // 'id' instead of a specific object type prevents most of our usual checks. 8094 // We only want to warn outside of template instantiations, though: 8095 // inside a template, the 'id' could have come from a parameter. 8096 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8097 DeducedType->isObjCIdType()) { 8098 SourceLocation Loc = 8099 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8100 Diag(Loc, diag::warn_auto_var_is_id) 8101 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8102 } 8103 8104 // If this is a redeclaration, check that the type we just deduced matches 8105 // the previously declared type. 8106 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8107 // We never need to merge the type, because we cannot form an incomplete 8108 // array of auto, nor deduce such a type. 8109 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8110 } 8111 8112 // Check the deduced type is valid for a variable declaration. 8113 CheckVariableDeclarationType(VDecl); 8114 if (VDecl->isInvalidDecl()) 8115 return; 8116 } 8117 8118 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8119 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8120 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8121 VDecl->setInvalidDecl(); 8122 return; 8123 } 8124 8125 if (!VDecl->getType()->isDependentType()) { 8126 // A definition must end up with a complete type, which means it must be 8127 // complete with the restriction that an array type might be completed by 8128 // the initializer; note that later code assumes this restriction. 8129 QualType BaseDeclType = VDecl->getType(); 8130 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8131 BaseDeclType = Array->getElementType(); 8132 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8133 diag::err_typecheck_decl_incomplete_type)) { 8134 RealDecl->setInvalidDecl(); 8135 return; 8136 } 8137 8138 // The variable can not have an abstract class type. 8139 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8140 diag::err_abstract_type_in_decl, 8141 AbstractVariableType)) 8142 VDecl->setInvalidDecl(); 8143 } 8144 8145 const VarDecl *Def; 8146 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8147 Diag(VDecl->getLocation(), diag::err_redefinition) 8148 << VDecl->getDeclName(); 8149 Diag(Def->getLocation(), diag::note_previous_definition); 8150 VDecl->setInvalidDecl(); 8151 return; 8152 } 8153 8154 const VarDecl* PrevInit = 0; 8155 if (getLangOpts().CPlusPlus) { 8156 // C++ [class.static.data]p4 8157 // If a static data member is of const integral or const 8158 // enumeration type, its declaration in the class definition can 8159 // specify a constant-initializer which shall be an integral 8160 // constant expression (5.19). In that case, the member can appear 8161 // in integral constant expressions. The member shall still be 8162 // defined in a namespace scope if it is used in the program and the 8163 // namespace scope definition shall not contain an initializer. 8164 // 8165 // We already performed a redefinition check above, but for static 8166 // data members we also need to check whether there was an in-class 8167 // declaration with an initializer. 8168 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8169 Diag(VDecl->getLocation(), diag::err_redefinition) 8170 << VDecl->getDeclName(); 8171 Diag(PrevInit->getLocation(), diag::note_previous_definition); 8172 return; 8173 } 8174 8175 if (VDecl->hasLocalStorage()) 8176 getCurFunction()->setHasBranchProtectedScope(); 8177 8178 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8179 VDecl->setInvalidDecl(); 8180 return; 8181 } 8182 } 8183 8184 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8185 // a kernel function cannot be initialized." 8186 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8187 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8188 VDecl->setInvalidDecl(); 8189 return; 8190 } 8191 8192 // Get the decls type and save a reference for later, since 8193 // CheckInitializerTypes may change it. 8194 QualType DclT = VDecl->getType(), SavT = DclT; 8195 8196 // Expressions default to 'id' when we're in a debugger 8197 // and we are assigning it to a variable of Objective-C pointer type. 8198 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8199 Init->getType() == Context.UnknownAnyTy) { 8200 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8201 if (Result.isInvalid()) { 8202 VDecl->setInvalidDecl(); 8203 return; 8204 } 8205 Init = Result.take(); 8206 } 8207 8208 // Perform the initialization. 8209 if (!VDecl->isInvalidDecl()) { 8210 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8211 InitializationKind Kind 8212 = DirectInit ? 8213 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8214 Init->getLocStart(), 8215 Init->getLocEnd()) 8216 : InitializationKind::CreateDirectList( 8217 VDecl->getLocation()) 8218 : InitializationKind::CreateCopy(VDecl->getLocation(), 8219 Init->getLocStart()); 8220 8221 MultiExprArg Args = Init; 8222 if (CXXDirectInit) 8223 Args = MultiExprArg(CXXDirectInit->getExprs(), 8224 CXXDirectInit->getNumExprs()); 8225 8226 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8227 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8228 if (Result.isInvalid()) { 8229 VDecl->setInvalidDecl(); 8230 return; 8231 } 8232 8233 Init = Result.takeAs<Expr>(); 8234 } 8235 8236 // Check for self-references within variable initializers. 8237 // Variables declared within a function/method body (except for references) 8238 // are handled by a dataflow analysis. 8239 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8240 VDecl->getType()->isReferenceType()) { 8241 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8242 } 8243 8244 // If the type changed, it means we had an incomplete type that was 8245 // completed by the initializer. For example: 8246 // int ary[] = { 1, 3, 5 }; 8247 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8248 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8249 VDecl->setType(DclT); 8250 8251 if (!VDecl->isInvalidDecl()) { 8252 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8253 8254 if (VDecl->hasAttr<BlocksAttr>()) 8255 checkRetainCycles(VDecl, Init); 8256 8257 // It is safe to assign a weak reference into a strong variable. 8258 // Although this code can still have problems: 8259 // id x = self.weakProp; 8260 // id y = self.weakProp; 8261 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8262 // paths through the function. This should be revisited if 8263 // -Wrepeated-use-of-weak is made flow-sensitive. 8264 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8265 DiagnosticsEngine::Level Level = 8266 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8267 Init->getLocStart()); 8268 if (Level != DiagnosticsEngine::Ignored) 8269 getCurFunction()->markSafeWeakUse(Init); 8270 } 8271 } 8272 8273 // The initialization is usually a full-expression. 8274 // 8275 // FIXME: If this is a braced initialization of an aggregate, it is not 8276 // an expression, and each individual field initializer is a separate 8277 // full-expression. For instance, in: 8278 // 8279 // struct Temp { ~Temp(); }; 8280 // struct S { S(Temp); }; 8281 // struct T { S a, b; } t = { Temp(), Temp() } 8282 // 8283 // we should destroy the first Temp before constructing the second. 8284 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8285 false, 8286 VDecl->isConstexpr()); 8287 if (Result.isInvalid()) { 8288 VDecl->setInvalidDecl(); 8289 return; 8290 } 8291 Init = Result.take(); 8292 8293 // Attach the initializer to the decl. 8294 VDecl->setInit(Init); 8295 8296 if (VDecl->isLocalVarDecl()) { 8297 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8298 // static storage duration shall be constant expressions or string literals. 8299 // C++ does not have this restriction. 8300 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8301 if (VDecl->getStorageClass() == SC_Static) 8302 CheckForConstantInitializer(Init, DclT); 8303 // C89 is stricter than C99 for non-static aggregate types. 8304 // C89 6.5.7p3: All the expressions [...] in an initializer list 8305 // for an object that has aggregate or union type shall be 8306 // constant expressions. 8307 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8308 isa<InitListExpr>(Init) && 8309 !Init->isConstantInitializer(Context, false)) 8310 Diag(Init->getExprLoc(), 8311 diag::ext_aggregate_init_not_constant) 8312 << Init->getSourceRange(); 8313 } 8314 } else if (VDecl->isStaticDataMember() && 8315 VDecl->getLexicalDeclContext()->isRecord()) { 8316 // This is an in-class initialization for a static data member, e.g., 8317 // 8318 // struct S { 8319 // static const int value = 17; 8320 // }; 8321 8322 // C++ [class.mem]p4: 8323 // A member-declarator can contain a constant-initializer only 8324 // if it declares a static member (9.4) of const integral or 8325 // const enumeration type, see 9.4.2. 8326 // 8327 // C++11 [class.static.data]p3: 8328 // If a non-volatile const static data member is of integral or 8329 // enumeration type, its declaration in the class definition can 8330 // specify a brace-or-equal-initializer in which every initalizer-clause 8331 // that is an assignment-expression is a constant expression. A static 8332 // data member of literal type can be declared in the class definition 8333 // with the constexpr specifier; if so, its declaration shall specify a 8334 // brace-or-equal-initializer in which every initializer-clause that is 8335 // an assignment-expression is a constant expression. 8336 8337 // Do nothing on dependent types. 8338 if (DclT->isDependentType()) { 8339 8340 // Allow any 'static constexpr' members, whether or not they are of literal 8341 // type. We separately check that every constexpr variable is of literal 8342 // type. 8343 } else if (VDecl->isConstexpr()) { 8344 8345 // Require constness. 8346 } else if (!DclT.isConstQualified()) { 8347 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8348 << Init->getSourceRange(); 8349 VDecl->setInvalidDecl(); 8350 8351 // We allow integer constant expressions in all cases. 8352 } else if (DclT->isIntegralOrEnumerationType()) { 8353 // Check whether the expression is a constant expression. 8354 SourceLocation Loc; 8355 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8356 // In C++11, a non-constexpr const static data member with an 8357 // in-class initializer cannot be volatile. 8358 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8359 else if (Init->isValueDependent()) 8360 ; // Nothing to check. 8361 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8362 ; // Ok, it's an ICE! 8363 else if (Init->isEvaluatable(Context)) { 8364 // If we can constant fold the initializer through heroics, accept it, 8365 // but report this as a use of an extension for -pedantic. 8366 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8367 << Init->getSourceRange(); 8368 } else { 8369 // Otherwise, this is some crazy unknown case. Report the issue at the 8370 // location provided by the isIntegerConstantExpr failed check. 8371 Diag(Loc, diag::err_in_class_initializer_non_constant) 8372 << Init->getSourceRange(); 8373 VDecl->setInvalidDecl(); 8374 } 8375 8376 // We allow foldable floating-point constants as an extension. 8377 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8378 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8379 // it anyway and provide a fixit to add the 'constexpr'. 8380 if (getLangOpts().CPlusPlus11) { 8381 Diag(VDecl->getLocation(), 8382 diag::ext_in_class_initializer_float_type_cxx11) 8383 << DclT << Init->getSourceRange(); 8384 Diag(VDecl->getLocStart(), 8385 diag::note_in_class_initializer_float_type_cxx11) 8386 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8387 } else { 8388 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8389 << DclT << Init->getSourceRange(); 8390 8391 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8392 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8393 << Init->getSourceRange(); 8394 VDecl->setInvalidDecl(); 8395 } 8396 } 8397 8398 // Suggest adding 'constexpr' in C++11 for literal types. 8399 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8400 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8401 << DclT << Init->getSourceRange() 8402 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8403 VDecl->setConstexpr(true); 8404 8405 } else { 8406 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8407 << DclT << Init->getSourceRange(); 8408 VDecl->setInvalidDecl(); 8409 } 8410 } else if (VDecl->isFileVarDecl()) { 8411 if (VDecl->getStorageClass() == SC_Extern && 8412 (!getLangOpts().CPlusPlus || 8413 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8414 VDecl->isExternC())) && 8415 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8416 Diag(VDecl->getLocation(), diag::warn_extern_init); 8417 8418 // C99 6.7.8p4. All file scoped initializers need to be constant. 8419 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8420 CheckForConstantInitializer(Init, DclT); 8421 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8422 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8423 !Init->isValueDependent() && !VDecl->isConstexpr() && 8424 !Init->isConstantInitializer( 8425 Context, VDecl->getType()->isReferenceType())) { 8426 // GNU C++98 edits for __thread, [basic.start.init]p4: 8427 // An object of thread storage duration shall not require dynamic 8428 // initialization. 8429 // FIXME: Need strict checking here. 8430 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8431 if (getLangOpts().CPlusPlus11) 8432 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8433 } 8434 } 8435 8436 // We will represent direct-initialization similarly to copy-initialization: 8437 // int x(1); -as-> int x = 1; 8438 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8439 // 8440 // Clients that want to distinguish between the two forms, can check for 8441 // direct initializer using VarDecl::getInitStyle(). 8442 // A major benefit is that clients that don't particularly care about which 8443 // exactly form was it (like the CodeGen) can handle both cases without 8444 // special case code. 8445 8446 // C++ 8.5p11: 8447 // The form of initialization (using parentheses or '=') is generally 8448 // insignificant, but does matter when the entity being initialized has a 8449 // class type. 8450 if (CXXDirectInit) { 8451 assert(DirectInit && "Call-style initializer must be direct init."); 8452 VDecl->setInitStyle(VarDecl::CallInit); 8453 } else if (DirectInit) { 8454 // This must be list-initialization. No other way is direct-initialization. 8455 VDecl->setInitStyle(VarDecl::ListInit); 8456 } 8457 8458 CheckCompleteVariableDeclaration(VDecl); 8459} 8460 8461/// ActOnInitializerError - Given that there was an error parsing an 8462/// initializer for the given declaration, try to return to some form 8463/// of sanity. 8464void Sema::ActOnInitializerError(Decl *D) { 8465 // Our main concern here is re-establishing invariants like "a 8466 // variable's type is either dependent or complete". 8467 if (!D || D->isInvalidDecl()) return; 8468 8469 VarDecl *VD = dyn_cast<VarDecl>(D); 8470 if (!VD) return; 8471 8472 // Auto types are meaningless if we can't make sense of the initializer. 8473 if (ParsingInitForAutoVars.count(D)) { 8474 D->setInvalidDecl(); 8475 return; 8476 } 8477 8478 QualType Ty = VD->getType(); 8479 if (Ty->isDependentType()) return; 8480 8481 // Require a complete type. 8482 if (RequireCompleteType(VD->getLocation(), 8483 Context.getBaseElementType(Ty), 8484 diag::err_typecheck_decl_incomplete_type)) { 8485 VD->setInvalidDecl(); 8486 return; 8487 } 8488 8489 // Require an abstract type. 8490 if (RequireNonAbstractType(VD->getLocation(), Ty, 8491 diag::err_abstract_type_in_decl, 8492 AbstractVariableType)) { 8493 VD->setInvalidDecl(); 8494 return; 8495 } 8496 8497 // Don't bother complaining about constructors or destructors, 8498 // though. 8499} 8500 8501void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8502 bool TypeMayContainAuto) { 8503 // If there is no declaration, there was an error parsing it. Just ignore it. 8504 if (RealDecl == 0) 8505 return; 8506 8507 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8508 QualType Type = Var->getType(); 8509 8510 // C++11 [dcl.spec.auto]p3 8511 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8512 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8513 << Var->getDeclName() << Type; 8514 Var->setInvalidDecl(); 8515 return; 8516 } 8517 8518 // C++11 [class.static.data]p3: A static data member can be declared with 8519 // the constexpr specifier; if so, its declaration shall specify 8520 // a brace-or-equal-initializer. 8521 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8522 // the definition of a variable [...] or the declaration of a static data 8523 // member. 8524 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8525 if (Var->isStaticDataMember()) 8526 Diag(Var->getLocation(), 8527 diag::err_constexpr_static_mem_var_requires_init) 8528 << Var->getDeclName(); 8529 else 8530 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8531 Var->setInvalidDecl(); 8532 return; 8533 } 8534 8535 switch (Var->isThisDeclarationADefinition()) { 8536 case VarDecl::Definition: 8537 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8538 break; 8539 8540 // We have an out-of-line definition of a static data member 8541 // that has an in-class initializer, so we type-check this like 8542 // a declaration. 8543 // 8544 // Fall through 8545 8546 case VarDecl::DeclarationOnly: 8547 // It's only a declaration. 8548 8549 // Block scope. C99 6.7p7: If an identifier for an object is 8550 // declared with no linkage (C99 6.2.2p6), the type for the 8551 // object shall be complete. 8552 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8553 !Var->hasLinkage() && !Var->isInvalidDecl() && 8554 RequireCompleteType(Var->getLocation(), Type, 8555 diag::err_typecheck_decl_incomplete_type)) 8556 Var->setInvalidDecl(); 8557 8558 // Make sure that the type is not abstract. 8559 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8560 RequireNonAbstractType(Var->getLocation(), Type, 8561 diag::err_abstract_type_in_decl, 8562 AbstractVariableType)) 8563 Var->setInvalidDecl(); 8564 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8565 Var->getStorageClass() == SC_PrivateExtern) { 8566 Diag(Var->getLocation(), diag::warn_private_extern); 8567 Diag(Var->getLocation(), diag::note_private_extern); 8568 } 8569 8570 return; 8571 8572 case VarDecl::TentativeDefinition: 8573 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8574 // object that has file scope without an initializer, and without a 8575 // storage-class specifier or with the storage-class specifier "static", 8576 // constitutes a tentative definition. Note: A tentative definition with 8577 // external linkage is valid (C99 6.2.2p5). 8578 if (!Var->isInvalidDecl()) { 8579 if (const IncompleteArrayType *ArrayT 8580 = Context.getAsIncompleteArrayType(Type)) { 8581 if (RequireCompleteType(Var->getLocation(), 8582 ArrayT->getElementType(), 8583 diag::err_illegal_decl_array_incomplete_type)) 8584 Var->setInvalidDecl(); 8585 } else if (Var->getStorageClass() == SC_Static) { 8586 // C99 6.9.2p3: If the declaration of an identifier for an object is 8587 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8588 // declared type shall not be an incomplete type. 8589 // NOTE: code such as the following 8590 // static struct s; 8591 // struct s { int a; }; 8592 // is accepted by gcc. Hence here we issue a warning instead of 8593 // an error and we do not invalidate the static declaration. 8594 // NOTE: to avoid multiple warnings, only check the first declaration. 8595 if (Var->isFirstDecl()) 8596 RequireCompleteType(Var->getLocation(), Type, 8597 diag::ext_typecheck_decl_incomplete_type); 8598 } 8599 } 8600 8601 // Record the tentative definition; we're done. 8602 if (!Var->isInvalidDecl()) 8603 TentativeDefinitions.push_back(Var); 8604 return; 8605 } 8606 8607 // Provide a specific diagnostic for uninitialized variable 8608 // definitions with incomplete array type. 8609 if (Type->isIncompleteArrayType()) { 8610 Diag(Var->getLocation(), 8611 diag::err_typecheck_incomplete_array_needs_initializer); 8612 Var->setInvalidDecl(); 8613 return; 8614 } 8615 8616 // Provide a specific diagnostic for uninitialized variable 8617 // definitions with reference type. 8618 if (Type->isReferenceType()) { 8619 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8620 << Var->getDeclName() 8621 << SourceRange(Var->getLocation(), Var->getLocation()); 8622 Var->setInvalidDecl(); 8623 return; 8624 } 8625 8626 // Do not attempt to type-check the default initializer for a 8627 // variable with dependent type. 8628 if (Type->isDependentType()) 8629 return; 8630 8631 if (Var->isInvalidDecl()) 8632 return; 8633 8634 if (RequireCompleteType(Var->getLocation(), 8635 Context.getBaseElementType(Type), 8636 diag::err_typecheck_decl_incomplete_type)) { 8637 Var->setInvalidDecl(); 8638 return; 8639 } 8640 8641 // The variable can not have an abstract class type. 8642 if (RequireNonAbstractType(Var->getLocation(), Type, 8643 diag::err_abstract_type_in_decl, 8644 AbstractVariableType)) { 8645 Var->setInvalidDecl(); 8646 return; 8647 } 8648 8649 // Check for jumps past the implicit initializer. C++0x 8650 // clarifies that this applies to a "variable with automatic 8651 // storage duration", not a "local variable". 8652 // C++11 [stmt.dcl]p3 8653 // A program that jumps from a point where a variable with automatic 8654 // storage duration is not in scope to a point where it is in scope is 8655 // ill-formed unless the variable has scalar type, class type with a 8656 // trivial default constructor and a trivial destructor, a cv-qualified 8657 // version of one of these types, or an array of one of the preceding 8658 // types and is declared without an initializer. 8659 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8660 if (const RecordType *Record 8661 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8662 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8663 // Mark the function for further checking even if the looser rules of 8664 // C++11 do not require such checks, so that we can diagnose 8665 // incompatibilities with C++98. 8666 if (!CXXRecord->isPOD()) 8667 getCurFunction()->setHasBranchProtectedScope(); 8668 } 8669 } 8670 8671 // C++03 [dcl.init]p9: 8672 // If no initializer is specified for an object, and the 8673 // object is of (possibly cv-qualified) non-POD class type (or 8674 // array thereof), the object shall be default-initialized; if 8675 // the object is of const-qualified type, the underlying class 8676 // type shall have a user-declared default 8677 // constructor. Otherwise, if no initializer is specified for 8678 // a non- static object, the object and its subobjects, if 8679 // any, have an indeterminate initial value); if the object 8680 // or any of its subobjects are of const-qualified type, the 8681 // program is ill-formed. 8682 // C++0x [dcl.init]p11: 8683 // If no initializer is specified for an object, the object is 8684 // default-initialized; [...]. 8685 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8686 InitializationKind Kind 8687 = InitializationKind::CreateDefault(Var->getLocation()); 8688 8689 InitializationSequence InitSeq(*this, Entity, Kind, None); 8690 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8691 if (Init.isInvalid()) 8692 Var->setInvalidDecl(); 8693 else if (Init.get()) { 8694 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8695 // This is important for template substitution. 8696 Var->setInitStyle(VarDecl::CallInit); 8697 } 8698 8699 CheckCompleteVariableDeclaration(Var); 8700 } 8701} 8702 8703void Sema::ActOnCXXForRangeDecl(Decl *D) { 8704 VarDecl *VD = dyn_cast<VarDecl>(D); 8705 if (!VD) { 8706 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8707 D->setInvalidDecl(); 8708 return; 8709 } 8710 8711 VD->setCXXForRangeDecl(true); 8712 8713 // for-range-declaration cannot be given a storage class specifier. 8714 int Error = -1; 8715 switch (VD->getStorageClass()) { 8716 case SC_None: 8717 break; 8718 case SC_Extern: 8719 Error = 0; 8720 break; 8721 case SC_Static: 8722 Error = 1; 8723 break; 8724 case SC_PrivateExtern: 8725 Error = 2; 8726 break; 8727 case SC_Auto: 8728 Error = 3; 8729 break; 8730 case SC_Register: 8731 Error = 4; 8732 break; 8733 case SC_OpenCLWorkGroupLocal: 8734 llvm_unreachable("Unexpected storage class"); 8735 } 8736 if (VD->isConstexpr()) 8737 Error = 5; 8738 if (Error != -1) { 8739 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8740 << VD->getDeclName() << Error; 8741 D->setInvalidDecl(); 8742 } 8743} 8744 8745void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8746 if (var->isInvalidDecl()) return; 8747 8748 // In ARC, don't allow jumps past the implicit initialization of a 8749 // local retaining variable. 8750 if (getLangOpts().ObjCAutoRefCount && 8751 var->hasLocalStorage()) { 8752 switch (var->getType().getObjCLifetime()) { 8753 case Qualifiers::OCL_None: 8754 case Qualifiers::OCL_ExplicitNone: 8755 case Qualifiers::OCL_Autoreleasing: 8756 break; 8757 8758 case Qualifiers::OCL_Weak: 8759 case Qualifiers::OCL_Strong: 8760 getCurFunction()->setHasBranchProtectedScope(); 8761 break; 8762 } 8763 } 8764 8765 if (var->isThisDeclarationADefinition() && 8766 var->isExternallyVisible() && var->hasLinkage() && 8767 getDiagnostics().getDiagnosticLevel( 8768 diag::warn_missing_variable_declarations, 8769 var->getLocation())) { 8770 // Find a previous declaration that's not a definition. 8771 VarDecl *prev = var->getPreviousDecl(); 8772 while (prev && prev->isThisDeclarationADefinition()) 8773 prev = prev->getPreviousDecl(); 8774 8775 if (!prev) 8776 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8777 } 8778 8779 if (var->getTLSKind() == VarDecl::TLS_Static && 8780 var->getType().isDestructedType()) { 8781 // GNU C++98 edits for __thread, [basic.start.term]p3: 8782 // The type of an object with thread storage duration shall not 8783 // have a non-trivial destructor. 8784 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8785 if (getLangOpts().CPlusPlus11) 8786 Diag(var->getLocation(), diag::note_use_thread_local); 8787 } 8788 8789 // All the following checks are C++ only. 8790 if (!getLangOpts().CPlusPlus) return; 8791 8792 QualType type = var->getType(); 8793 if (type->isDependentType()) return; 8794 8795 // __block variables might require us to capture a copy-initializer. 8796 if (var->hasAttr<BlocksAttr>()) { 8797 // It's currently invalid to ever have a __block variable with an 8798 // array type; should we diagnose that here? 8799 8800 // Regardless, we don't want to ignore array nesting when 8801 // constructing this copy. 8802 if (type->isStructureOrClassType()) { 8803 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8804 SourceLocation poi = var->getLocation(); 8805 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8806 ExprResult result 8807 = PerformMoveOrCopyInitialization( 8808 InitializedEntity::InitializeBlock(poi, type, false), 8809 var, var->getType(), varRef, /*AllowNRVO=*/true); 8810 if (!result.isInvalid()) { 8811 result = MaybeCreateExprWithCleanups(result); 8812 Expr *init = result.takeAs<Expr>(); 8813 Context.setBlockVarCopyInits(var, init); 8814 } 8815 } 8816 } 8817 8818 Expr *Init = var->getInit(); 8819 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8820 QualType baseType = Context.getBaseElementType(type); 8821 8822 if (!var->getDeclContext()->isDependentContext() && 8823 Init && !Init->isValueDependent()) { 8824 if (IsGlobal && !var->isConstexpr() && 8825 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8826 var->getLocation()) 8827 != DiagnosticsEngine::Ignored) { 8828 // Warn about globals which don't have a constant initializer. Don't 8829 // warn about globals with a non-trivial destructor because we already 8830 // warned about them. 8831 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8832 if (!(RD && !RD->hasTrivialDestructor()) && 8833 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8834 Diag(var->getLocation(), diag::warn_global_constructor) 8835 << Init->getSourceRange(); 8836 } 8837 8838 if (var->isConstexpr()) { 8839 SmallVector<PartialDiagnosticAt, 8> Notes; 8840 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8841 SourceLocation DiagLoc = var->getLocation(); 8842 // If the note doesn't add any useful information other than a source 8843 // location, fold it into the primary diagnostic. 8844 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8845 diag::note_invalid_subexpr_in_const_expr) { 8846 DiagLoc = Notes[0].first; 8847 Notes.clear(); 8848 } 8849 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8850 << var << Init->getSourceRange(); 8851 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8852 Diag(Notes[I].first, Notes[I].second); 8853 } 8854 } else if (var->isUsableInConstantExpressions(Context)) { 8855 // Check whether the initializer of a const variable of integral or 8856 // enumeration type is an ICE now, since we can't tell whether it was 8857 // initialized by a constant expression if we check later. 8858 var->checkInitIsICE(); 8859 } 8860 } 8861 8862 // Require the destructor. 8863 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8864 FinalizeVarWithDestructor(var, recordType); 8865} 8866 8867/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8868/// any semantic actions necessary after any initializer has been attached. 8869void 8870Sema::FinalizeDeclaration(Decl *ThisDecl) { 8871 // Note that we are no longer parsing the initializer for this declaration. 8872 ParsingInitForAutoVars.erase(ThisDecl); 8873 8874 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8875 if (!VD) 8876 return; 8877 8878 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8879 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8880 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used"; 8881 VD->dropAttr<UsedAttr>(); 8882 } 8883 } 8884 8885 if (!VD->isInvalidDecl() && 8886 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8887 if (const VarDecl *Def = VD->getDefinition()) { 8888 if (Def->hasAttr<AliasAttr>()) { 8889 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8890 << VD->getDeclName(); 8891 Diag(Def->getLocation(), diag::note_previous_definition); 8892 VD->setInvalidDecl(); 8893 } 8894 } 8895 } 8896 8897 const DeclContext *DC = VD->getDeclContext(); 8898 // If there's a #pragma GCC visibility in scope, and this isn't a class 8899 // member, set the visibility of this variable. 8900 if (!DC->isRecord() && VD->isExternallyVisible()) 8901 AddPushedVisibilityAttribute(VD); 8902 8903 if (VD->isFileVarDecl()) 8904 MarkUnusedFileScopedDecl(VD); 8905 8906 // Now we have parsed the initializer and can update the table of magic 8907 // tag values. 8908 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8909 !VD->getType()->isIntegralOrEnumerationType()) 8910 return; 8911 8912 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8913 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8914 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8915 I != E; ++I) { 8916 const Expr *MagicValueExpr = VD->getInit(); 8917 if (!MagicValueExpr) { 8918 continue; 8919 } 8920 llvm::APSInt MagicValueInt; 8921 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8922 Diag(I->getRange().getBegin(), 8923 diag::err_type_tag_for_datatype_not_ice) 8924 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8925 continue; 8926 } 8927 if (MagicValueInt.getActiveBits() > 64) { 8928 Diag(I->getRange().getBegin(), 8929 diag::err_type_tag_for_datatype_too_large) 8930 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8931 continue; 8932 } 8933 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8934 RegisterTypeTagForDatatype(I->getArgumentKind(), 8935 MagicValue, 8936 I->getMatchingCType(), 8937 I->getLayoutCompatible(), 8938 I->getMustBeNull()); 8939 } 8940} 8941 8942Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8943 ArrayRef<Decl *> Group) { 8944 SmallVector<Decl*, 8> Decls; 8945 8946 if (DS.isTypeSpecOwned()) 8947 Decls.push_back(DS.getRepAsDecl()); 8948 8949 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8950 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8951 if (Decl *D = Group[i]) { 8952 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8953 if (!FirstDeclaratorInGroup) 8954 FirstDeclaratorInGroup = DD; 8955 Decls.push_back(D); 8956 } 8957 8958 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8959 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8960 HandleTagNumbering(*this, Tag); 8961 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8962 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8963 } 8964 } 8965 8966 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8967} 8968 8969/// BuildDeclaratorGroup - convert a list of declarations into a declaration 8970/// group, performing any necessary semantic checking. 8971Sema::DeclGroupPtrTy 8972Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8973 bool TypeMayContainAuto) { 8974 // C++0x [dcl.spec.auto]p7: 8975 // If the type deduced for the template parameter U is not the same in each 8976 // deduction, the program is ill-formed. 8977 // FIXME: When initializer-list support is added, a distinction is needed 8978 // between the deduced type U and the deduced type which 'auto' stands for. 8979 // auto a = 0, b = { 1, 2, 3 }; 8980 // is legal because the deduced type U is 'int' in both cases. 8981 if (TypeMayContainAuto && Group.size() > 1) { 8982 QualType Deduced; 8983 CanQualType DeducedCanon; 8984 VarDecl *DeducedDecl = 0; 8985 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 8986 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 8987 AutoType *AT = D->getType()->getContainedAutoType(); 8988 // Don't reissue diagnostics when instantiating a template. 8989 if (AT && D->isInvalidDecl()) 8990 break; 8991 QualType U = AT ? AT->getDeducedType() : QualType(); 8992 if (!U.isNull()) { 8993 CanQualType UCanon = Context.getCanonicalType(U); 8994 if (Deduced.isNull()) { 8995 Deduced = U; 8996 DeducedCanon = UCanon; 8997 DeducedDecl = D; 8998 } else if (DeducedCanon != UCanon) { 8999 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9000 diag::err_auto_different_deductions) 9001 << (AT->isDecltypeAuto() ? 1 : 0) 9002 << Deduced << DeducedDecl->getDeclName() 9003 << U << D->getDeclName() 9004 << DeducedDecl->getInit()->getSourceRange() 9005 << D->getInit()->getSourceRange(); 9006 D->setInvalidDecl(); 9007 break; 9008 } 9009 } 9010 } 9011 } 9012 } 9013 9014 ActOnDocumentableDecls(Group); 9015 9016 return DeclGroupPtrTy::make( 9017 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9018} 9019 9020void Sema::ActOnDocumentableDecl(Decl *D) { 9021 ActOnDocumentableDecls(D); 9022} 9023 9024void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9025 // Don't parse the comment if Doxygen diagnostics are ignored. 9026 if (Group.empty() || !Group[0]) 9027 return; 9028 9029 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9030 Group[0]->getLocation()) 9031 == DiagnosticsEngine::Ignored) 9032 return; 9033 9034 if (Group.size() >= 2) { 9035 // This is a decl group. Normally it will contain only declarations 9036 // produced from declarator list. But in case we have any definitions or 9037 // additional declaration references: 9038 // 'typedef struct S {} S;' 9039 // 'typedef struct S *S;' 9040 // 'struct S *pS;' 9041 // FinalizeDeclaratorGroup adds these as separate declarations. 9042 Decl *MaybeTagDecl = Group[0]; 9043 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9044 Group = Group.slice(1); 9045 } 9046 } 9047 9048 // See if there are any new comments that are not attached to a decl. 9049 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9050 if (!Comments.empty() && 9051 !Comments.back()->isAttached()) { 9052 // There is at least one comment that not attached to a decl. 9053 // Maybe it should be attached to one of these decls? 9054 // 9055 // Note that this way we pick up not only comments that precede the 9056 // declaration, but also comments that *follow* the declaration -- thanks to 9057 // the lookahead in the lexer: we've consumed the semicolon and looked 9058 // ahead through comments. 9059 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9060 Context.getCommentForDecl(Group[i], &PP); 9061 } 9062} 9063 9064/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9065/// to introduce parameters into function prototype scope. 9066Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9067 const DeclSpec &DS = D.getDeclSpec(); 9068 9069 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9070 9071 // C++03 [dcl.stc]p2 also permits 'auto'. 9072 VarDecl::StorageClass StorageClass = SC_None; 9073 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9074 StorageClass = SC_Register; 9075 } else if (getLangOpts().CPlusPlus && 9076 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9077 StorageClass = SC_Auto; 9078 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9079 Diag(DS.getStorageClassSpecLoc(), 9080 diag::err_invalid_storage_class_in_func_decl); 9081 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9082 } 9083 9084 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9085 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9086 << DeclSpec::getSpecifierName(TSCS); 9087 if (DS.isConstexprSpecified()) 9088 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9089 << 0; 9090 9091 DiagnoseFunctionSpecifiers(DS); 9092 9093 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9094 QualType parmDeclType = TInfo->getType(); 9095 9096 if (getLangOpts().CPlusPlus) { 9097 // Check that there are no default arguments inside the type of this 9098 // parameter. 9099 CheckExtraCXXDefaultArguments(D); 9100 9101 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9102 if (D.getCXXScopeSpec().isSet()) { 9103 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9104 << D.getCXXScopeSpec().getRange(); 9105 D.getCXXScopeSpec().clear(); 9106 } 9107 } 9108 9109 // Ensure we have a valid name 9110 IdentifierInfo *II = 0; 9111 if (D.hasName()) { 9112 II = D.getIdentifier(); 9113 if (!II) { 9114 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9115 << GetNameForDeclarator(D).getName().getAsString(); 9116 D.setInvalidType(true); 9117 } 9118 } 9119 9120 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9121 if (II) { 9122 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9123 ForRedeclaration); 9124 LookupName(R, S); 9125 if (R.isSingleResult()) { 9126 NamedDecl *PrevDecl = R.getFoundDecl(); 9127 if (PrevDecl->isTemplateParameter()) { 9128 // Maybe we will complain about the shadowed template parameter. 9129 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9130 // Just pretend that we didn't see the previous declaration. 9131 PrevDecl = 0; 9132 } else if (S->isDeclScope(PrevDecl)) { 9133 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9134 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9135 9136 // Recover by removing the name 9137 II = 0; 9138 D.SetIdentifier(0, D.getIdentifierLoc()); 9139 D.setInvalidType(true); 9140 } 9141 } 9142 } 9143 9144 // Temporarily put parameter variables in the translation unit, not 9145 // the enclosing context. This prevents them from accidentally 9146 // looking like class members in C++. 9147 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9148 D.getLocStart(), 9149 D.getIdentifierLoc(), II, 9150 parmDeclType, TInfo, 9151 StorageClass); 9152 9153 if (D.isInvalidType()) 9154 New->setInvalidDecl(); 9155 9156 assert(S->isFunctionPrototypeScope()); 9157 assert(S->getFunctionPrototypeDepth() >= 1); 9158 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9159 S->getNextFunctionPrototypeIndex()); 9160 9161 // Add the parameter declaration into this scope. 9162 S->AddDecl(New); 9163 if (II) 9164 IdResolver.AddDecl(New); 9165 9166 ProcessDeclAttributes(S, New, D); 9167 9168 if (D.getDeclSpec().isModulePrivateSpecified()) 9169 Diag(New->getLocation(), diag::err_module_private_local) 9170 << 1 << New->getDeclName() 9171 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9172 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9173 9174 if (New->hasAttr<BlocksAttr>()) { 9175 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9176 } 9177 return New; 9178} 9179 9180/// \brief Synthesizes a variable for a parameter arising from a 9181/// typedef. 9182ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9183 SourceLocation Loc, 9184 QualType T) { 9185 /* FIXME: setting StartLoc == Loc. 9186 Would it be worth to modify callers so as to provide proper source 9187 location for the unnamed parameters, embedding the parameter's type? */ 9188 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9189 T, Context.getTrivialTypeSourceInfo(T, Loc), 9190 SC_None, 0); 9191 Param->setImplicit(); 9192 return Param; 9193} 9194 9195void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9196 ParmVarDecl * const *ParamEnd) { 9197 // Don't diagnose unused-parameter errors in template instantiations; we 9198 // will already have done so in the template itself. 9199 if (!ActiveTemplateInstantiations.empty()) 9200 return; 9201 9202 for (; Param != ParamEnd; ++Param) { 9203 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9204 !(*Param)->hasAttr<UnusedAttr>()) { 9205 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9206 << (*Param)->getDeclName(); 9207 } 9208 } 9209} 9210 9211void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9212 ParmVarDecl * const *ParamEnd, 9213 QualType ReturnTy, 9214 NamedDecl *D) { 9215 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9216 return; 9217 9218 // Warn if the return value is pass-by-value and larger than the specified 9219 // threshold. 9220 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9221 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9222 if (Size > LangOpts.NumLargeByValueCopy) 9223 Diag(D->getLocation(), diag::warn_return_value_size) 9224 << D->getDeclName() << Size; 9225 } 9226 9227 // Warn if any parameter is pass-by-value and larger than the specified 9228 // threshold. 9229 for (; Param != ParamEnd; ++Param) { 9230 QualType T = (*Param)->getType(); 9231 if (T->isDependentType() || !T.isPODType(Context)) 9232 continue; 9233 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9234 if (Size > LangOpts.NumLargeByValueCopy) 9235 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9236 << (*Param)->getDeclName() << Size; 9237 } 9238} 9239 9240ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9241 SourceLocation NameLoc, IdentifierInfo *Name, 9242 QualType T, TypeSourceInfo *TSInfo, 9243 VarDecl::StorageClass StorageClass) { 9244 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9245 if (getLangOpts().ObjCAutoRefCount && 9246 T.getObjCLifetime() == Qualifiers::OCL_None && 9247 T->isObjCLifetimeType()) { 9248 9249 Qualifiers::ObjCLifetime lifetime; 9250 9251 // Special cases for arrays: 9252 // - if it's const, use __unsafe_unretained 9253 // - otherwise, it's an error 9254 if (T->isArrayType()) { 9255 if (!T.isConstQualified()) { 9256 DelayedDiagnostics.add( 9257 sema::DelayedDiagnostic::makeForbiddenType( 9258 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9259 } 9260 lifetime = Qualifiers::OCL_ExplicitNone; 9261 } else { 9262 lifetime = T->getObjCARCImplicitLifetime(); 9263 } 9264 T = Context.getLifetimeQualifiedType(T, lifetime); 9265 } 9266 9267 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9268 Context.getAdjustedParameterType(T), 9269 TSInfo, 9270 StorageClass, 0); 9271 9272 // Parameters can not be abstract class types. 9273 // For record types, this is done by the AbstractClassUsageDiagnoser once 9274 // the class has been completely parsed. 9275 if (!CurContext->isRecord() && 9276 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9277 AbstractParamType)) 9278 New->setInvalidDecl(); 9279 9280 // Parameter declarators cannot be interface types. All ObjC objects are 9281 // passed by reference. 9282 if (T->isObjCObjectType()) { 9283 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9284 Diag(NameLoc, 9285 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9286 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9287 T = Context.getObjCObjectPointerType(T); 9288 New->setType(T); 9289 } 9290 9291 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9292 // duration shall not be qualified by an address-space qualifier." 9293 // Since all parameters have automatic store duration, they can not have 9294 // an address space. 9295 if (T.getAddressSpace() != 0) { 9296 Diag(NameLoc, diag::err_arg_with_address_space); 9297 New->setInvalidDecl(); 9298 } 9299 9300 return New; 9301} 9302 9303void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9304 SourceLocation LocAfterDecls) { 9305 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9306 9307 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9308 // for a K&R function. 9309 if (!FTI.hasPrototype) { 9310 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9311 --i; 9312 if (FTI.ArgInfo[i].Param == 0) { 9313 SmallString<256> Code; 9314 llvm::raw_svector_ostream(Code) << " int " 9315 << FTI.ArgInfo[i].Ident->getName() 9316 << ";\n"; 9317 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9318 << FTI.ArgInfo[i].Ident 9319 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9320 9321 // Implicitly declare the argument as type 'int' for lack of a better 9322 // type. 9323 AttributeFactory attrs; 9324 DeclSpec DS(attrs); 9325 const char* PrevSpec; // unused 9326 unsigned DiagID; // unused 9327 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9328 PrevSpec, DiagID); 9329 // Use the identifier location for the type source range. 9330 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9331 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9332 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9333 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9334 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9335 } 9336 } 9337 } 9338} 9339 9340Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9341 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9342 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9343 Scope *ParentScope = FnBodyScope->getParent(); 9344 9345 D.setFunctionDefinitionKind(FDK_Definition); 9346 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9347 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9348} 9349 9350static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9351 const FunctionDecl*& PossibleZeroParamPrototype) { 9352 // Don't warn about invalid declarations. 9353 if (FD->isInvalidDecl()) 9354 return false; 9355 9356 // Or declarations that aren't global. 9357 if (!FD->isGlobal()) 9358 return false; 9359 9360 // Don't warn about C++ member functions. 9361 if (isa<CXXMethodDecl>(FD)) 9362 return false; 9363 9364 // Don't warn about 'main'. 9365 if (FD->isMain()) 9366 return false; 9367 9368 // Don't warn about inline functions. 9369 if (FD->isInlined()) 9370 return false; 9371 9372 // Don't warn about function templates. 9373 if (FD->getDescribedFunctionTemplate()) 9374 return false; 9375 9376 // Don't warn about function template specializations. 9377 if (FD->isFunctionTemplateSpecialization()) 9378 return false; 9379 9380 // Don't warn for OpenCL kernels. 9381 if (FD->hasAttr<OpenCLKernelAttr>()) 9382 return false; 9383 9384 bool MissingPrototype = true; 9385 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9386 Prev; Prev = Prev->getPreviousDecl()) { 9387 // Ignore any declarations that occur in function or method 9388 // scope, because they aren't visible from the header. 9389 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9390 continue; 9391 9392 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9393 if (FD->getNumParams() == 0) 9394 PossibleZeroParamPrototype = Prev; 9395 break; 9396 } 9397 9398 return MissingPrototype; 9399} 9400 9401void 9402Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9403 const FunctionDecl *EffectiveDefinition) { 9404 // Don't complain if we're in GNU89 mode and the previous definition 9405 // was an extern inline function. 9406 const FunctionDecl *Definition = EffectiveDefinition; 9407 if (!Definition) 9408 if (!FD->isDefined(Definition)) 9409 return; 9410 9411 if (canRedefineFunction(Definition, getLangOpts())) 9412 return; 9413 9414 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9415 Definition->getStorageClass() == SC_Extern) 9416 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9417 << FD->getDeclName() << getLangOpts().CPlusPlus; 9418 else 9419 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9420 9421 Diag(Definition->getLocation(), diag::note_previous_definition); 9422 FD->setInvalidDecl(); 9423} 9424static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9425 Sema &S) { 9426 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9427 S.PushLambdaScope(); 9428 LambdaScopeInfo *LSI = S.getCurLambda(); 9429 LSI->CallOperator = CallOperator; 9430 LSI->Lambda = LambdaClass; 9431 LSI->ReturnType = CallOperator->getResultType(); 9432 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9433 9434 if (LCD == LCD_None) 9435 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9436 else if (LCD == LCD_ByCopy) 9437 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9438 else if (LCD == LCD_ByRef) 9439 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9440 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9441 9442 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9443 LSI->Mutable = !CallOperator->isConst(); 9444 9445 // FIXME: Add the captures to the LSI. 9446} 9447 9448Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9449 // Clear the last template instantiation error context. 9450 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9451 9452 if (!D) 9453 return D; 9454 FunctionDecl *FD = 0; 9455 9456 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9457 FD = FunTmpl->getTemplatedDecl(); 9458 else 9459 FD = cast<FunctionDecl>(D); 9460 // If we are instantiating a generic lambda call operator, push 9461 // a LambdaScopeInfo onto the function stack. But use the information 9462 // that's already been calculated (ActOnLambdaExpr) to prime the current 9463 // LambdaScopeInfo. 9464 // When the template operator is being specialized, the LambdaScopeInfo, 9465 // has to be properly restored so that tryCaptureVariable doesn't try 9466 // and capture any new variables. In addition when calculating potential 9467 // captures during transformation of nested lambdas, it is necessary to 9468 // have the LSI properly restored. 9469 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9470 assert(ActiveTemplateInstantiations.size() && 9471 "There should be an active template instantiation on the stack " 9472 "when instantiating a generic lambda!"); 9473 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9474 } 9475 else 9476 // Enter a new function scope 9477 PushFunctionScope(); 9478 9479 // See if this is a redefinition. 9480 if (!FD->isLateTemplateParsed()) 9481 CheckForFunctionRedefinition(FD); 9482 9483 // Builtin functions cannot be defined. 9484 if (unsigned BuiltinID = FD->getBuiltinID()) { 9485 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9486 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9487 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9488 FD->setInvalidDecl(); 9489 } 9490 } 9491 9492 // The return type of a function definition must be complete 9493 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9494 QualType ResultType = FD->getResultType(); 9495 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9496 !FD->isInvalidDecl() && 9497 RequireCompleteType(FD->getLocation(), ResultType, 9498 diag::err_func_def_incomplete_result)) 9499 FD->setInvalidDecl(); 9500 9501 // GNU warning -Wmissing-prototypes: 9502 // Warn if a global function is defined without a previous 9503 // prototype declaration. This warning is issued even if the 9504 // definition itself provides a prototype. The aim is to detect 9505 // global functions that fail to be declared in header files. 9506 const FunctionDecl *PossibleZeroParamPrototype = 0; 9507 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9508 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9509 9510 if (PossibleZeroParamPrototype) { 9511 // We found a declaration that is not a prototype, 9512 // but that could be a zero-parameter prototype 9513 if (TypeSourceInfo *TI = 9514 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9515 TypeLoc TL = TI->getTypeLoc(); 9516 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9517 Diag(PossibleZeroParamPrototype->getLocation(), 9518 diag::note_declaration_not_a_prototype) 9519 << PossibleZeroParamPrototype 9520 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9521 } 9522 } 9523 } 9524 9525 if (FnBodyScope) 9526 PushDeclContext(FnBodyScope, FD); 9527 9528 // Check the validity of our function parameters 9529 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9530 /*CheckParameterNames=*/true); 9531 9532 // Introduce our parameters into the function scope 9533 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9534 ParmVarDecl *Param = FD->getParamDecl(p); 9535 Param->setOwningFunction(FD); 9536 9537 // If this has an identifier, add it to the scope stack. 9538 if (Param->getIdentifier() && FnBodyScope) { 9539 CheckShadow(FnBodyScope, Param); 9540 9541 PushOnScopeChains(Param, FnBodyScope); 9542 } 9543 } 9544 9545 // If we had any tags defined in the function prototype, 9546 // introduce them into the function scope. 9547 if (FnBodyScope) { 9548 for (ArrayRef<NamedDecl *>::iterator 9549 I = FD->getDeclsInPrototypeScope().begin(), 9550 E = FD->getDeclsInPrototypeScope().end(); 9551 I != E; ++I) { 9552 NamedDecl *D = *I; 9553 9554 // Some of these decls (like enums) may have been pinned to the translation unit 9555 // for lack of a real context earlier. If so, remove from the translation unit 9556 // and reattach to the current context. 9557 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9558 // Is the decl actually in the context? 9559 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9560 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9561 if (*DI == D) { 9562 Context.getTranslationUnitDecl()->removeDecl(D); 9563 break; 9564 } 9565 } 9566 // Either way, reassign the lexical decl context to our FunctionDecl. 9567 D->setLexicalDeclContext(CurContext); 9568 } 9569 9570 // If the decl has a non-null name, make accessible in the current scope. 9571 if (!D->getName().empty()) 9572 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9573 9574 // Similarly, dive into enums and fish their constants out, making them 9575 // accessible in this scope. 9576 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9577 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9578 EE = ED->enumerator_end(); EI != EE; ++EI) 9579 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9580 } 9581 } 9582 } 9583 9584 // Ensure that the function's exception specification is instantiated. 9585 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9586 ResolveExceptionSpec(D->getLocation(), FPT); 9587 9588 // Checking attributes of current function definition 9589 // dllimport attribute. 9590 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9591 if (DA && (!FD->getAttr<DLLExportAttr>())) { 9592 // dllimport attribute cannot be directly applied to definition. 9593 // Microsoft accepts dllimport for functions defined within class scope. 9594 if (!DA->isInherited() && 9595 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9596 Diag(FD->getLocation(), 9597 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9598 << "dllimport"; 9599 FD->setInvalidDecl(); 9600 return D; 9601 } 9602 9603 // Visual C++ appears to not think this is an issue, so only issue 9604 // a warning when Microsoft extensions are disabled. 9605 if (!LangOpts.MicrosoftExt) { 9606 // If a symbol previously declared dllimport is later defined, the 9607 // attribute is ignored in subsequent references, and a warning is 9608 // emitted. 9609 Diag(FD->getLocation(), 9610 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9611 << FD->getName() << "dllimport"; 9612 } 9613 } 9614 // We want to attach documentation to original Decl (which might be 9615 // a function template). 9616 ActOnDocumentableDecl(D); 9617 return D; 9618} 9619 9620/// \brief Given the set of return statements within a function body, 9621/// compute the variables that are subject to the named return value 9622/// optimization. 9623/// 9624/// Each of the variables that is subject to the named return value 9625/// optimization will be marked as NRVO variables in the AST, and any 9626/// return statement that has a marked NRVO variable as its NRVO candidate can 9627/// use the named return value optimization. 9628/// 9629/// This function applies a very simplistic algorithm for NRVO: if every return 9630/// statement in the function has the same NRVO candidate, that candidate is 9631/// the NRVO variable. 9632/// 9633/// FIXME: Employ a smarter algorithm that accounts for multiple return 9634/// statements and the lifetimes of the NRVO candidates. We should be able to 9635/// find a maximal set of NRVO variables. 9636void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9637 ReturnStmt **Returns = Scope->Returns.data(); 9638 9639 const VarDecl *NRVOCandidate = 0; 9640 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9641 if (!Returns[I]->getNRVOCandidate()) 9642 return; 9643 9644 if (!NRVOCandidate) 9645 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9646 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9647 return; 9648 } 9649 9650 if (NRVOCandidate) 9651 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9652} 9653 9654bool Sema::canSkipFunctionBody(Decl *D) { 9655 if (!Consumer.shouldSkipFunctionBody(D)) 9656 return false; 9657 9658 if (isa<ObjCMethodDecl>(D)) 9659 return true; 9660 9661 FunctionDecl *FD = 0; 9662 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 9663 FD = FTD->getTemplatedDecl(); 9664 else 9665 FD = cast<FunctionDecl>(D); 9666 9667 // We cannot skip the body of a function (or function template) which is 9668 // constexpr, since we may need to evaluate its body in order to parse the 9669 // rest of the file. 9670 // We cannot skip the body of a function with an undeduced return type, 9671 // because any callers of that function need to know the type. 9672 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType(); 9673} 9674 9675Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9676 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9677 FD->setHasSkippedBody(); 9678 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9679 MD->setHasSkippedBody(); 9680 return ActOnFinishFunctionBody(Decl, 0); 9681} 9682 9683Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9684 return ActOnFinishFunctionBody(D, BodyArg, false); 9685} 9686 9687Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9688 bool IsInstantiation) { 9689 FunctionDecl *FD = 0; 9690 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 9691 if (FunTmpl) 9692 FD = FunTmpl->getTemplatedDecl(); 9693 else 9694 FD = dyn_cast_or_null<FunctionDecl>(dcl); 9695 9696 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9697 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9698 9699 if (FD) { 9700 FD->setBody(Body); 9701 9702 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9703 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) { 9704 // If the function has a deduced result type but contains no 'return' 9705 // statements, the result type as written must be exactly 'auto', and 9706 // the deduced result type is 'void'. 9707 if (!FD->getResultType()->getAs<AutoType>()) { 9708 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9709 << FD->getResultType(); 9710 FD->setInvalidDecl(); 9711 } else { 9712 // Substitute 'void' for the 'auto' in the type. 9713 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9714 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc(); 9715 Context.adjustDeducedFunctionResultType( 9716 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9717 } 9718 } 9719 9720 // The only way to be included in UndefinedButUsed is if there is an 9721 // ODR use before the definition. Avoid the expensive map lookup if this 9722 // is the first declaration. 9723 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9724 if (!FD->isExternallyVisible()) 9725 UndefinedButUsed.erase(FD); 9726 else if (FD->isInlined() && 9727 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9728 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9729 UndefinedButUsed.erase(FD); 9730 } 9731 9732 // If the function implicitly returns zero (like 'main') or is naked, 9733 // don't complain about missing return statements. 9734 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9735 WP.disableCheckFallThrough(); 9736 9737 // MSVC permits the use of pure specifier (=0) on function definition, 9738 // defined at class scope, warn about this non standard construct. 9739 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9740 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9741 9742 if (!FD->isInvalidDecl()) { 9743 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9744 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9745 FD->getResultType(), FD); 9746 9747 // If this is a constructor, we need a vtable. 9748 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9749 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9750 9751 // Try to apply the named return value optimization. We have to check 9752 // if we can do this here because lambdas keep return statements around 9753 // to deduce an implicit return type. 9754 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 9755 !FD->isDependentContext()) 9756 computeNRVO(Body, getCurFunction()); 9757 } 9758 9759 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9760 "Function parsing confused"); 9761 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9762 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9763 MD->setBody(Body); 9764 if (!MD->isInvalidDecl()) { 9765 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9766 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9767 MD->getResultType(), MD); 9768 9769 if (Body) 9770 computeNRVO(Body, getCurFunction()); 9771 } 9772 if (getCurFunction()->ObjCShouldCallSuper) { 9773 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9774 << MD->getSelector().getAsString(); 9775 getCurFunction()->ObjCShouldCallSuper = false; 9776 } 9777 } else { 9778 return 0; 9779 } 9780 9781 assert(!getCurFunction()->ObjCShouldCallSuper && 9782 "This should only be set for ObjC methods, which should have been " 9783 "handled in the block above."); 9784 9785 // Verify and clean out per-function state. 9786 if (Body) { 9787 // C++ constructors that have function-try-blocks can't have return 9788 // statements in the handlers of that block. (C++ [except.handle]p14) 9789 // Verify this. 9790 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9791 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9792 9793 // Verify that gotos and switch cases don't jump into scopes illegally. 9794 if (getCurFunction()->NeedsScopeChecking() && 9795 !dcl->isInvalidDecl() && 9796 !hasAnyUnrecoverableErrorsInThisFunction() && 9797 !PP.isCodeCompletionEnabled()) 9798 DiagnoseInvalidJumps(Body); 9799 9800 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9801 if (!Destructor->getParent()->isDependentType()) 9802 CheckDestructor(Destructor); 9803 9804 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9805 Destructor->getParent()); 9806 } 9807 9808 // If any errors have occurred, clear out any temporaries that may have 9809 // been leftover. This ensures that these temporaries won't be picked up for 9810 // deletion in some later function. 9811 if (PP.getDiagnostics().hasErrorOccurred() || 9812 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9813 DiscardCleanupsInEvaluationContext(); 9814 } 9815 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9816 !isa<FunctionTemplateDecl>(dcl)) { 9817 // Since the body is valid, issue any analysis-based warnings that are 9818 // enabled. 9819 ActivePolicy = &WP; 9820 } 9821 9822 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9823 (!CheckConstexprFunctionDecl(FD) || 9824 !CheckConstexprFunctionBody(FD, Body))) 9825 FD->setInvalidDecl(); 9826 9827 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9828 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9829 assert(MaybeODRUseExprs.empty() && 9830 "Leftover expressions for odr-use checking"); 9831 } 9832 9833 if (!IsInstantiation) 9834 PopDeclContext(); 9835 9836 PopFunctionScopeInfo(ActivePolicy, dcl); 9837 // If any errors have occurred, clear out any temporaries that may have 9838 // been leftover. This ensures that these temporaries won't be picked up for 9839 // deletion in some later function. 9840 if (getDiagnostics().hasErrorOccurred()) { 9841 DiscardCleanupsInEvaluationContext(); 9842 } 9843 9844 return dcl; 9845} 9846 9847 9848/// When we finish delayed parsing of an attribute, we must attach it to the 9849/// relevant Decl. 9850void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9851 ParsedAttributes &Attrs) { 9852 // Always attach attributes to the underlying decl. 9853 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9854 D = TD->getTemplatedDecl(); 9855 ProcessDeclAttributeList(S, D, Attrs.getList()); 9856 9857 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9858 if (Method->isStatic()) 9859 checkThisInStaticMemberFunctionAttributes(Method); 9860} 9861 9862 9863/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9864/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9865NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9866 IdentifierInfo &II, Scope *S) { 9867 // Before we produce a declaration for an implicitly defined 9868 // function, see whether there was a locally-scoped declaration of 9869 // this name as a function or variable. If so, use that 9870 // (non-visible) declaration, and complain about it. 9871 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9872 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9873 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9874 return ExternCPrev; 9875 } 9876 9877 // Extension in C99. Legal in C90, but warn about it. 9878 unsigned diag_id; 9879 if (II.getName().startswith("__builtin_")) 9880 diag_id = diag::warn_builtin_unknown; 9881 else if (getLangOpts().C99) 9882 diag_id = diag::ext_implicit_function_decl; 9883 else 9884 diag_id = diag::warn_implicit_function_decl; 9885 Diag(Loc, diag_id) << &II; 9886 9887 // Because typo correction is expensive, only do it if the implicit 9888 // function declaration is going to be treated as an error. 9889 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9890 TypoCorrection Corrected; 9891 DeclFilterCCC<FunctionDecl> Validator; 9892 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9893 LookupOrdinaryName, S, 0, Validator))) 9894 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9895 /*ErrorRecovery*/false); 9896 } 9897 9898 // Set a Declarator for the implicit definition: int foo(); 9899 const char *Dummy; 9900 AttributeFactory attrFactory; 9901 DeclSpec DS(attrFactory); 9902 unsigned DiagID; 9903 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 9904 (void)Error; // Silence warning. 9905 assert(!Error && "Error setting up implicit decl!"); 9906 SourceLocation NoLoc; 9907 Declarator D(DS, Declarator::BlockContext); 9908 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9909 /*IsAmbiguous=*/false, 9910 /*RParenLoc=*/NoLoc, 9911 /*ArgInfo=*/0, 9912 /*NumArgs=*/0, 9913 /*EllipsisLoc=*/NoLoc, 9914 /*RParenLoc=*/NoLoc, 9915 /*TypeQuals=*/0, 9916 /*RefQualifierIsLvalueRef=*/true, 9917 /*RefQualifierLoc=*/NoLoc, 9918 /*ConstQualifierLoc=*/NoLoc, 9919 /*VolatileQualifierLoc=*/NoLoc, 9920 /*MutableLoc=*/NoLoc, 9921 EST_None, 9922 /*ESpecLoc=*/NoLoc, 9923 /*Exceptions=*/0, 9924 /*ExceptionRanges=*/0, 9925 /*NumExceptions=*/0, 9926 /*NoexceptExpr=*/0, 9927 Loc, Loc, D), 9928 DS.getAttributes(), 9929 SourceLocation()); 9930 D.SetIdentifier(&II, Loc); 9931 9932 // Insert this function into translation-unit scope. 9933 9934 DeclContext *PrevDC = CurContext; 9935 CurContext = Context.getTranslationUnitDecl(); 9936 9937 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9938 FD->setImplicit(); 9939 9940 CurContext = PrevDC; 9941 9942 AddKnownFunctionAttributes(FD); 9943 9944 return FD; 9945} 9946 9947/// \brief Adds any function attributes that we know a priori based on 9948/// the declaration of this function. 9949/// 9950/// These attributes can apply both to implicitly-declared builtins 9951/// (like __builtin___printf_chk) or to library-declared functions 9952/// like NSLog or printf. 9953/// 9954/// We need to check for duplicate attributes both here and where user-written 9955/// attributes are applied to declarations. 9956void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 9957 if (FD->isInvalidDecl()) 9958 return; 9959 9960 // If this is a built-in function, map its builtin attributes to 9961 // actual attributes. 9962 if (unsigned BuiltinID = FD->getBuiltinID()) { 9963 // Handle printf-formatting attributes. 9964 unsigned FormatIdx; 9965 bool HasVAListArg; 9966 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 9967 if (!FD->getAttr<FormatAttr>()) { 9968 const char *fmt = "printf"; 9969 unsigned int NumParams = FD->getNumParams(); 9970 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 9971 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 9972 fmt = "NSString"; 9973 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9974 &Context.Idents.get(fmt), 9975 FormatIdx+1, 9976 HasVAListArg ? 0 : FormatIdx+2)); 9977 } 9978 } 9979 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 9980 HasVAListArg)) { 9981 if (!FD->getAttr<FormatAttr>()) 9982 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9983 &Context.Idents.get("scanf"), 9984 FormatIdx+1, 9985 HasVAListArg ? 0 : FormatIdx+2)); 9986 } 9987 9988 // Mark const if we don't care about errno and that is the only 9989 // thing preventing the function from being const. This allows 9990 // IRgen to use LLVM intrinsics for such functions. 9991 if (!getLangOpts().MathErrno && 9992 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 9993 if (!FD->getAttr<ConstAttr>()) 9994 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9995 } 9996 9997 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 9998 !FD->getAttr<ReturnsTwiceAttr>()) 9999 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 10000 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 10001 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 10002 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 10003 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10004 } 10005 10006 IdentifierInfo *Name = FD->getIdentifier(); 10007 if (!Name) 10008 return; 10009 if ((!getLangOpts().CPlusPlus && 10010 FD->getDeclContext()->isTranslationUnit()) || 10011 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10012 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10013 LinkageSpecDecl::lang_c)) { 10014 // Okay: this could be a libc/libm/Objective-C function we know 10015 // about. 10016 } else 10017 return; 10018 10019 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10020 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10021 // target-specific builtins, perhaps? 10022 if (!FD->getAttr<FormatAttr>()) 10023 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10024 &Context.Idents.get("printf"), 2, 10025 Name->isStr("vasprintf") ? 0 : 3)); 10026 } 10027 10028 if (Name->isStr("__CFStringMakeConstantString")) { 10029 // We already have a __builtin___CFStringMakeConstantString, 10030 // but builds that use -fno-constant-cfstrings don't go through that. 10031 if (!FD->getAttr<FormatArgAttr>()) 10032 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 10033 } 10034} 10035 10036TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10037 TypeSourceInfo *TInfo) { 10038 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10039 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10040 10041 if (!TInfo) { 10042 assert(D.isInvalidType() && "no declarator info for valid type"); 10043 TInfo = Context.getTrivialTypeSourceInfo(T); 10044 } 10045 10046 // Scope manipulation handled by caller. 10047 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10048 D.getLocStart(), 10049 D.getIdentifierLoc(), 10050 D.getIdentifier(), 10051 TInfo); 10052 10053 // Bail out immediately if we have an invalid declaration. 10054 if (D.isInvalidType()) { 10055 NewTD->setInvalidDecl(); 10056 return NewTD; 10057 } 10058 10059 if (D.getDeclSpec().isModulePrivateSpecified()) { 10060 if (CurContext->isFunctionOrMethod()) 10061 Diag(NewTD->getLocation(), diag::err_module_private_local) 10062 << 2 << NewTD->getDeclName() 10063 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10064 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10065 else 10066 NewTD->setModulePrivate(); 10067 } 10068 10069 // C++ [dcl.typedef]p8: 10070 // If the typedef declaration defines an unnamed class (or 10071 // enum), the first typedef-name declared by the declaration 10072 // to be that class type (or enum type) is used to denote the 10073 // class type (or enum type) for linkage purposes only. 10074 // We need to check whether the type was declared in the declaration. 10075 switch (D.getDeclSpec().getTypeSpecType()) { 10076 case TST_enum: 10077 case TST_struct: 10078 case TST_interface: 10079 case TST_union: 10080 case TST_class: { 10081 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10082 10083 // Do nothing if the tag is not anonymous or already has an 10084 // associated typedef (from an earlier typedef in this decl group). 10085 if (tagFromDeclSpec->getIdentifier()) break; 10086 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10087 10088 // A well-formed anonymous tag must always be a TUK_Definition. 10089 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10090 10091 // The type must match the tag exactly; no qualifiers allowed. 10092 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10093 break; 10094 10095 // Otherwise, set this is the anon-decl typedef for the tag. 10096 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10097 break; 10098 } 10099 10100 default: 10101 break; 10102 } 10103 10104 return NewTD; 10105} 10106 10107 10108/// \brief Check that this is a valid underlying type for an enum declaration. 10109bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10110 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10111 QualType T = TI->getType(); 10112 10113 if (T->isDependentType()) 10114 return false; 10115 10116 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10117 if (BT->isInteger()) 10118 return false; 10119 10120 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10121 return true; 10122} 10123 10124/// Check whether this is a valid redeclaration of a previous enumeration. 10125/// \return true if the redeclaration was invalid. 10126bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10127 QualType EnumUnderlyingTy, 10128 const EnumDecl *Prev) { 10129 bool IsFixed = !EnumUnderlyingTy.isNull(); 10130 10131 if (IsScoped != Prev->isScoped()) { 10132 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10133 << Prev->isScoped(); 10134 Diag(Prev->getLocation(), diag::note_previous_use); 10135 return true; 10136 } 10137 10138 if (IsFixed && Prev->isFixed()) { 10139 if (!EnumUnderlyingTy->isDependentType() && 10140 !Prev->getIntegerType()->isDependentType() && 10141 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10142 Prev->getIntegerType())) { 10143 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10144 << EnumUnderlyingTy << Prev->getIntegerType(); 10145 Diag(Prev->getLocation(), diag::note_previous_use); 10146 return true; 10147 } 10148 } else if (IsFixed != Prev->isFixed()) { 10149 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10150 << Prev->isFixed(); 10151 Diag(Prev->getLocation(), diag::note_previous_use); 10152 return true; 10153 } 10154 10155 return false; 10156} 10157 10158/// \brief Get diagnostic %select index for tag kind for 10159/// redeclaration diagnostic message. 10160/// WARNING: Indexes apply to particular diagnostics only! 10161/// 10162/// \returns diagnostic %select index. 10163static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10164 switch (Tag) { 10165 case TTK_Struct: return 0; 10166 case TTK_Interface: return 1; 10167 case TTK_Class: return 2; 10168 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10169 } 10170} 10171 10172/// \brief Determine if tag kind is a class-key compatible with 10173/// class for redeclaration (class, struct, or __interface). 10174/// 10175/// \returns true iff the tag kind is compatible. 10176static bool isClassCompatTagKind(TagTypeKind Tag) 10177{ 10178 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10179} 10180 10181/// \brief Determine whether a tag with a given kind is acceptable 10182/// as a redeclaration of the given tag declaration. 10183/// 10184/// \returns true if the new tag kind is acceptable, false otherwise. 10185bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10186 TagTypeKind NewTag, bool isDefinition, 10187 SourceLocation NewTagLoc, 10188 const IdentifierInfo &Name) { 10189 // C++ [dcl.type.elab]p3: 10190 // The class-key or enum keyword present in the 10191 // elaborated-type-specifier shall agree in kind with the 10192 // declaration to which the name in the elaborated-type-specifier 10193 // refers. This rule also applies to the form of 10194 // elaborated-type-specifier that declares a class-name or 10195 // friend class since it can be construed as referring to the 10196 // definition of the class. Thus, in any 10197 // elaborated-type-specifier, the enum keyword shall be used to 10198 // refer to an enumeration (7.2), the union class-key shall be 10199 // used to refer to a union (clause 9), and either the class or 10200 // struct class-key shall be used to refer to a class (clause 9) 10201 // declared using the class or struct class-key. 10202 TagTypeKind OldTag = Previous->getTagKind(); 10203 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10204 if (OldTag == NewTag) 10205 return true; 10206 10207 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10208 // Warn about the struct/class tag mismatch. 10209 bool isTemplate = false; 10210 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10211 isTemplate = Record->getDescribedClassTemplate(); 10212 10213 if (!ActiveTemplateInstantiations.empty()) { 10214 // In a template instantiation, do not offer fix-its for tag mismatches 10215 // since they usually mess up the template instead of fixing the problem. 10216 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10217 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10218 << getRedeclDiagFromTagKind(OldTag); 10219 return true; 10220 } 10221 10222 if (isDefinition) { 10223 // On definitions, check previous tags and issue a fix-it for each 10224 // one that doesn't match the current tag. 10225 if (Previous->getDefinition()) { 10226 // Don't suggest fix-its for redefinitions. 10227 return true; 10228 } 10229 10230 bool previousMismatch = false; 10231 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10232 E(Previous->redecls_end()); I != E; ++I) { 10233 if (I->getTagKind() != NewTag) { 10234 if (!previousMismatch) { 10235 previousMismatch = true; 10236 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10237 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10238 << getRedeclDiagFromTagKind(I->getTagKind()); 10239 } 10240 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10241 << getRedeclDiagFromTagKind(NewTag) 10242 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10243 TypeWithKeyword::getTagTypeKindName(NewTag)); 10244 } 10245 } 10246 return true; 10247 } 10248 10249 // Check for a previous definition. If current tag and definition 10250 // are same type, do nothing. If no definition, but disagree with 10251 // with previous tag type, give a warning, but no fix-it. 10252 const TagDecl *Redecl = Previous->getDefinition() ? 10253 Previous->getDefinition() : Previous; 10254 if (Redecl->getTagKind() == NewTag) { 10255 return true; 10256 } 10257 10258 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10259 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10260 << getRedeclDiagFromTagKind(OldTag); 10261 Diag(Redecl->getLocation(), diag::note_previous_use); 10262 10263 // If there is a previous defintion, suggest a fix-it. 10264 if (Previous->getDefinition()) { 10265 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10266 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10267 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10268 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10269 } 10270 10271 return true; 10272 } 10273 return false; 10274} 10275 10276/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10277/// former case, Name will be non-null. In the later case, Name will be null. 10278/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10279/// reference/declaration/definition of a tag. 10280Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10281 SourceLocation KWLoc, CXXScopeSpec &SS, 10282 IdentifierInfo *Name, SourceLocation NameLoc, 10283 AttributeList *Attr, AccessSpecifier AS, 10284 SourceLocation ModulePrivateLoc, 10285 MultiTemplateParamsArg TemplateParameterLists, 10286 bool &OwnedDecl, bool &IsDependent, 10287 SourceLocation ScopedEnumKWLoc, 10288 bool ScopedEnumUsesClassTag, 10289 TypeResult UnderlyingType) { 10290 // If this is not a definition, it must have a name. 10291 IdentifierInfo *OrigName = Name; 10292 assert((Name != 0 || TUK == TUK_Definition) && 10293 "Nameless record must be a definition!"); 10294 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10295 10296 OwnedDecl = false; 10297 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10298 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10299 10300 // FIXME: Check explicit specializations more carefully. 10301 bool isExplicitSpecialization = false; 10302 bool Invalid = false; 10303 10304 // We only need to do this matching if we have template parameters 10305 // or a scope specifier, which also conveniently avoids this work 10306 // for non-C++ cases. 10307 if (TemplateParameterLists.size() > 0 || 10308 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10309 if (TemplateParameterList *TemplateParams = 10310 MatchTemplateParametersToScopeSpecifier( 10311 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10312 isExplicitSpecialization, Invalid)) { 10313 if (Kind == TTK_Enum) { 10314 Diag(KWLoc, diag::err_enum_template); 10315 return 0; 10316 } 10317 10318 if (TemplateParams->size() > 0) { 10319 // This is a declaration or definition of a class template (which may 10320 // be a member of another template). 10321 10322 if (Invalid) 10323 return 0; 10324 10325 OwnedDecl = false; 10326 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10327 SS, Name, NameLoc, Attr, 10328 TemplateParams, AS, 10329 ModulePrivateLoc, 10330 TemplateParameterLists.size()-1, 10331 TemplateParameterLists.data()); 10332 return Result.get(); 10333 } else { 10334 // The "template<>" header is extraneous. 10335 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10336 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10337 isExplicitSpecialization = true; 10338 } 10339 } 10340 } 10341 10342 // Figure out the underlying type if this a enum declaration. We need to do 10343 // this early, because it's needed to detect if this is an incompatible 10344 // redeclaration. 10345 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10346 10347 if (Kind == TTK_Enum) { 10348 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10349 // No underlying type explicitly specified, or we failed to parse the 10350 // type, default to int. 10351 EnumUnderlying = Context.IntTy.getTypePtr(); 10352 else if (UnderlyingType.get()) { 10353 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10354 // integral type; any cv-qualification is ignored. 10355 TypeSourceInfo *TI = 0; 10356 GetTypeFromParser(UnderlyingType.get(), &TI); 10357 EnumUnderlying = TI; 10358 10359 if (CheckEnumUnderlyingType(TI)) 10360 // Recover by falling back to int. 10361 EnumUnderlying = Context.IntTy.getTypePtr(); 10362 10363 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10364 UPPC_FixedUnderlyingType)) 10365 EnumUnderlying = Context.IntTy.getTypePtr(); 10366 10367 } else if (getLangOpts().MicrosoftMode) 10368 // Microsoft enums are always of int type. 10369 EnumUnderlying = Context.IntTy.getTypePtr(); 10370 } 10371 10372 DeclContext *SearchDC = CurContext; 10373 DeclContext *DC = CurContext; 10374 bool isStdBadAlloc = false; 10375 10376 RedeclarationKind Redecl = ForRedeclaration; 10377 if (TUK == TUK_Friend || TUK == TUK_Reference) 10378 Redecl = NotForRedeclaration; 10379 10380 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10381 bool FriendSawTagOutsideEnclosingNamespace = false; 10382 if (Name && SS.isNotEmpty()) { 10383 // We have a nested-name tag ('struct foo::bar'). 10384 10385 // Check for invalid 'foo::'. 10386 if (SS.isInvalid()) { 10387 Name = 0; 10388 goto CreateNewDecl; 10389 } 10390 10391 // If this is a friend or a reference to a class in a dependent 10392 // context, don't try to make a decl for it. 10393 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10394 DC = computeDeclContext(SS, false); 10395 if (!DC) { 10396 IsDependent = true; 10397 return 0; 10398 } 10399 } else { 10400 DC = computeDeclContext(SS, true); 10401 if (!DC) { 10402 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10403 << SS.getRange(); 10404 return 0; 10405 } 10406 } 10407 10408 if (RequireCompleteDeclContext(SS, DC)) 10409 return 0; 10410 10411 SearchDC = DC; 10412 // Look-up name inside 'foo::'. 10413 LookupQualifiedName(Previous, DC); 10414 10415 if (Previous.isAmbiguous()) 10416 return 0; 10417 10418 if (Previous.empty()) { 10419 // Name lookup did not find anything. However, if the 10420 // nested-name-specifier refers to the current instantiation, 10421 // and that current instantiation has any dependent base 10422 // classes, we might find something at instantiation time: treat 10423 // this as a dependent elaborated-type-specifier. 10424 // But this only makes any sense for reference-like lookups. 10425 if (Previous.wasNotFoundInCurrentInstantiation() && 10426 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10427 IsDependent = true; 10428 return 0; 10429 } 10430 10431 // A tag 'foo::bar' must already exist. 10432 Diag(NameLoc, diag::err_not_tag_in_scope) 10433 << Kind << Name << DC << SS.getRange(); 10434 Name = 0; 10435 Invalid = true; 10436 goto CreateNewDecl; 10437 } 10438 } else if (Name) { 10439 // If this is a named struct, check to see if there was a previous forward 10440 // declaration or definition. 10441 // FIXME: We're looking into outer scopes here, even when we 10442 // shouldn't be. Doing so can result in ambiguities that we 10443 // shouldn't be diagnosing. 10444 LookupName(Previous, S); 10445 10446 // When declaring or defining a tag, ignore ambiguities introduced 10447 // by types using'ed into this scope. 10448 if (Previous.isAmbiguous() && 10449 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10450 LookupResult::Filter F = Previous.makeFilter(); 10451 while (F.hasNext()) { 10452 NamedDecl *ND = F.next(); 10453 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10454 F.erase(); 10455 } 10456 F.done(); 10457 } 10458 10459 // C++11 [namespace.memdef]p3: 10460 // If the name in a friend declaration is neither qualified nor 10461 // a template-id and the declaration is a function or an 10462 // elaborated-type-specifier, the lookup to determine whether 10463 // the entity has been previously declared shall not consider 10464 // any scopes outside the innermost enclosing namespace. 10465 // 10466 // Does it matter that this should be by scope instead of by 10467 // semantic context? 10468 if (!Previous.empty() && TUK == TUK_Friend) { 10469 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10470 LookupResult::Filter F = Previous.makeFilter(); 10471 while (F.hasNext()) { 10472 NamedDecl *ND = F.next(); 10473 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10474 if (DC->isFileContext() && 10475 !EnclosingNS->Encloses(ND->getDeclContext())) { 10476 F.erase(); 10477 FriendSawTagOutsideEnclosingNamespace = true; 10478 } 10479 } 10480 F.done(); 10481 } 10482 10483 // Note: there used to be some attempt at recovery here. 10484 if (Previous.isAmbiguous()) 10485 return 0; 10486 10487 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10488 // FIXME: This makes sure that we ignore the contexts associated 10489 // with C structs, unions, and enums when looking for a matching 10490 // tag declaration or definition. See the similar lookup tweak 10491 // in Sema::LookupName; is there a better way to deal with this? 10492 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10493 SearchDC = SearchDC->getParent(); 10494 } 10495 } else if (S->isFunctionPrototypeScope()) { 10496 // If this is an enum declaration in function prototype scope, set its 10497 // initial context to the translation unit. 10498 // FIXME: [citation needed] 10499 SearchDC = Context.getTranslationUnitDecl(); 10500 } 10501 10502 if (Previous.isSingleResult() && 10503 Previous.getFoundDecl()->isTemplateParameter()) { 10504 // Maybe we will complain about the shadowed template parameter. 10505 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10506 // Just pretend that we didn't see the previous declaration. 10507 Previous.clear(); 10508 } 10509 10510 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10511 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10512 // This is a declaration of or a reference to "std::bad_alloc". 10513 isStdBadAlloc = true; 10514 10515 if (Previous.empty() && StdBadAlloc) { 10516 // std::bad_alloc has been implicitly declared (but made invisible to 10517 // name lookup). Fill in this implicit declaration as the previous 10518 // declaration, so that the declarations get chained appropriately. 10519 Previous.addDecl(getStdBadAlloc()); 10520 } 10521 } 10522 10523 // If we didn't find a previous declaration, and this is a reference 10524 // (or friend reference), move to the correct scope. In C++, we 10525 // also need to do a redeclaration lookup there, just in case 10526 // there's a shadow friend decl. 10527 if (Name && Previous.empty() && 10528 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10529 if (Invalid) goto CreateNewDecl; 10530 assert(SS.isEmpty()); 10531 10532 if (TUK == TUK_Reference) { 10533 // C++ [basic.scope.pdecl]p5: 10534 // -- for an elaborated-type-specifier of the form 10535 // 10536 // class-key identifier 10537 // 10538 // if the elaborated-type-specifier is used in the 10539 // decl-specifier-seq or parameter-declaration-clause of a 10540 // function defined in namespace scope, the identifier is 10541 // declared as a class-name in the namespace that contains 10542 // the declaration; otherwise, except as a friend 10543 // declaration, the identifier is declared in the smallest 10544 // non-class, non-function-prototype scope that contains the 10545 // declaration. 10546 // 10547 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10548 // C structs and unions. 10549 // 10550 // It is an error in C++ to declare (rather than define) an enum 10551 // type, including via an elaborated type specifier. We'll 10552 // diagnose that later; for now, declare the enum in the same 10553 // scope as we would have picked for any other tag type. 10554 // 10555 // GNU C also supports this behavior as part of its incomplete 10556 // enum types extension, while GNU C++ does not. 10557 // 10558 // Find the context where we'll be declaring the tag. 10559 // FIXME: We would like to maintain the current DeclContext as the 10560 // lexical context, 10561 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10562 SearchDC = SearchDC->getParent(); 10563 10564 // Find the scope where we'll be declaring the tag. 10565 while (S->isClassScope() || 10566 (getLangOpts().CPlusPlus && 10567 S->isFunctionPrototypeScope()) || 10568 ((S->getFlags() & Scope::DeclScope) == 0) || 10569 (S->getEntity() && S->getEntity()->isTransparentContext())) 10570 S = S->getParent(); 10571 } else { 10572 assert(TUK == TUK_Friend); 10573 // C++ [namespace.memdef]p3: 10574 // If a friend declaration in a non-local class first declares a 10575 // class or function, the friend class or function is a member of 10576 // the innermost enclosing namespace. 10577 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10578 } 10579 10580 // In C++, we need to do a redeclaration lookup to properly 10581 // diagnose some problems. 10582 if (getLangOpts().CPlusPlus) { 10583 Previous.setRedeclarationKind(ForRedeclaration); 10584 LookupQualifiedName(Previous, SearchDC); 10585 } 10586 } 10587 10588 if (!Previous.empty()) { 10589 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 10590 10591 // It's okay to have a tag decl in the same scope as a typedef 10592 // which hides a tag decl in the same scope. Finding this 10593 // insanity with a redeclaration lookup can only actually happen 10594 // in C++. 10595 // 10596 // This is also okay for elaborated-type-specifiers, which is 10597 // technically forbidden by the current standard but which is 10598 // okay according to the likely resolution of an open issue; 10599 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10600 if (getLangOpts().CPlusPlus) { 10601 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10602 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10603 TagDecl *Tag = TT->getDecl(); 10604 if (Tag->getDeclName() == Name && 10605 Tag->getDeclContext()->getRedeclContext() 10606 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10607 PrevDecl = Tag; 10608 Previous.clear(); 10609 Previous.addDecl(Tag); 10610 Previous.resolveKind(); 10611 } 10612 } 10613 } 10614 } 10615 10616 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10617 // If this is a use of a previous tag, or if the tag is already declared 10618 // in the same scope (so that the definition/declaration completes or 10619 // rementions the tag), reuse the decl. 10620 if (TUK == TUK_Reference || TUK == TUK_Friend || 10621 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 10622 // Make sure that this wasn't declared as an enum and now used as a 10623 // struct or something similar. 10624 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10625 TUK == TUK_Definition, KWLoc, 10626 *Name)) { 10627 bool SafeToContinue 10628 = (PrevTagDecl->getTagKind() != TTK_Enum && 10629 Kind != TTK_Enum); 10630 if (SafeToContinue) 10631 Diag(KWLoc, diag::err_use_with_wrong_tag) 10632 << Name 10633 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10634 PrevTagDecl->getKindName()); 10635 else 10636 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10637 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10638 10639 if (SafeToContinue) 10640 Kind = PrevTagDecl->getTagKind(); 10641 else { 10642 // Recover by making this an anonymous redefinition. 10643 Name = 0; 10644 Previous.clear(); 10645 Invalid = true; 10646 } 10647 } 10648 10649 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10650 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10651 10652 // If this is an elaborated-type-specifier for a scoped enumeration, 10653 // the 'class' keyword is not necessary and not permitted. 10654 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10655 if (ScopedEnum) 10656 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10657 << PrevEnum->isScoped() 10658 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10659 return PrevTagDecl; 10660 } 10661 10662 QualType EnumUnderlyingTy; 10663 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10664 EnumUnderlyingTy = TI->getType(); 10665 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10666 EnumUnderlyingTy = QualType(T, 0); 10667 10668 // All conflicts with previous declarations are recovered by 10669 // returning the previous declaration, unless this is a definition, 10670 // in which case we want the caller to bail out. 10671 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10672 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10673 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10674 } 10675 10676 // C++11 [class.mem]p1: 10677 // A member shall not be declared twice in the member-specification, 10678 // except that a nested class or member class template can be declared 10679 // and then later defined. 10680 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10681 S->isDeclScope(PrevDecl)) { 10682 Diag(NameLoc, diag::ext_member_redeclared); 10683 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10684 } 10685 10686 if (!Invalid) { 10687 // If this is a use, just return the declaration we found. 10688 10689 // FIXME: In the future, return a variant or some other clue 10690 // for the consumer of this Decl to know it doesn't own it. 10691 // For our current ASTs this shouldn't be a problem, but will 10692 // need to be changed with DeclGroups. 10693 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10694 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10695 return PrevTagDecl; 10696 10697 // Diagnose attempts to redefine a tag. 10698 if (TUK == TUK_Definition) { 10699 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10700 // If we're defining a specialization and the previous definition 10701 // is from an implicit instantiation, don't emit an error 10702 // here; we'll catch this in the general case below. 10703 bool IsExplicitSpecializationAfterInstantiation = false; 10704 if (isExplicitSpecialization) { 10705 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10706 IsExplicitSpecializationAfterInstantiation = 10707 RD->getTemplateSpecializationKind() != 10708 TSK_ExplicitSpecialization; 10709 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10710 IsExplicitSpecializationAfterInstantiation = 10711 ED->getTemplateSpecializationKind() != 10712 TSK_ExplicitSpecialization; 10713 } 10714 10715 if (!IsExplicitSpecializationAfterInstantiation) { 10716 // A redeclaration in function prototype scope in C isn't 10717 // visible elsewhere, so merely issue a warning. 10718 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10719 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10720 else 10721 Diag(NameLoc, diag::err_redefinition) << Name; 10722 Diag(Def->getLocation(), diag::note_previous_definition); 10723 // If this is a redefinition, recover by making this 10724 // struct be anonymous, which will make any later 10725 // references get the previous definition. 10726 Name = 0; 10727 Previous.clear(); 10728 Invalid = true; 10729 } 10730 } else { 10731 // If the type is currently being defined, complain 10732 // about a nested redefinition. 10733 const TagType *Tag 10734 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10735 if (Tag->isBeingDefined()) { 10736 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10737 Diag(PrevTagDecl->getLocation(), 10738 diag::note_previous_definition); 10739 Name = 0; 10740 Previous.clear(); 10741 Invalid = true; 10742 } 10743 } 10744 10745 // Okay, this is definition of a previously declared or referenced 10746 // tag PrevDecl. We're going to create a new Decl for it. 10747 } 10748 } 10749 // If we get here we have (another) forward declaration or we 10750 // have a definition. Just create a new decl. 10751 10752 } else { 10753 // If we get here, this is a definition of a new tag type in a nested 10754 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10755 // new decl/type. We set PrevDecl to NULL so that the entities 10756 // have distinct types. 10757 Previous.clear(); 10758 } 10759 // If we get here, we're going to create a new Decl. If PrevDecl 10760 // is non-NULL, it's a definition of the tag declared by 10761 // PrevDecl. If it's NULL, we have a new definition. 10762 10763 10764 // Otherwise, PrevDecl is not a tag, but was found with tag 10765 // lookup. This is only actually possible in C++, where a few 10766 // things like templates still live in the tag namespace. 10767 } else { 10768 // Use a better diagnostic if an elaborated-type-specifier 10769 // found the wrong kind of type on the first 10770 // (non-redeclaration) lookup. 10771 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10772 !Previous.isForRedeclaration()) { 10773 unsigned Kind = 0; 10774 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10775 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10776 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10777 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10778 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10779 Invalid = true; 10780 10781 // Otherwise, only diagnose if the declaration is in scope. 10782 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10783 isExplicitSpecialization)) { 10784 // do nothing 10785 10786 // Diagnose implicit declarations introduced by elaborated types. 10787 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10788 unsigned Kind = 0; 10789 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10790 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10791 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10792 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10793 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10794 Invalid = true; 10795 10796 // Otherwise it's a declaration. Call out a particularly common 10797 // case here. 10798 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10799 unsigned Kind = 0; 10800 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10801 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10802 << Name << Kind << TND->getUnderlyingType(); 10803 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10804 Invalid = true; 10805 10806 // Otherwise, diagnose. 10807 } else { 10808 // The tag name clashes with something else in the target scope, 10809 // issue an error and recover by making this tag be anonymous. 10810 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10811 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10812 Name = 0; 10813 Invalid = true; 10814 } 10815 10816 // The existing declaration isn't relevant to us; we're in a 10817 // new scope, so clear out the previous declaration. 10818 Previous.clear(); 10819 } 10820 } 10821 10822CreateNewDecl: 10823 10824 TagDecl *PrevDecl = 0; 10825 if (Previous.isSingleResult()) 10826 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10827 10828 // If there is an identifier, use the location of the identifier as the 10829 // location of the decl, otherwise use the location of the struct/union 10830 // keyword. 10831 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10832 10833 // Otherwise, create a new declaration. If there is a previous 10834 // declaration of the same entity, the two will be linked via 10835 // PrevDecl. 10836 TagDecl *New; 10837 10838 bool IsForwardReference = false; 10839 if (Kind == TTK_Enum) { 10840 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10841 // enum X { A, B, C } D; D should chain to X. 10842 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10843 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10844 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10845 // If this is an undefined enum, warn. 10846 if (TUK != TUK_Definition && !Invalid) { 10847 TagDecl *Def; 10848 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10849 cast<EnumDecl>(New)->isFixed()) { 10850 // C++0x: 7.2p2: opaque-enum-declaration. 10851 // Conflicts are diagnosed above. Do nothing. 10852 } 10853 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10854 Diag(Loc, diag::ext_forward_ref_enum_def) 10855 << New; 10856 Diag(Def->getLocation(), diag::note_previous_definition); 10857 } else { 10858 unsigned DiagID = diag::ext_forward_ref_enum; 10859 if (getLangOpts().MicrosoftMode) 10860 DiagID = diag::ext_ms_forward_ref_enum; 10861 else if (getLangOpts().CPlusPlus) 10862 DiagID = diag::err_forward_ref_enum; 10863 Diag(Loc, DiagID); 10864 10865 // If this is a forward-declared reference to an enumeration, make a 10866 // note of it; we won't actually be introducing the declaration into 10867 // the declaration context. 10868 if (TUK == TUK_Reference) 10869 IsForwardReference = true; 10870 } 10871 } 10872 10873 if (EnumUnderlying) { 10874 EnumDecl *ED = cast<EnumDecl>(New); 10875 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10876 ED->setIntegerTypeSourceInfo(TI); 10877 else 10878 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10879 ED->setPromotionType(ED->getIntegerType()); 10880 } 10881 10882 } else { 10883 // struct/union/class 10884 10885 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10886 // struct X { int A; } D; D should chain to X. 10887 if (getLangOpts().CPlusPlus) { 10888 // FIXME: Look for a way to use RecordDecl for simple structs. 10889 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10890 cast_or_null<CXXRecordDecl>(PrevDecl)); 10891 10892 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10893 StdBadAlloc = cast<CXXRecordDecl>(New); 10894 } else 10895 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10896 cast_or_null<RecordDecl>(PrevDecl)); 10897 } 10898 10899 // Maybe add qualifier info. 10900 if (SS.isNotEmpty()) { 10901 if (SS.isSet()) { 10902 // If this is either a declaration or a definition, check the 10903 // nested-name-specifier against the current context. We don't do this 10904 // for explicit specializations, because they have similar checking 10905 // (with more specific diagnostics) in the call to 10906 // CheckMemberSpecialization, below. 10907 if (!isExplicitSpecialization && 10908 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10909 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10910 Invalid = true; 10911 10912 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10913 if (TemplateParameterLists.size() > 0) { 10914 New->setTemplateParameterListsInfo(Context, 10915 TemplateParameterLists.size(), 10916 TemplateParameterLists.data()); 10917 } 10918 } 10919 else 10920 Invalid = true; 10921 } 10922 10923 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 10924 // Add alignment attributes if necessary; these attributes are checked when 10925 // the ASTContext lays out the structure. 10926 // 10927 // It is important for implementing the correct semantics that this 10928 // happen here (in act on tag decl). The #pragma pack stack is 10929 // maintained as a result of parser callbacks which can occur at 10930 // many points during the parsing of a struct declaration (because 10931 // the #pragma tokens are effectively skipped over during the 10932 // parsing of the struct). 10933 if (TUK == TUK_Definition) { 10934 AddAlignmentAttributesForRecord(RD); 10935 AddMsStructLayoutForRecord(RD); 10936 } 10937 } 10938 10939 if (ModulePrivateLoc.isValid()) { 10940 if (isExplicitSpecialization) 10941 Diag(New->getLocation(), diag::err_module_private_specialization) 10942 << 2 10943 << FixItHint::CreateRemoval(ModulePrivateLoc); 10944 // __module_private__ does not apply to local classes. However, we only 10945 // diagnose this as an error when the declaration specifiers are 10946 // freestanding. Here, we just ignore the __module_private__. 10947 else if (!SearchDC->isFunctionOrMethod()) 10948 New->setModulePrivate(); 10949 } 10950 10951 // If this is a specialization of a member class (of a class template), 10952 // check the specialization. 10953 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 10954 Invalid = true; 10955 10956 if (Invalid) 10957 New->setInvalidDecl(); 10958 10959 if (Attr) 10960 ProcessDeclAttributeList(S, New, Attr); 10961 10962 // If we're declaring or defining a tag in function prototype scope 10963 // in C, note that this type can only be used within the function. 10964 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 10965 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 10966 10967 // Set the lexical context. If the tag has a C++ scope specifier, the 10968 // lexical context will be different from the semantic context. 10969 New->setLexicalDeclContext(CurContext); 10970 10971 // Mark this as a friend decl if applicable. 10972 // In Microsoft mode, a friend declaration also acts as a forward 10973 // declaration so we always pass true to setObjectOfFriendDecl to make 10974 // the tag name visible. 10975 if (TUK == TUK_Friend) 10976 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 10977 getLangOpts().MicrosoftExt); 10978 10979 // Set the access specifier. 10980 if (!Invalid && SearchDC->isRecord()) 10981 SetMemberAccessSpecifier(New, PrevDecl, AS); 10982 10983 if (TUK == TUK_Definition) 10984 New->startDefinition(); 10985 10986 // If this has an identifier, add it to the scope stack. 10987 if (TUK == TUK_Friend) { 10988 // We might be replacing an existing declaration in the lookup tables; 10989 // if so, borrow its access specifier. 10990 if (PrevDecl) 10991 New->setAccess(PrevDecl->getAccess()); 10992 10993 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 10994 DC->makeDeclVisibleInContext(New); 10995 if (Name) // can be null along some error paths 10996 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10997 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 10998 } else if (Name) { 10999 S = getNonFieldDeclScope(S); 11000 PushOnScopeChains(New, S, !IsForwardReference); 11001 if (IsForwardReference) 11002 SearchDC->makeDeclVisibleInContext(New); 11003 11004 } else { 11005 CurContext->addDecl(New); 11006 } 11007 11008 // If this is the C FILE type, notify the AST context. 11009 if (IdentifierInfo *II = New->getIdentifier()) 11010 if (!New->isInvalidDecl() && 11011 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11012 II->isStr("FILE")) 11013 Context.setFILEDecl(New); 11014 11015 // If we were in function prototype scope (and not in C++ mode), add this 11016 // tag to the list of decls to inject into the function definition scope. 11017 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11018 InFunctionDeclarator && Name) 11019 DeclsInPrototypeScope.push_back(New); 11020 11021 if (PrevDecl) 11022 mergeDeclAttributes(New, PrevDecl); 11023 11024 // If there's a #pragma GCC visibility in scope, set the visibility of this 11025 // record. 11026 AddPushedVisibilityAttribute(New); 11027 11028 OwnedDecl = true; 11029 // In C++, don't return an invalid declaration. We can't recover well from 11030 // the cases where we make the type anonymous. 11031 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11032} 11033 11034void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11035 AdjustDeclIfTemplate(TagD); 11036 TagDecl *Tag = cast<TagDecl>(TagD); 11037 11038 // Enter the tag context. 11039 PushDeclContext(S, Tag); 11040 11041 ActOnDocumentableDecl(TagD); 11042 11043 // If there's a #pragma GCC visibility in scope, set the visibility of this 11044 // record. 11045 AddPushedVisibilityAttribute(Tag); 11046} 11047 11048Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11049 assert(isa<ObjCContainerDecl>(IDecl) && 11050 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11051 DeclContext *OCD = cast<DeclContext>(IDecl); 11052 assert(getContainingDC(OCD) == CurContext && 11053 "The next DeclContext should be lexically contained in the current one."); 11054 CurContext = OCD; 11055 return IDecl; 11056} 11057 11058void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11059 SourceLocation FinalLoc, 11060 bool IsFinalSpelledSealed, 11061 SourceLocation LBraceLoc) { 11062 AdjustDeclIfTemplate(TagD); 11063 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11064 11065 FieldCollector->StartClass(); 11066 11067 if (!Record->getIdentifier()) 11068 return; 11069 11070 if (FinalLoc.isValid()) 11071 Record->addAttr(new (Context) 11072 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11073 11074 // C++ [class]p2: 11075 // [...] The class-name is also inserted into the scope of the 11076 // class itself; this is known as the injected-class-name. For 11077 // purposes of access checking, the injected-class-name is treated 11078 // as if it were a public member name. 11079 CXXRecordDecl *InjectedClassName 11080 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11081 Record->getLocStart(), Record->getLocation(), 11082 Record->getIdentifier(), 11083 /*PrevDecl=*/0, 11084 /*DelayTypeCreation=*/true); 11085 Context.getTypeDeclType(InjectedClassName, Record); 11086 InjectedClassName->setImplicit(); 11087 InjectedClassName->setAccess(AS_public); 11088 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11089 InjectedClassName->setDescribedClassTemplate(Template); 11090 PushOnScopeChains(InjectedClassName, S); 11091 assert(InjectedClassName->isInjectedClassName() && 11092 "Broken injected-class-name"); 11093} 11094 11095void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11096 SourceLocation RBraceLoc) { 11097 AdjustDeclIfTemplate(TagD); 11098 TagDecl *Tag = cast<TagDecl>(TagD); 11099 Tag->setRBraceLoc(RBraceLoc); 11100 11101 // Make sure we "complete" the definition even it is invalid. 11102 if (Tag->isBeingDefined()) { 11103 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11104 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11105 RD->completeDefinition(); 11106 } 11107 11108 if (isa<CXXRecordDecl>(Tag)) 11109 FieldCollector->FinishClass(); 11110 11111 // Exit this scope of this tag's definition. 11112 PopDeclContext(); 11113 11114 if (getCurLexicalContext()->isObjCContainer() && 11115 Tag->getDeclContext()->isFileContext()) 11116 Tag->setTopLevelDeclInObjCContainer(); 11117 11118 // Notify the consumer that we've defined a tag. 11119 if (!Tag->isInvalidDecl()) 11120 Consumer.HandleTagDeclDefinition(Tag); 11121} 11122 11123void Sema::ActOnObjCContainerFinishDefinition() { 11124 // Exit this scope of this interface definition. 11125 PopDeclContext(); 11126} 11127 11128void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11129 assert(DC == CurContext && "Mismatch of container contexts"); 11130 OriginalLexicalContext = DC; 11131 ActOnObjCContainerFinishDefinition(); 11132} 11133 11134void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11135 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11136 OriginalLexicalContext = 0; 11137} 11138 11139void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11140 AdjustDeclIfTemplate(TagD); 11141 TagDecl *Tag = cast<TagDecl>(TagD); 11142 Tag->setInvalidDecl(); 11143 11144 // Make sure we "complete" the definition even it is invalid. 11145 if (Tag->isBeingDefined()) { 11146 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11147 RD->completeDefinition(); 11148 } 11149 11150 // We're undoing ActOnTagStartDefinition here, not 11151 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11152 // the FieldCollector. 11153 11154 PopDeclContext(); 11155} 11156 11157// Note that FieldName may be null for anonymous bitfields. 11158ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11159 IdentifierInfo *FieldName, 11160 QualType FieldTy, bool IsMsStruct, 11161 Expr *BitWidth, bool *ZeroWidth) { 11162 // Default to true; that shouldn't confuse checks for emptiness 11163 if (ZeroWidth) 11164 *ZeroWidth = true; 11165 11166 // C99 6.7.2.1p4 - verify the field type. 11167 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11168 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11169 // Handle incomplete types with specific error. 11170 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11171 return ExprError(); 11172 if (FieldName) 11173 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11174 << FieldName << FieldTy << BitWidth->getSourceRange(); 11175 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11176 << FieldTy << BitWidth->getSourceRange(); 11177 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11178 UPPC_BitFieldWidth)) 11179 return ExprError(); 11180 11181 // If the bit-width is type- or value-dependent, don't try to check 11182 // it now. 11183 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11184 return Owned(BitWidth); 11185 11186 llvm::APSInt Value; 11187 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11188 if (ICE.isInvalid()) 11189 return ICE; 11190 BitWidth = ICE.take(); 11191 11192 if (Value != 0 && ZeroWidth) 11193 *ZeroWidth = false; 11194 11195 // Zero-width bitfield is ok for anonymous field. 11196 if (Value == 0 && FieldName) 11197 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11198 11199 if (Value.isSigned() && Value.isNegative()) { 11200 if (FieldName) 11201 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11202 << FieldName << Value.toString(10); 11203 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11204 << Value.toString(10); 11205 } 11206 11207 if (!FieldTy->isDependentType()) { 11208 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11209 if (Value.getZExtValue() > TypeSize) { 11210 if (!getLangOpts().CPlusPlus || IsMsStruct) { 11211 if (FieldName) 11212 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11213 << FieldName << (unsigned)Value.getZExtValue() 11214 << (unsigned)TypeSize; 11215 11216 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11217 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11218 } 11219 11220 if (FieldName) 11221 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11222 << FieldName << (unsigned)Value.getZExtValue() 11223 << (unsigned)TypeSize; 11224 else 11225 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11226 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11227 } 11228 } 11229 11230 return Owned(BitWidth); 11231} 11232 11233/// ActOnField - Each field of a C struct/union is passed into this in order 11234/// to create a FieldDecl object for it. 11235Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11236 Declarator &D, Expr *BitfieldWidth) { 11237 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11238 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11239 /*InitStyle=*/ICIS_NoInit, AS_public); 11240 return Res; 11241} 11242 11243/// HandleField - Analyze a field of a C struct or a C++ data member. 11244/// 11245FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11246 SourceLocation DeclStart, 11247 Declarator &D, Expr *BitWidth, 11248 InClassInitStyle InitStyle, 11249 AccessSpecifier AS) { 11250 IdentifierInfo *II = D.getIdentifier(); 11251 SourceLocation Loc = DeclStart; 11252 if (II) Loc = D.getIdentifierLoc(); 11253 11254 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11255 QualType T = TInfo->getType(); 11256 if (getLangOpts().CPlusPlus) { 11257 CheckExtraCXXDefaultArguments(D); 11258 11259 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11260 UPPC_DataMemberType)) { 11261 D.setInvalidType(); 11262 T = Context.IntTy; 11263 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11264 } 11265 } 11266 11267 // TR 18037 does not allow fields to be declared with address spaces. 11268 if (T.getQualifiers().hasAddressSpace()) { 11269 Diag(Loc, diag::err_field_with_address_space); 11270 D.setInvalidType(); 11271 } 11272 11273 // OpenCL 1.2 spec, s6.9 r: 11274 // The event type cannot be used to declare a structure or union field. 11275 if (LangOpts.OpenCL && T->isEventT()) { 11276 Diag(Loc, diag::err_event_t_struct_field); 11277 D.setInvalidType(); 11278 } 11279 11280 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11281 11282 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11283 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11284 diag::err_invalid_thread) 11285 << DeclSpec::getSpecifierName(TSCS); 11286 11287 // Check to see if this name was declared as a member previously 11288 NamedDecl *PrevDecl = 0; 11289 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11290 LookupName(Previous, S); 11291 switch (Previous.getResultKind()) { 11292 case LookupResult::Found: 11293 case LookupResult::FoundUnresolvedValue: 11294 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11295 break; 11296 11297 case LookupResult::FoundOverloaded: 11298 PrevDecl = Previous.getRepresentativeDecl(); 11299 break; 11300 11301 case LookupResult::NotFound: 11302 case LookupResult::NotFoundInCurrentInstantiation: 11303 case LookupResult::Ambiguous: 11304 break; 11305 } 11306 Previous.suppressDiagnostics(); 11307 11308 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11309 // Maybe we will complain about the shadowed template parameter. 11310 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11311 // Just pretend that we didn't see the previous declaration. 11312 PrevDecl = 0; 11313 } 11314 11315 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11316 PrevDecl = 0; 11317 11318 bool Mutable 11319 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11320 SourceLocation TSSL = D.getLocStart(); 11321 FieldDecl *NewFD 11322 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11323 TSSL, AS, PrevDecl, &D); 11324 11325 if (NewFD->isInvalidDecl()) 11326 Record->setInvalidDecl(); 11327 11328 if (D.getDeclSpec().isModulePrivateSpecified()) 11329 NewFD->setModulePrivate(); 11330 11331 if (NewFD->isInvalidDecl() && PrevDecl) { 11332 // Don't introduce NewFD into scope; there's already something 11333 // with the same name in the same scope. 11334 } else if (II) { 11335 PushOnScopeChains(NewFD, S); 11336 } else 11337 Record->addDecl(NewFD); 11338 11339 return NewFD; 11340} 11341 11342/// \brief Build a new FieldDecl and check its well-formedness. 11343/// 11344/// This routine builds a new FieldDecl given the fields name, type, 11345/// record, etc. \p PrevDecl should refer to any previous declaration 11346/// with the same name and in the same scope as the field to be 11347/// created. 11348/// 11349/// \returns a new FieldDecl. 11350/// 11351/// \todo The Declarator argument is a hack. It will be removed once 11352FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11353 TypeSourceInfo *TInfo, 11354 RecordDecl *Record, SourceLocation Loc, 11355 bool Mutable, Expr *BitWidth, 11356 InClassInitStyle InitStyle, 11357 SourceLocation TSSL, 11358 AccessSpecifier AS, NamedDecl *PrevDecl, 11359 Declarator *D) { 11360 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11361 bool InvalidDecl = false; 11362 if (D) InvalidDecl = D->isInvalidType(); 11363 11364 // If we receive a broken type, recover by assuming 'int' and 11365 // marking this declaration as invalid. 11366 if (T.isNull()) { 11367 InvalidDecl = true; 11368 T = Context.IntTy; 11369 } 11370 11371 QualType EltTy = Context.getBaseElementType(T); 11372 if (!EltTy->isDependentType()) { 11373 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11374 // Fields of incomplete type force their record to be invalid. 11375 Record->setInvalidDecl(); 11376 InvalidDecl = true; 11377 } else { 11378 NamedDecl *Def; 11379 EltTy->isIncompleteType(&Def); 11380 if (Def && Def->isInvalidDecl()) { 11381 Record->setInvalidDecl(); 11382 InvalidDecl = true; 11383 } 11384 } 11385 } 11386 11387 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11388 if (BitWidth && getLangOpts().OpenCL) { 11389 Diag(Loc, diag::err_opencl_bitfields); 11390 InvalidDecl = true; 11391 } 11392 11393 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11394 // than a variably modified type. 11395 if (!InvalidDecl && T->isVariablyModifiedType()) { 11396 bool SizeIsNegative; 11397 llvm::APSInt Oversized; 11398 11399 TypeSourceInfo *FixedTInfo = 11400 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11401 SizeIsNegative, 11402 Oversized); 11403 if (FixedTInfo) { 11404 Diag(Loc, diag::warn_illegal_constant_array_size); 11405 TInfo = FixedTInfo; 11406 T = FixedTInfo->getType(); 11407 } else { 11408 if (SizeIsNegative) 11409 Diag(Loc, diag::err_typecheck_negative_array_size); 11410 else if (Oversized.getBoolValue()) 11411 Diag(Loc, diag::err_array_too_large) 11412 << Oversized.toString(10); 11413 else 11414 Diag(Loc, diag::err_typecheck_field_variable_size); 11415 InvalidDecl = true; 11416 } 11417 } 11418 11419 // Fields can not have abstract class types 11420 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11421 diag::err_abstract_type_in_decl, 11422 AbstractFieldType)) 11423 InvalidDecl = true; 11424 11425 bool ZeroWidth = false; 11426 // If this is declared as a bit-field, check the bit-field. 11427 if (!InvalidDecl && BitWidth) { 11428 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11429 &ZeroWidth).take(); 11430 if (!BitWidth) { 11431 InvalidDecl = true; 11432 BitWidth = 0; 11433 ZeroWidth = false; 11434 } 11435 } 11436 11437 // Check that 'mutable' is consistent with the type of the declaration. 11438 if (!InvalidDecl && Mutable) { 11439 unsigned DiagID = 0; 11440 if (T->isReferenceType()) 11441 DiagID = diag::err_mutable_reference; 11442 else if (T.isConstQualified()) 11443 DiagID = diag::err_mutable_const; 11444 11445 if (DiagID) { 11446 SourceLocation ErrLoc = Loc; 11447 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11448 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11449 Diag(ErrLoc, DiagID); 11450 Mutable = false; 11451 InvalidDecl = true; 11452 } 11453 } 11454 11455 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11456 BitWidth, Mutable, InitStyle); 11457 if (InvalidDecl) 11458 NewFD->setInvalidDecl(); 11459 11460 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11461 Diag(Loc, diag::err_duplicate_member) << II; 11462 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11463 NewFD->setInvalidDecl(); 11464 } 11465 11466 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11467 if (Record->isUnion()) { 11468 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11469 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11470 if (RDecl->getDefinition()) { 11471 // C++ [class.union]p1: An object of a class with a non-trivial 11472 // constructor, a non-trivial copy constructor, a non-trivial 11473 // destructor, or a non-trivial copy assignment operator 11474 // cannot be a member of a union, nor can an array of such 11475 // objects. 11476 if (CheckNontrivialField(NewFD)) 11477 NewFD->setInvalidDecl(); 11478 } 11479 } 11480 11481 // C++ [class.union]p1: If a union contains a member of reference type, 11482 // the program is ill-formed, except when compiling with MSVC extensions 11483 // enabled. 11484 if (EltTy->isReferenceType()) { 11485 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11486 diag::ext_union_member_of_reference_type : 11487 diag::err_union_member_of_reference_type) 11488 << NewFD->getDeclName() << EltTy; 11489 if (!getLangOpts().MicrosoftExt) 11490 NewFD->setInvalidDecl(); 11491 } 11492 } 11493 } 11494 11495 // FIXME: We need to pass in the attributes given an AST 11496 // representation, not a parser representation. 11497 if (D) { 11498 // FIXME: The current scope is almost... but not entirely... correct here. 11499 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11500 11501 if (NewFD->hasAttrs()) 11502 CheckAlignasUnderalignment(NewFD); 11503 } 11504 11505 // In auto-retain/release, infer strong retension for fields of 11506 // retainable type. 11507 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11508 NewFD->setInvalidDecl(); 11509 11510 if (T.isObjCGCWeak()) 11511 Diag(Loc, diag::warn_attribute_weak_on_field); 11512 11513 NewFD->setAccess(AS); 11514 return NewFD; 11515} 11516 11517bool Sema::CheckNontrivialField(FieldDecl *FD) { 11518 assert(FD); 11519 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11520 11521 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11522 return false; 11523 11524 QualType EltTy = Context.getBaseElementType(FD->getType()); 11525 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11526 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11527 if (RDecl->getDefinition()) { 11528 // We check for copy constructors before constructors 11529 // because otherwise we'll never get complaints about 11530 // copy constructors. 11531 11532 CXXSpecialMember member = CXXInvalid; 11533 // We're required to check for any non-trivial constructors. Since the 11534 // implicit default constructor is suppressed if there are any 11535 // user-declared constructors, we just need to check that there is a 11536 // trivial default constructor and a trivial copy constructor. (We don't 11537 // worry about move constructors here, since this is a C++98 check.) 11538 if (RDecl->hasNonTrivialCopyConstructor()) 11539 member = CXXCopyConstructor; 11540 else if (!RDecl->hasTrivialDefaultConstructor()) 11541 member = CXXDefaultConstructor; 11542 else if (RDecl->hasNonTrivialCopyAssignment()) 11543 member = CXXCopyAssignment; 11544 else if (RDecl->hasNonTrivialDestructor()) 11545 member = CXXDestructor; 11546 11547 if (member != CXXInvalid) { 11548 if (!getLangOpts().CPlusPlus11 && 11549 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11550 // Objective-C++ ARC: it is an error to have a non-trivial field of 11551 // a union. However, system headers in Objective-C programs 11552 // occasionally have Objective-C lifetime objects within unions, 11553 // and rather than cause the program to fail, we make those 11554 // members unavailable. 11555 SourceLocation Loc = FD->getLocation(); 11556 if (getSourceManager().isInSystemHeader(Loc)) { 11557 if (!FD->hasAttr<UnavailableAttr>()) 11558 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 11559 "this system field has retaining ownership")); 11560 return false; 11561 } 11562 } 11563 11564 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11565 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11566 diag::err_illegal_union_or_anon_struct_member) 11567 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11568 DiagnoseNontrivial(RDecl, member); 11569 return !getLangOpts().CPlusPlus11; 11570 } 11571 } 11572 } 11573 11574 return false; 11575} 11576 11577/// TranslateIvarVisibility - Translate visibility from a token ID to an 11578/// AST enum value. 11579static ObjCIvarDecl::AccessControl 11580TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11581 switch (ivarVisibility) { 11582 default: llvm_unreachable("Unknown visitibility kind"); 11583 case tok::objc_private: return ObjCIvarDecl::Private; 11584 case tok::objc_public: return ObjCIvarDecl::Public; 11585 case tok::objc_protected: return ObjCIvarDecl::Protected; 11586 case tok::objc_package: return ObjCIvarDecl::Package; 11587 } 11588} 11589 11590/// ActOnIvar - Each ivar field of an objective-c class is passed into this 11591/// in order to create an IvarDecl object for it. 11592Decl *Sema::ActOnIvar(Scope *S, 11593 SourceLocation DeclStart, 11594 Declarator &D, Expr *BitfieldWidth, 11595 tok::ObjCKeywordKind Visibility) { 11596 11597 IdentifierInfo *II = D.getIdentifier(); 11598 Expr *BitWidth = (Expr*)BitfieldWidth; 11599 SourceLocation Loc = DeclStart; 11600 if (II) Loc = D.getIdentifierLoc(); 11601 11602 // FIXME: Unnamed fields can be handled in various different ways, for 11603 // example, unnamed unions inject all members into the struct namespace! 11604 11605 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11606 QualType T = TInfo->getType(); 11607 11608 if (BitWidth) { 11609 // 6.7.2.1p3, 6.7.2.1p4 11610 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11611 if (!BitWidth) 11612 D.setInvalidType(); 11613 } else { 11614 // Not a bitfield. 11615 11616 // validate II. 11617 11618 } 11619 if (T->isReferenceType()) { 11620 Diag(Loc, diag::err_ivar_reference_type); 11621 D.setInvalidType(); 11622 } 11623 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11624 // than a variably modified type. 11625 else if (T->isVariablyModifiedType()) { 11626 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11627 D.setInvalidType(); 11628 } 11629 11630 // Get the visibility (access control) for this ivar. 11631 ObjCIvarDecl::AccessControl ac = 11632 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11633 : ObjCIvarDecl::None; 11634 // Must set ivar's DeclContext to its enclosing interface. 11635 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11636 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11637 return 0; 11638 ObjCContainerDecl *EnclosingContext; 11639 if (ObjCImplementationDecl *IMPDecl = 11640 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11641 if (LangOpts.ObjCRuntime.isFragile()) { 11642 // Case of ivar declared in an implementation. Context is that of its class. 11643 EnclosingContext = IMPDecl->getClassInterface(); 11644 assert(EnclosingContext && "Implementation has no class interface!"); 11645 } 11646 else 11647 EnclosingContext = EnclosingDecl; 11648 } else { 11649 if (ObjCCategoryDecl *CDecl = 11650 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11651 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11652 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11653 return 0; 11654 } 11655 } 11656 EnclosingContext = EnclosingDecl; 11657 } 11658 11659 // Construct the decl. 11660 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11661 DeclStart, Loc, II, T, 11662 TInfo, ac, (Expr *)BitfieldWidth); 11663 11664 if (II) { 11665 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11666 ForRedeclaration); 11667 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11668 && !isa<TagDecl>(PrevDecl)) { 11669 Diag(Loc, diag::err_duplicate_member) << II; 11670 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11671 NewID->setInvalidDecl(); 11672 } 11673 } 11674 11675 // Process attributes attached to the ivar. 11676 ProcessDeclAttributes(S, NewID, D); 11677 11678 if (D.isInvalidType()) 11679 NewID->setInvalidDecl(); 11680 11681 // In ARC, infer 'retaining' for ivars of retainable type. 11682 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11683 NewID->setInvalidDecl(); 11684 11685 if (D.getDeclSpec().isModulePrivateSpecified()) 11686 NewID->setModulePrivate(); 11687 11688 if (II) { 11689 // FIXME: When interfaces are DeclContexts, we'll need to add 11690 // these to the interface. 11691 S->AddDecl(NewID); 11692 IdResolver.AddDecl(NewID); 11693 } 11694 11695 if (LangOpts.ObjCRuntime.isNonFragile() && 11696 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11697 Diag(Loc, diag::warn_ivars_in_interface); 11698 11699 return NewID; 11700} 11701 11702/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11703/// class and class extensions. For every class \@interface and class 11704/// extension \@interface, if the last ivar is a bitfield of any type, 11705/// then add an implicit `char :0` ivar to the end of that interface. 11706void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11707 SmallVectorImpl<Decl *> &AllIvarDecls) { 11708 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11709 return; 11710 11711 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11712 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11713 11714 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11715 return; 11716 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11717 if (!ID) { 11718 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11719 if (!CD->IsClassExtension()) 11720 return; 11721 } 11722 // No need to add this to end of @implementation. 11723 else 11724 return; 11725 } 11726 // All conditions are met. Add a new bitfield to the tail end of ivars. 11727 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11728 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11729 11730 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11731 DeclLoc, DeclLoc, 0, 11732 Context.CharTy, 11733 Context.getTrivialTypeSourceInfo(Context.CharTy, 11734 DeclLoc), 11735 ObjCIvarDecl::Private, BW, 11736 true); 11737 AllIvarDecls.push_back(Ivar); 11738} 11739 11740void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11741 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11742 SourceLocation RBrac, AttributeList *Attr) { 11743 assert(EnclosingDecl && "missing record or interface decl"); 11744 11745 // If this is an Objective-C @implementation or category and we have 11746 // new fields here we should reset the layout of the interface since 11747 // it will now change. 11748 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11749 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11750 switch (DC->getKind()) { 11751 default: break; 11752 case Decl::ObjCCategory: 11753 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11754 break; 11755 case Decl::ObjCImplementation: 11756 Context. 11757 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11758 break; 11759 } 11760 } 11761 11762 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11763 11764 // Start counting up the number of named members; make sure to include 11765 // members of anonymous structs and unions in the total. 11766 unsigned NumNamedMembers = 0; 11767 if (Record) { 11768 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11769 e = Record->decls_end(); i != e; i++) { 11770 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11771 if (IFD->getDeclName()) 11772 ++NumNamedMembers; 11773 } 11774 } 11775 11776 // Verify that all the fields are okay. 11777 SmallVector<FieldDecl*, 32> RecFields; 11778 11779 bool ARCErrReported = false; 11780 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11781 i != end; ++i) { 11782 FieldDecl *FD = cast<FieldDecl>(*i); 11783 11784 // Get the type for the field. 11785 const Type *FDTy = FD->getType().getTypePtr(); 11786 11787 if (!FD->isAnonymousStructOrUnion()) { 11788 // Remember all fields written by the user. 11789 RecFields.push_back(FD); 11790 } 11791 11792 // If the field is already invalid for some reason, don't emit more 11793 // diagnostics about it. 11794 if (FD->isInvalidDecl()) { 11795 EnclosingDecl->setInvalidDecl(); 11796 continue; 11797 } 11798 11799 // C99 6.7.2.1p2: 11800 // A structure or union shall not contain a member with 11801 // incomplete or function type (hence, a structure shall not 11802 // contain an instance of itself, but may contain a pointer to 11803 // an instance of itself), except that the last member of a 11804 // structure with more than one named member may have incomplete 11805 // array type; such a structure (and any union containing, 11806 // possibly recursively, a member that is such a structure) 11807 // shall not be a member of a structure or an element of an 11808 // array. 11809 if (FDTy->isFunctionType()) { 11810 // Field declared as a function. 11811 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11812 << FD->getDeclName(); 11813 FD->setInvalidDecl(); 11814 EnclosingDecl->setInvalidDecl(); 11815 continue; 11816 } else if (FDTy->isIncompleteArrayType() && Record && 11817 ((i + 1 == Fields.end() && !Record->isUnion()) || 11818 ((getLangOpts().MicrosoftExt || 11819 getLangOpts().CPlusPlus) && 11820 (i + 1 == Fields.end() || Record->isUnion())))) { 11821 // Flexible array member. 11822 // Microsoft and g++ is more permissive regarding flexible array. 11823 // It will accept flexible array in union and also 11824 // as the sole element of a struct/class. 11825 if (getLangOpts().MicrosoftExt) { 11826 if (Record->isUnion()) 11827 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 11828 << FD->getDeclName(); 11829 else if (Fields.size() == 1) 11830 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 11831 << FD->getDeclName() << Record->getTagKind(); 11832 else 11833 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11834 << FD->getDeclName() << Record->getTagKind(); 11835 } else if (getLangOpts().CPlusPlus) { 11836 if (Record->isUnion()) 11837 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 11838 << FD->getDeclName(); 11839 else if (Fields.size() == 1) 11840 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 11841 << FD->getDeclName() << Record->getTagKind(); 11842 else 11843 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11844 << FD->getDeclName() << Record->getTagKind(); 11845 } else if (!getLangOpts().C99) { 11846 if (Record->isUnion()) 11847 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 11848 << FD->getDeclName(); 11849 else 11850 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11851 << FD->getDeclName() << Record->getTagKind(); 11852 } else if (NumNamedMembers < 1) { 11853 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 11854 << FD->getDeclName(); 11855 FD->setInvalidDecl(); 11856 EnclosingDecl->setInvalidDecl(); 11857 continue; 11858 } 11859 if (!FD->getType()->isDependentType() && 11860 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 11861 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 11862 << FD->getDeclName() << FD->getType(); 11863 FD->setInvalidDecl(); 11864 EnclosingDecl->setInvalidDecl(); 11865 continue; 11866 } 11867 // Okay, we have a legal flexible array member at the end of the struct. 11868 if (Record) 11869 Record->setHasFlexibleArrayMember(true); 11870 } else if (!FDTy->isDependentType() && 11871 RequireCompleteType(FD->getLocation(), FD->getType(), 11872 diag::err_field_incomplete)) { 11873 // Incomplete type 11874 FD->setInvalidDecl(); 11875 EnclosingDecl->setInvalidDecl(); 11876 continue; 11877 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11878 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11879 // If this is a member of a union, then entire union becomes "flexible". 11880 if (Record && Record->isUnion()) { 11881 Record->setHasFlexibleArrayMember(true); 11882 } else { 11883 // If this is a struct/class and this is not the last element, reject 11884 // it. Note that GCC supports variable sized arrays in the middle of 11885 // structures. 11886 if (i + 1 != Fields.end()) 11887 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11888 << FD->getDeclName() << FD->getType(); 11889 else { 11890 // We support flexible arrays at the end of structs in 11891 // other structs as an extension. 11892 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11893 << FD->getDeclName(); 11894 if (Record) 11895 Record->setHasFlexibleArrayMember(true); 11896 } 11897 } 11898 } 11899 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11900 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11901 diag::err_abstract_type_in_decl, 11902 AbstractIvarType)) { 11903 // Ivars can not have abstract class types 11904 FD->setInvalidDecl(); 11905 } 11906 if (Record && FDTTy->getDecl()->hasObjectMember()) 11907 Record->setHasObjectMember(true); 11908 if (Record && FDTTy->getDecl()->hasVolatileMember()) 11909 Record->setHasVolatileMember(true); 11910 } else if (FDTy->isObjCObjectType()) { 11911 /// A field cannot be an Objective-c object 11912 Diag(FD->getLocation(), diag::err_statically_allocated_object) 11913 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 11914 QualType T = Context.getObjCObjectPointerType(FD->getType()); 11915 FD->setType(T); 11916 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 11917 (!getLangOpts().CPlusPlus || Record->isUnion())) { 11918 // It's an error in ARC if a field has lifetime. 11919 // We don't want to report this in a system header, though, 11920 // so we just make the field unavailable. 11921 // FIXME: that's really not sufficient; we need to make the type 11922 // itself invalid to, say, initialize or copy. 11923 QualType T = FD->getType(); 11924 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 11925 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 11926 SourceLocation loc = FD->getLocation(); 11927 if (getSourceManager().isInSystemHeader(loc)) { 11928 if (!FD->hasAttr<UnavailableAttr>()) { 11929 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 11930 "this system field has retaining ownership")); 11931 } 11932 } else { 11933 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 11934 << T->isBlockPointerType() << Record->getTagKind(); 11935 } 11936 ARCErrReported = true; 11937 } 11938 } else if (getLangOpts().ObjC1 && 11939 getLangOpts().getGC() != LangOptions::NonGC && 11940 Record && !Record->hasObjectMember()) { 11941 if (FD->getType()->isObjCObjectPointerType() || 11942 FD->getType().isObjCGCStrong()) 11943 Record->setHasObjectMember(true); 11944 else if (Context.getAsArrayType(FD->getType())) { 11945 QualType BaseType = Context.getBaseElementType(FD->getType()); 11946 if (BaseType->isRecordType() && 11947 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 11948 Record->setHasObjectMember(true); 11949 else if (BaseType->isObjCObjectPointerType() || 11950 BaseType.isObjCGCStrong()) 11951 Record->setHasObjectMember(true); 11952 } 11953 } 11954 if (Record && FD->getType().isVolatileQualified()) 11955 Record->setHasVolatileMember(true); 11956 // Keep track of the number of named members. 11957 if (FD->getIdentifier()) 11958 ++NumNamedMembers; 11959 } 11960 11961 // Okay, we successfully defined 'Record'. 11962 if (Record) { 11963 bool Completed = false; 11964 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 11965 if (!CXXRecord->isInvalidDecl()) { 11966 // Set access bits correctly on the directly-declared conversions. 11967 for (CXXRecordDecl::conversion_iterator 11968 I = CXXRecord->conversion_begin(), 11969 E = CXXRecord->conversion_end(); I != E; ++I) 11970 I.setAccess((*I)->getAccess()); 11971 11972 if (!CXXRecord->isDependentType()) { 11973 if (CXXRecord->hasUserDeclaredDestructor()) { 11974 // Adjust user-defined destructor exception spec. 11975 if (getLangOpts().CPlusPlus11) 11976 AdjustDestructorExceptionSpec(CXXRecord, 11977 CXXRecord->getDestructor()); 11978 11979 // The Microsoft ABI requires that we perform the destructor body 11980 // checks (i.e. operator delete() lookup) at every declaration, as 11981 // any translation unit may need to emit a deleting destructor. 11982 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11983 CheckDestructor(CXXRecord->getDestructor()); 11984 } 11985 11986 // Add any implicitly-declared members to this class. 11987 AddImplicitlyDeclaredMembersToClass(CXXRecord); 11988 11989 // If we have virtual base classes, we may end up finding multiple 11990 // final overriders for a given virtual function. Check for this 11991 // problem now. 11992 if (CXXRecord->getNumVBases()) { 11993 CXXFinalOverriderMap FinalOverriders; 11994 CXXRecord->getFinalOverriders(FinalOverriders); 11995 11996 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 11997 MEnd = FinalOverriders.end(); 11998 M != MEnd; ++M) { 11999 for (OverridingMethods::iterator SO = M->second.begin(), 12000 SOEnd = M->second.end(); 12001 SO != SOEnd; ++SO) { 12002 assert(SO->second.size() > 0 && 12003 "Virtual function without overridding functions?"); 12004 if (SO->second.size() == 1) 12005 continue; 12006 12007 // C++ [class.virtual]p2: 12008 // In a derived class, if a virtual member function of a base 12009 // class subobject has more than one final overrider the 12010 // program is ill-formed. 12011 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12012 << (const NamedDecl *)M->first << Record; 12013 Diag(M->first->getLocation(), 12014 diag::note_overridden_virtual_function); 12015 for (OverridingMethods::overriding_iterator 12016 OM = SO->second.begin(), 12017 OMEnd = SO->second.end(); 12018 OM != OMEnd; ++OM) 12019 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12020 << (const NamedDecl *)M->first << OM->Method->getParent(); 12021 12022 Record->setInvalidDecl(); 12023 } 12024 } 12025 CXXRecord->completeDefinition(&FinalOverriders); 12026 Completed = true; 12027 } 12028 } 12029 } 12030 } 12031 12032 if (!Completed) 12033 Record->completeDefinition(); 12034 12035 if (Record->hasAttrs()) 12036 CheckAlignasUnderalignment(Record); 12037 12038 // Check if the structure/union declaration is a language extension. 12039 if (!getLangOpts().CPlusPlus) { 12040 bool ZeroSize = true; 12041 bool IsEmpty = true; 12042 unsigned NonBitFields = 0; 12043 for (RecordDecl::field_iterator I = Record->field_begin(), 12044 E = Record->field_end(); 12045 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12046 IsEmpty = false; 12047 if (I->isUnnamedBitfield()) { 12048 if (I->getBitWidthValue(Context) > 0) 12049 ZeroSize = false; 12050 } else { 12051 ++NonBitFields; 12052 QualType FieldType = I->getType(); 12053 if (FieldType->isIncompleteType() || 12054 !Context.getTypeSizeInChars(FieldType).isZero()) 12055 ZeroSize = false; 12056 } 12057 } 12058 12059 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 12060 // C++. 12061 if (ZeroSize) 12062 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty 12063 << Record->isUnion() << (NonBitFields > 1); 12064 12065 // Structs without named members are extension in C (C99 6.7.2.1p7), but 12066 // are accepted by GCC. 12067 if (NonBitFields == 0) { 12068 if (IsEmpty) 12069 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion(); 12070 else 12071 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion(); 12072 } 12073 } 12074 } else { 12075 ObjCIvarDecl **ClsFields = 12076 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12077 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12078 ID->setEndOfDefinitionLoc(RBrac); 12079 // Add ivar's to class's DeclContext. 12080 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12081 ClsFields[i]->setLexicalDeclContext(ID); 12082 ID->addDecl(ClsFields[i]); 12083 } 12084 // Must enforce the rule that ivars in the base classes may not be 12085 // duplicates. 12086 if (ID->getSuperClass()) 12087 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12088 } else if (ObjCImplementationDecl *IMPDecl = 12089 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12090 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12091 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12092 // Ivar declared in @implementation never belongs to the implementation. 12093 // Only it is in implementation's lexical context. 12094 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12095 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12096 IMPDecl->setIvarLBraceLoc(LBrac); 12097 IMPDecl->setIvarRBraceLoc(RBrac); 12098 } else if (ObjCCategoryDecl *CDecl = 12099 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12100 // case of ivars in class extension; all other cases have been 12101 // reported as errors elsewhere. 12102 // FIXME. Class extension does not have a LocEnd field. 12103 // CDecl->setLocEnd(RBrac); 12104 // Add ivar's to class extension's DeclContext. 12105 // Diagnose redeclaration of private ivars. 12106 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12107 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12108 if (IDecl) { 12109 if (const ObjCIvarDecl *ClsIvar = 12110 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12111 Diag(ClsFields[i]->getLocation(), 12112 diag::err_duplicate_ivar_declaration); 12113 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12114 continue; 12115 } 12116 for (ObjCInterfaceDecl::known_extensions_iterator 12117 Ext = IDecl->known_extensions_begin(), 12118 ExtEnd = IDecl->known_extensions_end(); 12119 Ext != ExtEnd; ++Ext) { 12120 if (const ObjCIvarDecl *ClsExtIvar 12121 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12122 Diag(ClsFields[i]->getLocation(), 12123 diag::err_duplicate_ivar_declaration); 12124 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12125 continue; 12126 } 12127 } 12128 } 12129 ClsFields[i]->setLexicalDeclContext(CDecl); 12130 CDecl->addDecl(ClsFields[i]); 12131 } 12132 CDecl->setIvarLBraceLoc(LBrac); 12133 CDecl->setIvarRBraceLoc(RBrac); 12134 } 12135 } 12136 12137 if (Attr) 12138 ProcessDeclAttributeList(S, Record, Attr); 12139} 12140 12141/// \brief Determine whether the given integral value is representable within 12142/// the given type T. 12143static bool isRepresentableIntegerValue(ASTContext &Context, 12144 llvm::APSInt &Value, 12145 QualType T) { 12146 assert(T->isIntegralType(Context) && "Integral type required!"); 12147 unsigned BitWidth = Context.getIntWidth(T); 12148 12149 if (Value.isUnsigned() || Value.isNonNegative()) { 12150 if (T->isSignedIntegerOrEnumerationType()) 12151 --BitWidth; 12152 return Value.getActiveBits() <= BitWidth; 12153 } 12154 return Value.getMinSignedBits() <= BitWidth; 12155} 12156 12157// \brief Given an integral type, return the next larger integral type 12158// (or a NULL type of no such type exists). 12159static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12160 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12161 // enum checking below. 12162 assert(T->isIntegralType(Context) && "Integral type required!"); 12163 const unsigned NumTypes = 4; 12164 QualType SignedIntegralTypes[NumTypes] = { 12165 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12166 }; 12167 QualType UnsignedIntegralTypes[NumTypes] = { 12168 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12169 Context.UnsignedLongLongTy 12170 }; 12171 12172 unsigned BitWidth = Context.getTypeSize(T); 12173 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12174 : UnsignedIntegralTypes; 12175 for (unsigned I = 0; I != NumTypes; ++I) 12176 if (Context.getTypeSize(Types[I]) > BitWidth) 12177 return Types[I]; 12178 12179 return QualType(); 12180} 12181 12182EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12183 EnumConstantDecl *LastEnumConst, 12184 SourceLocation IdLoc, 12185 IdentifierInfo *Id, 12186 Expr *Val) { 12187 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12188 llvm::APSInt EnumVal(IntWidth); 12189 QualType EltTy; 12190 12191 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12192 Val = 0; 12193 12194 if (Val) 12195 Val = DefaultLvalueConversion(Val).take(); 12196 12197 if (Val) { 12198 if (Enum->isDependentType() || Val->isTypeDependent()) 12199 EltTy = Context.DependentTy; 12200 else { 12201 SourceLocation ExpLoc; 12202 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12203 !getLangOpts().MicrosoftMode) { 12204 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12205 // constant-expression in the enumerator-definition shall be a converted 12206 // constant expression of the underlying type. 12207 EltTy = Enum->getIntegerType(); 12208 ExprResult Converted = 12209 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12210 CCEK_Enumerator); 12211 if (Converted.isInvalid()) 12212 Val = 0; 12213 else 12214 Val = Converted.take(); 12215 } else if (!Val->isValueDependent() && 12216 !(Val = VerifyIntegerConstantExpression(Val, 12217 &EnumVal).take())) { 12218 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12219 } else { 12220 if (Enum->isFixed()) { 12221 EltTy = Enum->getIntegerType(); 12222 12223 // In Obj-C and Microsoft mode, require the enumeration value to be 12224 // representable in the underlying type of the enumeration. In C++11, 12225 // we perform a non-narrowing conversion as part of converted constant 12226 // expression checking. 12227 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12228 if (getLangOpts().MicrosoftMode) { 12229 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12230 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12231 } else 12232 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12233 } else 12234 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12235 } else if (getLangOpts().CPlusPlus) { 12236 // C++11 [dcl.enum]p5: 12237 // If the underlying type is not fixed, the type of each enumerator 12238 // is the type of its initializing value: 12239 // - If an initializer is specified for an enumerator, the 12240 // initializing value has the same type as the expression. 12241 EltTy = Val->getType(); 12242 } else { 12243 // C99 6.7.2.2p2: 12244 // The expression that defines the value of an enumeration constant 12245 // shall be an integer constant expression that has a value 12246 // representable as an int. 12247 12248 // Complain if the value is not representable in an int. 12249 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12250 Diag(IdLoc, diag::ext_enum_value_not_int) 12251 << EnumVal.toString(10) << Val->getSourceRange() 12252 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12253 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12254 // Force the type of the expression to 'int'. 12255 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12256 } 12257 EltTy = Val->getType(); 12258 } 12259 } 12260 } 12261 } 12262 12263 if (!Val) { 12264 if (Enum->isDependentType()) 12265 EltTy = Context.DependentTy; 12266 else if (!LastEnumConst) { 12267 // C++0x [dcl.enum]p5: 12268 // If the underlying type is not fixed, the type of each enumerator 12269 // is the type of its initializing value: 12270 // - If no initializer is specified for the first enumerator, the 12271 // initializing value has an unspecified integral type. 12272 // 12273 // GCC uses 'int' for its unspecified integral type, as does 12274 // C99 6.7.2.2p3. 12275 if (Enum->isFixed()) { 12276 EltTy = Enum->getIntegerType(); 12277 } 12278 else { 12279 EltTy = Context.IntTy; 12280 } 12281 } else { 12282 // Assign the last value + 1. 12283 EnumVal = LastEnumConst->getInitVal(); 12284 ++EnumVal; 12285 EltTy = LastEnumConst->getType(); 12286 12287 // Check for overflow on increment. 12288 if (EnumVal < LastEnumConst->getInitVal()) { 12289 // C++0x [dcl.enum]p5: 12290 // If the underlying type is not fixed, the type of each enumerator 12291 // is the type of its initializing value: 12292 // 12293 // - Otherwise the type of the initializing value is the same as 12294 // the type of the initializing value of the preceding enumerator 12295 // unless the incremented value is not representable in that type, 12296 // in which case the type is an unspecified integral type 12297 // sufficient to contain the incremented value. If no such type 12298 // exists, the program is ill-formed. 12299 QualType T = getNextLargerIntegralType(Context, EltTy); 12300 if (T.isNull() || Enum->isFixed()) { 12301 // There is no integral type larger enough to represent this 12302 // value. Complain, then allow the value to wrap around. 12303 EnumVal = LastEnumConst->getInitVal(); 12304 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12305 ++EnumVal; 12306 if (Enum->isFixed()) 12307 // When the underlying type is fixed, this is ill-formed. 12308 Diag(IdLoc, diag::err_enumerator_wrapped) 12309 << EnumVal.toString(10) 12310 << EltTy; 12311 else 12312 Diag(IdLoc, diag::warn_enumerator_too_large) 12313 << EnumVal.toString(10); 12314 } else { 12315 EltTy = T; 12316 } 12317 12318 // Retrieve the last enumerator's value, extent that type to the 12319 // type that is supposed to be large enough to represent the incremented 12320 // value, then increment. 12321 EnumVal = LastEnumConst->getInitVal(); 12322 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12323 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12324 ++EnumVal; 12325 12326 // If we're not in C++, diagnose the overflow of enumerator values, 12327 // which in C99 means that the enumerator value is not representable in 12328 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12329 // permits enumerator values that are representable in some larger 12330 // integral type. 12331 if (!getLangOpts().CPlusPlus && !T.isNull()) 12332 Diag(IdLoc, diag::warn_enum_value_overflow); 12333 } else if (!getLangOpts().CPlusPlus && 12334 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12335 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12336 Diag(IdLoc, diag::ext_enum_value_not_int) 12337 << EnumVal.toString(10) << 1; 12338 } 12339 } 12340 } 12341 12342 if (!EltTy->isDependentType()) { 12343 // Make the enumerator value match the signedness and size of the 12344 // enumerator's type. 12345 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12346 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12347 } 12348 12349 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12350 Val, EnumVal); 12351} 12352 12353 12354Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12355 SourceLocation IdLoc, IdentifierInfo *Id, 12356 AttributeList *Attr, 12357 SourceLocation EqualLoc, Expr *Val) { 12358 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12359 EnumConstantDecl *LastEnumConst = 12360 cast_or_null<EnumConstantDecl>(lastEnumConst); 12361 12362 // The scope passed in may not be a decl scope. Zip up the scope tree until 12363 // we find one that is. 12364 S = getNonFieldDeclScope(S); 12365 12366 // Verify that there isn't already something declared with this name in this 12367 // scope. 12368 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12369 ForRedeclaration); 12370 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12371 // Maybe we will complain about the shadowed template parameter. 12372 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12373 // Just pretend that we didn't see the previous declaration. 12374 PrevDecl = 0; 12375 } 12376 12377 if (PrevDecl) { 12378 // When in C++, we may get a TagDecl with the same name; in this case the 12379 // enum constant will 'hide' the tag. 12380 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12381 "Received TagDecl when not in C++!"); 12382 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12383 if (isa<EnumConstantDecl>(PrevDecl)) 12384 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12385 else 12386 Diag(IdLoc, diag::err_redefinition) << Id; 12387 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12388 return 0; 12389 } 12390 } 12391 12392 // C++ [class.mem]p15: 12393 // If T is the name of a class, then each of the following shall have a name 12394 // different from T: 12395 // - every enumerator of every member of class T that is an unscoped 12396 // enumerated type 12397 if (CXXRecordDecl *Record 12398 = dyn_cast<CXXRecordDecl>( 12399 TheEnumDecl->getDeclContext()->getRedeclContext())) 12400 if (!TheEnumDecl->isScoped() && 12401 Record->getIdentifier() && Record->getIdentifier() == Id) 12402 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12403 12404 EnumConstantDecl *New = 12405 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12406 12407 if (New) { 12408 // Process attributes. 12409 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12410 12411 // Register this decl in the current scope stack. 12412 New->setAccess(TheEnumDecl->getAccess()); 12413 PushOnScopeChains(New, S); 12414 } 12415 12416 ActOnDocumentableDecl(New); 12417 12418 return New; 12419} 12420 12421// Returns true when the enum initial expression does not trigger the 12422// duplicate enum warning. A few common cases are exempted as follows: 12423// Element2 = Element1 12424// Element2 = Element1 + 1 12425// Element2 = Element1 - 1 12426// Where Element2 and Element1 are from the same enum. 12427static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12428 Expr *InitExpr = ECD->getInitExpr(); 12429 if (!InitExpr) 12430 return true; 12431 InitExpr = InitExpr->IgnoreImpCasts(); 12432 12433 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12434 if (!BO->isAdditiveOp()) 12435 return true; 12436 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12437 if (!IL) 12438 return true; 12439 if (IL->getValue() != 1) 12440 return true; 12441 12442 InitExpr = BO->getLHS(); 12443 } 12444 12445 // This checks if the elements are from the same enum. 12446 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12447 if (!DRE) 12448 return true; 12449 12450 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12451 if (!EnumConstant) 12452 return true; 12453 12454 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12455 Enum) 12456 return true; 12457 12458 return false; 12459} 12460 12461struct DupKey { 12462 int64_t val; 12463 bool isTombstoneOrEmptyKey; 12464 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12465 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12466}; 12467 12468static DupKey GetDupKey(const llvm::APSInt& Val) { 12469 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12470 false); 12471} 12472 12473struct DenseMapInfoDupKey { 12474 static DupKey getEmptyKey() { return DupKey(0, true); } 12475 static DupKey getTombstoneKey() { return DupKey(1, true); } 12476 static unsigned getHashValue(const DupKey Key) { 12477 return (unsigned)(Key.val * 37); 12478 } 12479 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12480 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12481 LHS.val == RHS.val; 12482 } 12483}; 12484 12485// Emits a warning when an element is implicitly set a value that 12486// a previous element has already been set to. 12487static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12488 EnumDecl *Enum, 12489 QualType EnumType) { 12490 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12491 Enum->getLocation()) == 12492 DiagnosticsEngine::Ignored) 12493 return; 12494 // Avoid anonymous enums 12495 if (!Enum->getIdentifier()) 12496 return; 12497 12498 // Only check for small enums. 12499 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12500 return; 12501 12502 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12503 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12504 12505 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12506 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12507 ValueToVectorMap; 12508 12509 DuplicatesVector DupVector; 12510 ValueToVectorMap EnumMap; 12511 12512 // Populate the EnumMap with all values represented by enum constants without 12513 // an initialier. 12514 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12515 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12516 12517 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12518 // this constant. Skip this enum since it may be ill-formed. 12519 if (!ECD) { 12520 return; 12521 } 12522 12523 if (ECD->getInitExpr()) 12524 continue; 12525 12526 DupKey Key = GetDupKey(ECD->getInitVal()); 12527 DeclOrVector &Entry = EnumMap[Key]; 12528 12529 // First time encountering this value. 12530 if (Entry.isNull()) 12531 Entry = ECD; 12532 } 12533 12534 // Create vectors for any values that has duplicates. 12535 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12536 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12537 if (!ValidDuplicateEnum(ECD, Enum)) 12538 continue; 12539 12540 DupKey Key = GetDupKey(ECD->getInitVal()); 12541 12542 DeclOrVector& Entry = EnumMap[Key]; 12543 if (Entry.isNull()) 12544 continue; 12545 12546 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12547 // Ensure constants are different. 12548 if (D == ECD) 12549 continue; 12550 12551 // Create new vector and push values onto it. 12552 ECDVector *Vec = new ECDVector(); 12553 Vec->push_back(D); 12554 Vec->push_back(ECD); 12555 12556 // Update entry to point to the duplicates vector. 12557 Entry = Vec; 12558 12559 // Store the vector somewhere we can consult later for quick emission of 12560 // diagnostics. 12561 DupVector.push_back(Vec); 12562 continue; 12563 } 12564 12565 ECDVector *Vec = Entry.get<ECDVector*>(); 12566 // Make sure constants are not added more than once. 12567 if (*Vec->begin() == ECD) 12568 continue; 12569 12570 Vec->push_back(ECD); 12571 } 12572 12573 // Emit diagnostics. 12574 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12575 DupVectorEnd = DupVector.end(); 12576 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12577 ECDVector *Vec = *DupVectorIter; 12578 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12579 12580 // Emit warning for one enum constant. 12581 ECDVector::iterator I = Vec->begin(); 12582 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12583 << (*I)->getName() << (*I)->getInitVal().toString(10) 12584 << (*I)->getSourceRange(); 12585 ++I; 12586 12587 // Emit one note for each of the remaining enum constants with 12588 // the same value. 12589 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12590 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12591 << (*I)->getName() << (*I)->getInitVal().toString(10) 12592 << (*I)->getSourceRange(); 12593 delete Vec; 12594 } 12595} 12596 12597void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12598 SourceLocation RBraceLoc, Decl *EnumDeclX, 12599 ArrayRef<Decl *> Elements, 12600 Scope *S, AttributeList *Attr) { 12601 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12602 QualType EnumType = Context.getTypeDeclType(Enum); 12603 12604 if (Attr) 12605 ProcessDeclAttributeList(S, Enum, Attr); 12606 12607 if (Enum->isDependentType()) { 12608 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12609 EnumConstantDecl *ECD = 12610 cast_or_null<EnumConstantDecl>(Elements[i]); 12611 if (!ECD) continue; 12612 12613 ECD->setType(EnumType); 12614 } 12615 12616 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12617 return; 12618 } 12619 12620 // TODO: If the result value doesn't fit in an int, it must be a long or long 12621 // long value. ISO C does not support this, but GCC does as an extension, 12622 // emit a warning. 12623 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12624 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12625 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12626 12627 // Verify that all the values are okay, compute the size of the values, and 12628 // reverse the list. 12629 unsigned NumNegativeBits = 0; 12630 unsigned NumPositiveBits = 0; 12631 12632 // Keep track of whether all elements have type int. 12633 bool AllElementsInt = true; 12634 12635 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12636 EnumConstantDecl *ECD = 12637 cast_or_null<EnumConstantDecl>(Elements[i]); 12638 if (!ECD) continue; // Already issued a diagnostic. 12639 12640 const llvm::APSInt &InitVal = ECD->getInitVal(); 12641 12642 // Keep track of the size of positive and negative values. 12643 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12644 NumPositiveBits = std::max(NumPositiveBits, 12645 (unsigned)InitVal.getActiveBits()); 12646 else 12647 NumNegativeBits = std::max(NumNegativeBits, 12648 (unsigned)InitVal.getMinSignedBits()); 12649 12650 // Keep track of whether every enum element has type int (very commmon). 12651 if (AllElementsInt) 12652 AllElementsInt = ECD->getType() == Context.IntTy; 12653 } 12654 12655 // Figure out the type that should be used for this enum. 12656 QualType BestType; 12657 unsigned BestWidth; 12658 12659 // C++0x N3000 [conv.prom]p3: 12660 // An rvalue of an unscoped enumeration type whose underlying 12661 // type is not fixed can be converted to an rvalue of the first 12662 // of the following types that can represent all the values of 12663 // the enumeration: int, unsigned int, long int, unsigned long 12664 // int, long long int, or unsigned long long int. 12665 // C99 6.4.4.3p2: 12666 // An identifier declared as an enumeration constant has type int. 12667 // The C99 rule is modified by a gcc extension 12668 QualType BestPromotionType; 12669 12670 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 12671 // -fshort-enums is the equivalent to specifying the packed attribute on all 12672 // enum definitions. 12673 if (LangOpts.ShortEnums) 12674 Packed = true; 12675 12676 if (Enum->isFixed()) { 12677 BestType = Enum->getIntegerType(); 12678 if (BestType->isPromotableIntegerType()) 12679 BestPromotionType = Context.getPromotedIntegerType(BestType); 12680 else 12681 BestPromotionType = BestType; 12682 // We don't need to set BestWidth, because BestType is going to be the type 12683 // of the enumerators, but we do anyway because otherwise some compilers 12684 // warn that it might be used uninitialized. 12685 BestWidth = CharWidth; 12686 } 12687 else if (NumNegativeBits) { 12688 // If there is a negative value, figure out the smallest integer type (of 12689 // int/long/longlong) that fits. 12690 // If it's packed, check also if it fits a char or a short. 12691 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12692 BestType = Context.SignedCharTy; 12693 BestWidth = CharWidth; 12694 } else if (Packed && NumNegativeBits <= ShortWidth && 12695 NumPositiveBits < ShortWidth) { 12696 BestType = Context.ShortTy; 12697 BestWidth = ShortWidth; 12698 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12699 BestType = Context.IntTy; 12700 BestWidth = IntWidth; 12701 } else { 12702 BestWidth = Context.getTargetInfo().getLongWidth(); 12703 12704 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12705 BestType = Context.LongTy; 12706 } else { 12707 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12708 12709 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12710 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12711 BestType = Context.LongLongTy; 12712 } 12713 } 12714 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12715 } else { 12716 // If there is no negative value, figure out the smallest type that fits 12717 // all of the enumerator values. 12718 // If it's packed, check also if it fits a char or a short. 12719 if (Packed && NumPositiveBits <= CharWidth) { 12720 BestType = Context.UnsignedCharTy; 12721 BestPromotionType = Context.IntTy; 12722 BestWidth = CharWidth; 12723 } else if (Packed && NumPositiveBits <= ShortWidth) { 12724 BestType = Context.UnsignedShortTy; 12725 BestPromotionType = Context.IntTy; 12726 BestWidth = ShortWidth; 12727 } else if (NumPositiveBits <= IntWidth) { 12728 BestType = Context.UnsignedIntTy; 12729 BestWidth = IntWidth; 12730 BestPromotionType 12731 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12732 ? Context.UnsignedIntTy : Context.IntTy; 12733 } else if (NumPositiveBits <= 12734 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12735 BestType = Context.UnsignedLongTy; 12736 BestPromotionType 12737 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12738 ? Context.UnsignedLongTy : Context.LongTy; 12739 } else { 12740 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12741 assert(NumPositiveBits <= BestWidth && 12742 "How could an initializer get larger than ULL?"); 12743 BestType = Context.UnsignedLongLongTy; 12744 BestPromotionType 12745 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12746 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12747 } 12748 } 12749 12750 // Loop over all of the enumerator constants, changing their types to match 12751 // the type of the enum if needed. 12752 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12753 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12754 if (!ECD) continue; // Already issued a diagnostic. 12755 12756 // Standard C says the enumerators have int type, but we allow, as an 12757 // extension, the enumerators to be larger than int size. If each 12758 // enumerator value fits in an int, type it as an int, otherwise type it the 12759 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12760 // that X has type 'int', not 'unsigned'. 12761 12762 // Determine whether the value fits into an int. 12763 llvm::APSInt InitVal = ECD->getInitVal(); 12764 12765 // If it fits into an integer type, force it. Otherwise force it to match 12766 // the enum decl type. 12767 QualType NewTy; 12768 unsigned NewWidth; 12769 bool NewSign; 12770 if (!getLangOpts().CPlusPlus && 12771 !Enum->isFixed() && 12772 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12773 NewTy = Context.IntTy; 12774 NewWidth = IntWidth; 12775 NewSign = true; 12776 } else if (ECD->getType() == BestType) { 12777 // Already the right type! 12778 if (getLangOpts().CPlusPlus) 12779 // C++ [dcl.enum]p4: Following the closing brace of an 12780 // enum-specifier, each enumerator has the type of its 12781 // enumeration. 12782 ECD->setType(EnumType); 12783 continue; 12784 } else { 12785 NewTy = BestType; 12786 NewWidth = BestWidth; 12787 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12788 } 12789 12790 // Adjust the APSInt value. 12791 InitVal = InitVal.extOrTrunc(NewWidth); 12792 InitVal.setIsSigned(NewSign); 12793 ECD->setInitVal(InitVal); 12794 12795 // Adjust the Expr initializer and type. 12796 if (ECD->getInitExpr() && 12797 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12798 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12799 CK_IntegralCast, 12800 ECD->getInitExpr(), 12801 /*base paths*/ 0, 12802 VK_RValue)); 12803 if (getLangOpts().CPlusPlus) 12804 // C++ [dcl.enum]p4: Following the closing brace of an 12805 // enum-specifier, each enumerator has the type of its 12806 // enumeration. 12807 ECD->setType(EnumType); 12808 else 12809 ECD->setType(NewTy); 12810 } 12811 12812 Enum->completeDefinition(BestType, BestPromotionType, 12813 NumPositiveBits, NumNegativeBits); 12814 12815 // If we're declaring a function, ensure this decl isn't forgotten about - 12816 // it needs to go into the function scope. 12817 if (InFunctionDeclarator) 12818 DeclsInPrototypeScope.push_back(Enum); 12819 12820 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12821 12822 // Now that the enum type is defined, ensure it's not been underaligned. 12823 if (Enum->hasAttrs()) 12824 CheckAlignasUnderalignment(Enum); 12825} 12826 12827Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12828 SourceLocation StartLoc, 12829 SourceLocation EndLoc) { 12830 StringLiteral *AsmString = cast<StringLiteral>(expr); 12831 12832 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12833 AsmString, StartLoc, 12834 EndLoc); 12835 CurContext->addDecl(New); 12836 return New; 12837} 12838 12839DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12840 SourceLocation ImportLoc, 12841 ModuleIdPath Path) { 12842 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12843 Module::AllVisible, 12844 /*IsIncludeDirective=*/false); 12845 if (!Mod) 12846 return true; 12847 12848 SmallVector<SourceLocation, 2> IdentifierLocs; 12849 Module *ModCheck = Mod; 12850 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12851 // If we've run out of module parents, just drop the remaining identifiers. 12852 // We need the length to be consistent. 12853 if (!ModCheck) 12854 break; 12855 ModCheck = ModCheck->Parent; 12856 12857 IdentifierLocs.push_back(Path[I].second); 12858 } 12859 12860 ImportDecl *Import = ImportDecl::Create(Context, 12861 Context.getTranslationUnitDecl(), 12862 AtLoc.isValid()? AtLoc : ImportLoc, 12863 Mod, IdentifierLocs); 12864 Context.getTranslationUnitDecl()->addDecl(Import); 12865 return Import; 12866} 12867 12868void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 12869 // Create the implicit import declaration. 12870 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 12871 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 12872 Loc, Mod, Loc); 12873 TU->addDecl(ImportD); 12874 Consumer.HandleImplicitImportDecl(ImportD); 12875 12876 // Make the module visible. 12877 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 12878 /*Complain=*/false); 12879} 12880 12881void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 12882 IdentifierInfo* AliasName, 12883 SourceLocation PragmaLoc, 12884 SourceLocation NameLoc, 12885 SourceLocation AliasNameLoc) { 12886 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 12887 LookupOrdinaryName); 12888 AsmLabelAttr *Attr = 12889 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 12890 12891 if (PrevDecl) 12892 PrevDecl->addAttr(Attr); 12893 else 12894 (void)ExtnameUndeclaredIdentifiers.insert( 12895 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 12896} 12897 12898void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 12899 SourceLocation PragmaLoc, 12900 SourceLocation NameLoc) { 12901 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 12902 12903 if (PrevDecl) { 12904 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 12905 } else { 12906 (void)WeakUndeclaredIdentifiers.insert( 12907 std::pair<IdentifierInfo*,WeakInfo> 12908 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 12909 } 12910} 12911 12912void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 12913 IdentifierInfo* AliasName, 12914 SourceLocation PragmaLoc, 12915 SourceLocation NameLoc, 12916 SourceLocation AliasNameLoc) { 12917 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 12918 LookupOrdinaryName); 12919 WeakInfo W = WeakInfo(Name, NameLoc); 12920 12921 if (PrevDecl) { 12922 if (!PrevDecl->hasAttr<AliasAttr>()) 12923 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 12924 DeclApplyPragmaWeak(TUScope, ND, W); 12925 } else { 12926 (void)WeakUndeclaredIdentifiers.insert( 12927 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 12928 } 12929} 12930 12931Decl *Sema::getObjCDeclContext() const { 12932 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 12933} 12934 12935AvailabilityResult Sema::getCurContextAvailability() const { 12936 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 12937 return D->getAvailability(); 12938} 12939