SemaDecl.cpp revision 6df81a94fca403c7aa66918404caab19cffbca35
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 "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/CXXFieldCollector.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "TypeLocBuilder.h" 21#include "clang/AST/ASTConsumer.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/CommentDiagnostic.h" 25#include "clang/AST/DeclCXX.h" 26#include "clang/AST/DeclObjC.h" 27#include "clang/AST/DeclTemplate.h" 28#include "clang/AST/EvaluatedExprVisitor.h" 29#include "clang/AST/ExprCXX.h" 30#include "clang/AST/StmtCXX.h" 31#include "clang/AST/CharUnits.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/ParsedTemplate.h" 34#include "clang/Parse/ParseDiagnostic.h" 35#include "clang/Basic/PartialDiagnostic.h" 36#include "clang/Sema/DelayedDiagnostic.h" 37#include "clang/Basic/SourceManager.h" 38#include "clang/Basic/TargetInfo.h" 39// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 40#include "clang/Lex/Preprocessor.h" 41#include "clang/Lex/HeaderSearch.h" 42#include "clang/Lex/ModuleLoader.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::kw_decltype: 113 return getLangOpts().CPlusPlus; 114 115 default: 116 break; 117 } 118 119 return false; 120} 121 122/// \brief If the identifier refers to a type name within this scope, 123/// return the declaration of that type. 124/// 125/// This routine performs ordinary name lookup of the identifier II 126/// within the given scope, with optional C++ scope specifier SS, to 127/// determine whether the name refers to a type. If so, returns an 128/// opaque pointer (actually a QualType) corresponding to that 129/// type. Otherwise, returns NULL. 130/// 131/// If name lookup results in an ambiguity, this routine will complain 132/// and then return NULL. 133ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 134 Scope *S, CXXScopeSpec *SS, 135 bool isClassName, bool HasTrailingDot, 136 ParsedType ObjectTypePtr, 137 bool IsCtorOrDtorName, 138 bool WantNontrivialTypeSourceInfo, 139 IdentifierInfo **CorrectedII) { 140 // Determine where we will perform name lookup. 141 DeclContext *LookupCtx = 0; 142 if (ObjectTypePtr) { 143 QualType ObjectType = ObjectTypePtr.get(); 144 if (ObjectType->isRecordType()) 145 LookupCtx = computeDeclContext(ObjectType); 146 } else if (SS && SS->isNotEmpty()) { 147 LookupCtx = computeDeclContext(*SS, false); 148 149 if (!LookupCtx) { 150 if (isDependentScopeSpecifier(*SS)) { 151 // C++ [temp.res]p3: 152 // A qualified-id that refers to a type and in which the 153 // nested-name-specifier depends on a template-parameter (14.6.2) 154 // shall be prefixed by the keyword typename to indicate that the 155 // qualified-id denotes a type, forming an 156 // elaborated-type-specifier (7.1.5.3). 157 // 158 // We therefore do not perform any name lookup if the result would 159 // refer to a member of an unknown specialization. 160 if (!isClassName && !IsCtorOrDtorName) 161 return ParsedType(); 162 163 // We know from the grammar that this name refers to a type, 164 // so build a dependent node to describe the type. 165 if (WantNontrivialTypeSourceInfo) 166 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 167 168 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 169 QualType T = 170 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 171 II, NameLoc); 172 173 return ParsedType::make(T); 174 } 175 176 return ParsedType(); 177 } 178 179 if (!LookupCtx->isDependentContext() && 180 RequireCompleteDeclContext(*SS, LookupCtx)) 181 return ParsedType(); 182 } 183 184 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 185 // lookup for class-names. 186 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 187 LookupOrdinaryName; 188 LookupResult Result(*this, &II, NameLoc, Kind); 189 if (LookupCtx) { 190 // Perform "qualified" name lookup into the declaration context we 191 // computed, which is either the type of the base of a member access 192 // expression or the declaration context associated with a prior 193 // nested-name-specifier. 194 LookupQualifiedName(Result, LookupCtx); 195 196 if (ObjectTypePtr && Result.empty()) { 197 // C++ [basic.lookup.classref]p3: 198 // If the unqualified-id is ~type-name, the type-name is looked up 199 // in the context of the entire postfix-expression. If the type T of 200 // the object expression is of a class type C, the type-name is also 201 // looked up in the scope of class C. At least one of the lookups shall 202 // find a name that refers to (possibly cv-qualified) T. 203 LookupName(Result, S); 204 } 205 } else { 206 // Perform unqualified name lookup. 207 LookupName(Result, S); 208 } 209 210 NamedDecl *IIDecl = 0; 211 switch (Result.getResultKind()) { 212 case LookupResult::NotFound: 213 case LookupResult::NotFoundInCurrentInstantiation: 214 if (CorrectedII) { 215 TypeNameValidatorCCC Validator(true, isClassName); 216 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 217 Kind, S, SS, Validator); 218 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 219 TemplateTy Template; 220 bool MemberOfUnknownSpecialization; 221 UnqualifiedId TemplateName; 222 TemplateName.setIdentifier(NewII, NameLoc); 223 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 224 CXXScopeSpec NewSS, *NewSSPtr = SS; 225 if (SS && NNS) { 226 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 227 NewSSPtr = &NewSS; 228 } 229 if (Correction && (NNS || NewII != &II) && 230 // Ignore a correction to a template type as the to-be-corrected 231 // identifier is not a template (typo correction for template names 232 // is handled elsewhere). 233 !(getLangOpts().CPlusPlus && NewSSPtr && 234 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 235 false, Template, MemberOfUnknownSpecialization))) { 236 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 237 isClassName, HasTrailingDot, ObjectTypePtr, 238 IsCtorOrDtorName, 239 WantNontrivialTypeSourceInfo); 240 if (Ty) { 241 std::string CorrectedStr(Correction.getAsString(getLangOpts())); 242 std::string CorrectedQuotedStr( 243 Correction.getQuoted(getLangOpts())); 244 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest) 245 << Result.getLookupName() << CorrectedQuotedStr << isClassName 246 << FixItHint::CreateReplacement(SourceRange(NameLoc), 247 CorrectedStr); 248 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 249 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 250 << CorrectedQuotedStr; 251 252 if (SS && NNS) 253 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 254 *CorrectedII = NewII; 255 return Ty; 256 } 257 } 258 } 259 // If typo correction failed or was not performed, fall through 260 case LookupResult::FoundOverloaded: 261 case LookupResult::FoundUnresolvedValue: 262 Result.suppressDiagnostics(); 263 return ParsedType(); 264 265 case LookupResult::Ambiguous: 266 // Recover from type-hiding ambiguities by hiding the type. We'll 267 // do the lookup again when looking for an object, and we can 268 // diagnose the error then. If we don't do this, then the error 269 // about hiding the type will be immediately followed by an error 270 // that only makes sense if the identifier was treated like a type. 271 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 272 Result.suppressDiagnostics(); 273 return ParsedType(); 274 } 275 276 // Look to see if we have a type anywhere in the list of results. 277 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 278 Res != ResEnd; ++Res) { 279 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 280 if (!IIDecl || 281 (*Res)->getLocation().getRawEncoding() < 282 IIDecl->getLocation().getRawEncoding()) 283 IIDecl = *Res; 284 } 285 } 286 287 if (!IIDecl) { 288 // None of the entities we found is a type, so there is no way 289 // to even assume that the result is a type. In this case, don't 290 // complain about the ambiguity. The parser will either try to 291 // perform this lookup again (e.g., as an object name), which 292 // will produce the ambiguity, or will complain that it expected 293 // a type name. 294 Result.suppressDiagnostics(); 295 return ParsedType(); 296 } 297 298 // We found a type within the ambiguous lookup; diagnose the 299 // ambiguity and then return that type. This might be the right 300 // answer, or it might not be, but it suppresses any attempt to 301 // perform the name lookup again. 302 break; 303 304 case LookupResult::Found: 305 IIDecl = Result.getFoundDecl(); 306 break; 307 } 308 309 assert(IIDecl && "Didn't find decl"); 310 311 QualType T; 312 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 313 DiagnoseUseOfDecl(IIDecl, NameLoc); 314 315 if (T.isNull()) 316 T = Context.getTypeDeclType(TD); 317 318 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 319 // constructor or destructor name (in such a case, the scope specifier 320 // will be attached to the enclosing Expr or Decl node). 321 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 322 if (WantNontrivialTypeSourceInfo) { 323 // Construct a type with type-source information. 324 TypeLocBuilder Builder; 325 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 326 327 T = getElaboratedType(ETK_None, *SS, T); 328 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 329 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 330 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 331 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 332 } else { 333 T = getElaboratedType(ETK_None, *SS, T); 334 } 335 } 336 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 337 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 338 if (!HasTrailingDot) 339 T = Context.getObjCInterfaceType(IDecl); 340 } 341 342 if (T.isNull()) { 343 // If it's not plausibly a type, suppress diagnostics. 344 Result.suppressDiagnostics(); 345 return ParsedType(); 346 } 347 return ParsedType::make(T); 348} 349 350/// isTagName() - This method is called *for error recovery purposes only* 351/// to determine if the specified name is a valid tag name ("struct foo"). If 352/// so, this returns the TST for the tag corresponding to it (TST_enum, 353/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 354/// cases in C where the user forgot to specify the tag. 355DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 356 // Do a tag name lookup in this scope. 357 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 358 LookupName(R, S, false); 359 R.suppressDiagnostics(); 360 if (R.getResultKind() == LookupResult::Found) 361 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 362 switch (TD->getTagKind()) { 363 case TTK_Struct: return DeclSpec::TST_struct; 364 case TTK_Interface: return DeclSpec::TST_interface; 365 case TTK_Union: return DeclSpec::TST_union; 366 case TTK_Class: return DeclSpec::TST_class; 367 case TTK_Enum: return DeclSpec::TST_enum; 368 } 369 } 370 371 return DeclSpec::TST_unspecified; 372} 373 374/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 375/// if a CXXScopeSpec's type is equal to the type of one of the base classes 376/// then downgrade the missing typename error to a warning. 377/// This is needed for MSVC compatibility; Example: 378/// @code 379/// template<class T> class A { 380/// public: 381/// typedef int TYPE; 382/// }; 383/// template<class T> class B : public A<T> { 384/// public: 385/// A<T>::TYPE a; // no typename required because A<T> is a base class. 386/// }; 387/// @endcode 388bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 389 if (CurContext->isRecord()) { 390 const Type *Ty = SS->getScopeRep()->getAsType(); 391 392 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 393 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 394 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 395 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 396 return true; 397 return S->isFunctionPrototypeScope(); 398 } 399 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 400} 401 402bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 403 SourceLocation IILoc, 404 Scope *S, 405 CXXScopeSpec *SS, 406 ParsedType &SuggestedType) { 407 // We don't have anything to suggest (yet). 408 SuggestedType = ParsedType(); 409 410 // There may have been a typo in the name of the type. Look up typo 411 // results, in case we have something that we can suggest. 412 TypeNameValidatorCCC Validator(false); 413 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 414 LookupOrdinaryName, S, SS, 415 Validator)) { 416 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 417 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 418 419 if (Corrected.isKeyword()) { 420 // We corrected to a keyword. 421 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo(); 422 if (!isSimpleTypeSpecifier(NewII->getTokenID())) 423 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr; 424 Diag(IILoc, diag::err_unknown_typename_suggest) 425 << II << CorrectedQuotedStr 426 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 427 II = NewII; 428 } else { 429 NamedDecl *Result = Corrected.getCorrectionDecl(); 430 // We found a similarly-named type or interface; suggest that. 431 if (!SS || !SS->isSet()) 432 Diag(IILoc, diag::err_unknown_typename_suggest) 433 << II << CorrectedQuotedStr 434 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 435 else if (DeclContext *DC = computeDeclContext(*SS, false)) 436 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 437 << II << DC << CorrectedQuotedStr << SS->getRange() 438 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 439 CorrectedStr); 440 else 441 llvm_unreachable("could not have corrected a typo here"); 442 443 Diag(Result->getLocation(), diag::note_previous_decl) 444 << CorrectedQuotedStr; 445 446 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 447 false, false, ParsedType(), 448 /*IsCtorOrDtorName=*/false, 449 /*NonTrivialTypeSourceInfo=*/true); 450 } 451 return true; 452 } 453 454 if (getLangOpts().CPlusPlus) { 455 // See if II is a class template that the user forgot to pass arguments to. 456 UnqualifiedId Name; 457 Name.setIdentifier(II, IILoc); 458 CXXScopeSpec EmptySS; 459 TemplateTy TemplateResult; 460 bool MemberOfUnknownSpecialization; 461 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 462 Name, ParsedType(), true, TemplateResult, 463 MemberOfUnknownSpecialization) == TNK_Type_template) { 464 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 465 Diag(IILoc, diag::err_template_missing_args) << TplName; 466 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 467 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 468 << TplDecl->getTemplateParameters()->getSourceRange(); 469 } 470 return true; 471 } 472 } 473 474 // FIXME: Should we move the logic that tries to recover from a missing tag 475 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 476 477 if (!SS || (!SS->isSet() && !SS->isInvalid())) 478 Diag(IILoc, diag::err_unknown_typename) << II; 479 else if (DeclContext *DC = computeDeclContext(*SS, false)) 480 Diag(IILoc, diag::err_typename_nested_not_found) 481 << II << DC << SS->getRange(); 482 else if (isDependentScopeSpecifier(*SS)) { 483 unsigned DiagID = diag::err_typename_missing; 484 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 485 DiagID = diag::warn_typename_missing; 486 487 Diag(SS->getRange().getBegin(), DiagID) 488 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 489 << SourceRange(SS->getRange().getBegin(), IILoc) 490 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 491 SuggestedType = ActOnTypenameType(S, SourceLocation(), 492 *SS, *II, IILoc).get(); 493 } else { 494 assert(SS && SS->isInvalid() && 495 "Invalid scope specifier has already been diagnosed"); 496 } 497 498 return true; 499} 500 501/// \brief Determine whether the given result set contains either a type name 502/// or 503static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 504 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 505 NextToken.is(tok::less); 506 507 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 508 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 509 return true; 510 511 if (CheckTemplate && isa<TemplateDecl>(*I)) 512 return true; 513 } 514 515 return false; 516} 517 518static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 519 Scope *S, CXXScopeSpec &SS, 520 IdentifierInfo *&Name, 521 SourceLocation NameLoc) { 522 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 523 SemaRef.LookupParsedName(R, S, &SS); 524 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 525 const char *TagName = 0; 526 const char *FixItTagName = 0; 527 switch (Tag->getTagKind()) { 528 case TTK_Class: 529 TagName = "class"; 530 FixItTagName = "class "; 531 break; 532 533 case TTK_Enum: 534 TagName = "enum"; 535 FixItTagName = "enum "; 536 break; 537 538 case TTK_Struct: 539 TagName = "struct"; 540 FixItTagName = "struct "; 541 break; 542 543 case TTK_Interface: 544 TagName = "__interface"; 545 FixItTagName = "__interface "; 546 break; 547 548 case TTK_Union: 549 TagName = "union"; 550 FixItTagName = "union "; 551 break; 552 } 553 554 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 555 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 556 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 557 558 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 559 I != IEnd; ++I) 560 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 561 << Name << TagName; 562 563 // Replace lookup results with just the tag decl. 564 Result.clear(Sema::LookupTagName); 565 SemaRef.LookupParsedName(Result, S, &SS); 566 return true; 567 } 568 569 return false; 570} 571 572/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 573static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 574 QualType T, SourceLocation NameLoc) { 575 ASTContext &Context = S.Context; 576 577 TypeLocBuilder Builder; 578 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 579 580 T = S.getElaboratedType(ETK_None, SS, T); 581 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 582 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 583 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 584 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 585} 586 587Sema::NameClassification Sema::ClassifyName(Scope *S, 588 CXXScopeSpec &SS, 589 IdentifierInfo *&Name, 590 SourceLocation NameLoc, 591 const Token &NextToken, 592 bool IsAddressOfOperand, 593 CorrectionCandidateCallback *CCC) { 594 DeclarationNameInfo NameInfo(Name, NameLoc); 595 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 596 597 if (NextToken.is(tok::coloncolon)) { 598 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 599 QualType(), false, SS, 0, false); 600 601 } 602 603 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 604 LookupParsedName(Result, S, &SS, !CurMethod); 605 606 // Perform lookup for Objective-C instance variables (including automatically 607 // synthesized instance variables), if we're in an Objective-C method. 608 // FIXME: This lookup really, really needs to be folded in to the normal 609 // unqualified lookup mechanism. 610 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 611 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 612 if (E.get() || E.isInvalid()) 613 return E; 614 } 615 616 bool SecondTry = false; 617 bool IsFilteredTemplateName = false; 618 619Corrected: 620 switch (Result.getResultKind()) { 621 case LookupResult::NotFound: 622 // If an unqualified-id is followed by a '(', then we have a function 623 // call. 624 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 625 // In C++, this is an ADL-only call. 626 // FIXME: Reference? 627 if (getLangOpts().CPlusPlus) 628 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 629 630 // C90 6.3.2.2: 631 // If the expression that precedes the parenthesized argument list in a 632 // function call consists solely of an identifier, and if no 633 // declaration is visible for this identifier, the identifier is 634 // implicitly declared exactly as if, in the innermost block containing 635 // the function call, the declaration 636 // 637 // extern int identifier (); 638 // 639 // appeared. 640 // 641 // We also allow this in C99 as an extension. 642 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 643 Result.addDecl(D); 644 Result.resolveKind(); 645 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 646 } 647 } 648 649 // In C, we first see whether there is a tag type by the same name, in 650 // which case it's likely that the user just forget to write "enum", 651 // "struct", or "union". 652 if (!getLangOpts().CPlusPlus && !SecondTry && 653 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 654 break; 655 } 656 657 // Perform typo correction to determine if there is another name that is 658 // close to this name. 659 if (!SecondTry && CCC) { 660 SecondTry = true; 661 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 662 Result.getLookupKind(), S, 663 &SS, *CCC)) { 664 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 665 unsigned QualifiedDiag = diag::err_no_member_suggest; 666 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 667 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 668 669 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 670 NamedDecl *UnderlyingFirstDecl 671 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 672 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 673 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 674 UnqualifiedDiag = diag::err_no_template_suggest; 675 QualifiedDiag = diag::err_no_member_template_suggest; 676 } else if (UnderlyingFirstDecl && 677 (isa<TypeDecl>(UnderlyingFirstDecl) || 678 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 679 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 680 UnqualifiedDiag = diag::err_unknown_typename_suggest; 681 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 682 } 683 684 if (SS.isEmpty()) 685 Diag(NameLoc, UnqualifiedDiag) 686 << Name << CorrectedQuotedStr 687 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 688 else // FIXME: is this even reachable? Test it. 689 Diag(NameLoc, QualifiedDiag) 690 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 691 << SS.getRange() 692 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 693 CorrectedStr); 694 695 // Update the name, so that the caller has the new name. 696 Name = Corrected.getCorrectionAsIdentifierInfo(); 697 698 // Typo correction corrected to a keyword. 699 if (Corrected.isKeyword()) 700 return Corrected.getCorrectionAsIdentifierInfo(); 701 702 // Also update the LookupResult... 703 // FIXME: This should probably go away at some point 704 Result.clear(); 705 Result.setLookupName(Corrected.getCorrection()); 706 if (FirstDecl) { 707 Result.addDecl(FirstDecl); 708 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 709 << CorrectedQuotedStr; 710 } 711 712 // If we found an Objective-C instance variable, let 713 // LookupInObjCMethod build the appropriate expression to 714 // reference the ivar. 715 // FIXME: This is a gross hack. 716 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 717 Result.clear(); 718 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 719 return E; 720 } 721 722 goto Corrected; 723 } 724 } 725 726 // We failed to correct; just fall through and let the parser deal with it. 727 Result.suppressDiagnostics(); 728 return NameClassification::Unknown(); 729 730 case LookupResult::NotFoundInCurrentInstantiation: { 731 // We performed name lookup into the current instantiation, and there were 732 // dependent bases, so we treat this result the same way as any other 733 // dependent nested-name-specifier. 734 735 // C++ [temp.res]p2: 736 // A name used in a template declaration or definition and that is 737 // dependent on a template-parameter is assumed not to name a type 738 // unless the applicable name lookup finds a type name or the name is 739 // qualified by the keyword typename. 740 // 741 // FIXME: If the next token is '<', we might want to ask the parser to 742 // perform some heroics to see if we actually have a 743 // template-argument-list, which would indicate a missing 'template' 744 // keyword here. 745 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 746 NameInfo, IsAddressOfOperand, 747 /*TemplateArgs=*/0); 748 } 749 750 case LookupResult::Found: 751 case LookupResult::FoundOverloaded: 752 case LookupResult::FoundUnresolvedValue: 753 break; 754 755 case LookupResult::Ambiguous: 756 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 757 hasAnyAcceptableTemplateNames(Result)) { 758 // C++ [temp.local]p3: 759 // A lookup that finds an injected-class-name (10.2) can result in an 760 // ambiguity in certain cases (for example, if it is found in more than 761 // one base class). If all of the injected-class-names that are found 762 // refer to specializations of the same class template, and if the name 763 // is followed by a template-argument-list, the reference refers to the 764 // class template itself and not a specialization thereof, and is not 765 // ambiguous. 766 // 767 // This filtering can make an ambiguous result into an unambiguous one, 768 // so try again after filtering out template names. 769 FilterAcceptableTemplateNames(Result); 770 if (!Result.isAmbiguous()) { 771 IsFilteredTemplateName = true; 772 break; 773 } 774 } 775 776 // Diagnose the ambiguity and return an error. 777 return NameClassification::Error(); 778 } 779 780 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 781 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 782 // C++ [temp.names]p3: 783 // After name lookup (3.4) finds that a name is a template-name or that 784 // an operator-function-id or a literal- operator-id refers to a set of 785 // overloaded functions any member of which is a function template if 786 // this is followed by a <, the < is always taken as the delimiter of a 787 // template-argument-list and never as the less-than operator. 788 if (!IsFilteredTemplateName) 789 FilterAcceptableTemplateNames(Result); 790 791 if (!Result.empty()) { 792 bool IsFunctionTemplate; 793 TemplateName Template; 794 if (Result.end() - Result.begin() > 1) { 795 IsFunctionTemplate = true; 796 Template = Context.getOverloadedTemplateName(Result.begin(), 797 Result.end()); 798 } else { 799 TemplateDecl *TD 800 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 801 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 802 803 if (SS.isSet() && !SS.isInvalid()) 804 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 805 /*TemplateKeyword=*/false, 806 TD); 807 else 808 Template = TemplateName(TD); 809 } 810 811 if (IsFunctionTemplate) { 812 // Function templates always go through overload resolution, at which 813 // point we'll perform the various checks (e.g., accessibility) we need 814 // to based on which function we selected. 815 Result.suppressDiagnostics(); 816 817 return NameClassification::FunctionTemplate(Template); 818 } 819 820 return NameClassification::TypeTemplate(Template); 821 } 822 } 823 824 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 825 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 826 DiagnoseUseOfDecl(Type, NameLoc); 827 QualType T = Context.getTypeDeclType(Type); 828 if (SS.isNotEmpty()) 829 return buildNestedType(*this, SS, T, NameLoc); 830 return ParsedType::make(T); 831 } 832 833 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 834 if (!Class) { 835 // FIXME: It's unfortunate that we don't have a Type node for handling this. 836 if (ObjCCompatibleAliasDecl *Alias 837 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 838 Class = Alias->getClassInterface(); 839 } 840 841 if (Class) { 842 DiagnoseUseOfDecl(Class, NameLoc); 843 844 if (NextToken.is(tok::period)) { 845 // Interface. <something> is parsed as a property reference expression. 846 // Just return "unknown" as a fall-through for now. 847 Result.suppressDiagnostics(); 848 return NameClassification::Unknown(); 849 } 850 851 QualType T = Context.getObjCInterfaceType(Class); 852 return ParsedType::make(T); 853 } 854 855 // We can have a type template here if we're classifying a template argument. 856 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 857 return NameClassification::TypeTemplate( 858 TemplateName(cast<TemplateDecl>(FirstDecl))); 859 860 // Check for a tag type hidden by a non-type decl in a few cases where it 861 // seems likely a type is wanted instead of the non-type that was found. 862 if (!getLangOpts().ObjC1) { 863 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 864 if ((NextToken.is(tok::identifier) || 865 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 866 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 867 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 868 DiagnoseUseOfDecl(Type, NameLoc); 869 QualType T = Context.getTypeDeclType(Type); 870 if (SS.isNotEmpty()) 871 return buildNestedType(*this, SS, T, NameLoc); 872 return ParsedType::make(T); 873 } 874 } 875 876 if (FirstDecl->isCXXClassMember()) 877 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 878 879 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 880 return BuildDeclarationNameExpr(SS, Result, ADL); 881} 882 883// Determines the context to return to after temporarily entering a 884// context. This depends in an unnecessarily complicated way on the 885// exact ordering of callbacks from the parser. 886DeclContext *Sema::getContainingDC(DeclContext *DC) { 887 888 // Functions defined inline within classes aren't parsed until we've 889 // finished parsing the top-level class, so the top-level class is 890 // the context we'll need to return to. 891 if (isa<FunctionDecl>(DC)) { 892 DC = DC->getLexicalParent(); 893 894 // A function not defined within a class will always return to its 895 // lexical context. 896 if (!isa<CXXRecordDecl>(DC)) 897 return DC; 898 899 // A C++ inline method/friend is parsed *after* the topmost class 900 // it was declared in is fully parsed ("complete"); the topmost 901 // class is the context we need to return to. 902 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 903 DC = RD; 904 905 // Return the declaration context of the topmost class the inline method is 906 // declared in. 907 return DC; 908 } 909 910 return DC->getLexicalParent(); 911} 912 913void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 914 assert(getContainingDC(DC) == CurContext && 915 "The next DeclContext should be lexically contained in the current one."); 916 CurContext = DC; 917 S->setEntity(DC); 918} 919 920void Sema::PopDeclContext() { 921 assert(CurContext && "DeclContext imbalance!"); 922 923 CurContext = getContainingDC(CurContext); 924 assert(CurContext && "Popped translation unit!"); 925} 926 927/// EnterDeclaratorContext - Used when we must lookup names in the context 928/// of a declarator's nested name specifier. 929/// 930void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 931 // C++0x [basic.lookup.unqual]p13: 932 // A name used in the definition of a static data member of class 933 // X (after the qualified-id of the static member) is looked up as 934 // if the name was used in a member function of X. 935 // C++0x [basic.lookup.unqual]p14: 936 // If a variable member of a namespace is defined outside of the 937 // scope of its namespace then any name used in the definition of 938 // the variable member (after the declarator-id) is looked up as 939 // if the definition of the variable member occurred in its 940 // namespace. 941 // Both of these imply that we should push a scope whose context 942 // is the semantic context of the declaration. We can't use 943 // PushDeclContext here because that context is not necessarily 944 // lexically contained in the current context. Fortunately, 945 // the containing scope should have the appropriate information. 946 947 assert(!S->getEntity() && "scope already has entity"); 948 949#ifndef NDEBUG 950 Scope *Ancestor = S->getParent(); 951 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 952 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 953#endif 954 955 CurContext = DC; 956 S->setEntity(DC); 957} 958 959void Sema::ExitDeclaratorContext(Scope *S) { 960 assert(S->getEntity() == CurContext && "Context imbalance!"); 961 962 // Switch back to the lexical context. The safety of this is 963 // enforced by an assert in EnterDeclaratorContext. 964 Scope *Ancestor = S->getParent(); 965 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 966 CurContext = (DeclContext*) Ancestor->getEntity(); 967 968 // We don't need to do anything with the scope, which is going to 969 // disappear. 970} 971 972 973void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 974 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 975 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 976 // We assume that the caller has already called 977 // ActOnReenterTemplateScope 978 FD = TFD->getTemplatedDecl(); 979 } 980 if (!FD) 981 return; 982 983 // Same implementation as PushDeclContext, but enters the context 984 // from the lexical parent, rather than the top-level class. 985 assert(CurContext == FD->getLexicalParent() && 986 "The next DeclContext should be lexically contained in the current one."); 987 CurContext = FD; 988 S->setEntity(CurContext); 989 990 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 991 ParmVarDecl *Param = FD->getParamDecl(P); 992 // If the parameter has an identifier, then add it to the scope 993 if (Param->getIdentifier()) { 994 S->AddDecl(Param); 995 IdResolver.AddDecl(Param); 996 } 997 } 998} 999 1000 1001void Sema::ActOnExitFunctionContext() { 1002 // Same implementation as PopDeclContext, but returns to the lexical parent, 1003 // rather than the top-level class. 1004 assert(CurContext && "DeclContext imbalance!"); 1005 CurContext = CurContext->getLexicalParent(); 1006 assert(CurContext && "Popped translation unit!"); 1007} 1008 1009 1010/// \brief Determine whether we allow overloading of the function 1011/// PrevDecl with another declaration. 1012/// 1013/// This routine determines whether overloading is possible, not 1014/// whether some new function is actually an overload. It will return 1015/// true in C++ (where we can always provide overloads) or, as an 1016/// extension, in C when the previous function is already an 1017/// overloaded function declaration or has the "overloadable" 1018/// attribute. 1019static bool AllowOverloadingOfFunction(LookupResult &Previous, 1020 ASTContext &Context) { 1021 if (Context.getLangOpts().CPlusPlus) 1022 return true; 1023 1024 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1025 return true; 1026 1027 return (Previous.getResultKind() == LookupResult::Found 1028 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1029} 1030 1031/// Add this decl to the scope shadowed decl chains. 1032void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1033 // Move up the scope chain until we find the nearest enclosing 1034 // non-transparent context. The declaration will be introduced into this 1035 // scope. 1036 while (S->getEntity() && 1037 ((DeclContext *)S->getEntity())->isTransparentContext()) 1038 S = S->getParent(); 1039 1040 // Add scoped declarations into their context, so that they can be 1041 // found later. Declarations without a context won't be inserted 1042 // into any context. 1043 if (AddToContext) 1044 CurContext->addDecl(D); 1045 1046 // Out-of-line definitions shouldn't be pushed into scope in C++. 1047 // Out-of-line variable and function definitions shouldn't even in C. 1048 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 1049 D->isOutOfLine() && 1050 !D->getDeclContext()->getRedeclContext()->Equals( 1051 D->getLexicalDeclContext()->getRedeclContext())) 1052 return; 1053 1054 // Template instantiations should also not be pushed into scope. 1055 if (isa<FunctionDecl>(D) && 1056 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1057 return; 1058 1059 // If this replaces anything in the current scope, 1060 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1061 IEnd = IdResolver.end(); 1062 for (; I != IEnd; ++I) { 1063 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1064 S->RemoveDecl(*I); 1065 IdResolver.RemoveDecl(*I); 1066 1067 // Should only need to replace one decl. 1068 break; 1069 } 1070 } 1071 1072 S->AddDecl(D); 1073 1074 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1075 // Implicitly-generated labels may end up getting generated in an order that 1076 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1077 // the label at the appropriate place in the identifier chain. 1078 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1079 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1080 if (IDC == CurContext) { 1081 if (!S->isDeclScope(*I)) 1082 continue; 1083 } else if (IDC->Encloses(CurContext)) 1084 break; 1085 } 1086 1087 IdResolver.InsertDeclAfter(I, D); 1088 } else { 1089 IdResolver.AddDecl(D); 1090 } 1091} 1092 1093void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1094 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1095 TUScope->AddDecl(D); 1096} 1097 1098bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 1099 bool ExplicitInstantiationOrSpecialization) { 1100 return IdResolver.isDeclInScope(D, Ctx, Context, S, 1101 ExplicitInstantiationOrSpecialization); 1102} 1103 1104Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1105 DeclContext *TargetDC = DC->getPrimaryContext(); 1106 do { 1107 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 1108 if (ScopeDC->getPrimaryContext() == TargetDC) 1109 return S; 1110 } while ((S = S->getParent())); 1111 1112 return 0; 1113} 1114 1115static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1116 DeclContext*, 1117 ASTContext&); 1118 1119/// Filters out lookup results that don't fall within the given scope 1120/// as determined by isDeclInScope. 1121void Sema::FilterLookupForScope(LookupResult &R, 1122 DeclContext *Ctx, Scope *S, 1123 bool ConsiderLinkage, 1124 bool ExplicitInstantiationOrSpecialization) { 1125 LookupResult::Filter F = R.makeFilter(); 1126 while (F.hasNext()) { 1127 NamedDecl *D = F.next(); 1128 1129 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1130 continue; 1131 1132 if (ConsiderLinkage && 1133 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1134 continue; 1135 1136 F.erase(); 1137 } 1138 1139 F.done(); 1140} 1141 1142static bool isUsingDecl(NamedDecl *D) { 1143 return isa<UsingShadowDecl>(D) || 1144 isa<UnresolvedUsingTypenameDecl>(D) || 1145 isa<UnresolvedUsingValueDecl>(D); 1146} 1147 1148/// Removes using shadow declarations from the lookup results. 1149static void RemoveUsingDecls(LookupResult &R) { 1150 LookupResult::Filter F = R.makeFilter(); 1151 while (F.hasNext()) 1152 if (isUsingDecl(F.next())) 1153 F.erase(); 1154 1155 F.done(); 1156} 1157 1158/// \brief Check for this common pattern: 1159/// @code 1160/// class S { 1161/// S(const S&); // DO NOT IMPLEMENT 1162/// void operator=(const S&); // DO NOT IMPLEMENT 1163/// }; 1164/// @endcode 1165static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1166 // FIXME: Should check for private access too but access is set after we get 1167 // the decl here. 1168 if (D->doesThisDeclarationHaveABody()) 1169 return false; 1170 1171 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1172 return CD->isCopyConstructor(); 1173 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1174 return Method->isCopyAssignmentOperator(); 1175 return false; 1176} 1177 1178bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1179 assert(D); 1180 1181 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1182 return false; 1183 1184 // Ignore class templates. 1185 if (D->getDeclContext()->isDependentContext() || 1186 D->getLexicalDeclContext()->isDependentContext()) 1187 return false; 1188 1189 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1190 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1191 return false; 1192 1193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1194 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1195 return false; 1196 } else { 1197 // 'static inline' functions are used in headers; don't warn. 1198 if (FD->getStorageClass() == SC_Static && 1199 FD->isInlineSpecified()) 1200 return false; 1201 } 1202 1203 if (FD->doesThisDeclarationHaveABody() && 1204 Context.DeclMustBeEmitted(FD)) 1205 return false; 1206 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1207 // Don't warn on variables of const-qualified or reference type, since their 1208 // values can be used even if though they're not odr-used, and because const 1209 // qualified variables can appear in headers in contexts where they're not 1210 // intended to be used. 1211 // FIXME: Use more principled rules for these exemptions. 1212 if (!VD->isFileVarDecl() || 1213 VD->getType().isConstQualified() || 1214 VD->getType()->isReferenceType() || 1215 Context.DeclMustBeEmitted(VD)) 1216 return false; 1217 1218 if (VD->isStaticDataMember() && 1219 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1220 return false; 1221 1222 } else { 1223 return false; 1224 } 1225 1226 // Only warn for unused decls internal to the translation unit. 1227 if (D->getLinkage() == ExternalLinkage) 1228 return false; 1229 1230 return true; 1231} 1232 1233void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1234 if (!D) 1235 return; 1236 1237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1238 const FunctionDecl *First = FD->getFirstDeclaration(); 1239 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1240 return; // First should already be in the vector. 1241 } 1242 1243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1244 const VarDecl *First = VD->getFirstDeclaration(); 1245 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1246 return; // First should already be in the vector. 1247 } 1248 1249 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1250 UnusedFileScopedDecls.push_back(D); 1251} 1252 1253static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1254 if (D->isInvalidDecl()) 1255 return false; 1256 1257 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1258 return false; 1259 1260 if (isa<LabelDecl>(D)) 1261 return true; 1262 1263 // White-list anything that isn't a local variable. 1264 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1265 !D->getDeclContext()->isFunctionOrMethod()) 1266 return false; 1267 1268 // Types of valid local variables should be complete, so this should succeed. 1269 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1270 1271 // White-list anything with an __attribute__((unused)) type. 1272 QualType Ty = VD->getType(); 1273 1274 // Only look at the outermost level of typedef. 1275 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1276 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1277 return false; 1278 } 1279 1280 // If we failed to complete the type for some reason, or if the type is 1281 // dependent, don't diagnose the variable. 1282 if (Ty->isIncompleteType() || Ty->isDependentType()) 1283 return false; 1284 1285 if (const TagType *TT = Ty->getAs<TagType>()) { 1286 const TagDecl *Tag = TT->getDecl(); 1287 if (Tag->hasAttr<UnusedAttr>()) 1288 return false; 1289 1290 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1291 if (!RD->hasTrivialDestructor()) 1292 return false; 1293 1294 if (const Expr *Init = VD->getInit()) { 1295 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1296 Init = Cleanups->getSubExpr(); 1297 const CXXConstructExpr *Construct = 1298 dyn_cast<CXXConstructExpr>(Init); 1299 if (Construct && !Construct->isElidable()) { 1300 CXXConstructorDecl *CD = Construct->getConstructor(); 1301 if (!CD->isTrivial()) 1302 return false; 1303 } 1304 } 1305 } 1306 } 1307 1308 // TODO: __attribute__((unused)) templates? 1309 } 1310 1311 return true; 1312} 1313 1314static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1315 FixItHint &Hint) { 1316 if (isa<LabelDecl>(D)) { 1317 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1318 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1319 if (AfterColon.isInvalid()) 1320 return; 1321 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1322 getCharRange(D->getLocStart(), AfterColon)); 1323 } 1324 return; 1325} 1326 1327/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1328/// unless they are marked attr(unused). 1329void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1330 FixItHint Hint; 1331 if (!ShouldDiagnoseUnusedDecl(D)) 1332 return; 1333 1334 GenerateFixForUnusedDecl(D, Context, Hint); 1335 1336 unsigned DiagID; 1337 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1338 DiagID = diag::warn_unused_exception_param; 1339 else if (isa<LabelDecl>(D)) 1340 DiagID = diag::warn_unused_label; 1341 else 1342 DiagID = diag::warn_unused_variable; 1343 1344 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1345} 1346 1347static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1348 // Verify that we have no forward references left. If so, there was a goto 1349 // or address of a label taken, but no definition of it. Label fwd 1350 // definitions are indicated with a null substmt. 1351 if (L->getStmt() == 0) 1352 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1353} 1354 1355void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1356 if (S->decl_empty()) return; 1357 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1358 "Scope shouldn't contain decls!"); 1359 1360 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1361 I != E; ++I) { 1362 Decl *TmpD = (*I); 1363 assert(TmpD && "This decl didn't get pushed??"); 1364 1365 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1366 NamedDecl *D = cast<NamedDecl>(TmpD); 1367 1368 if (!D->getDeclName()) continue; 1369 1370 // Diagnose unused variables in this scope. 1371 if (!S->hasErrorOccurred()) 1372 DiagnoseUnusedDecl(D); 1373 1374 // If this was a forward reference to a label, verify it was defined. 1375 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1376 CheckPoppedLabel(LD, *this); 1377 1378 // Remove this name from our lexical scope. 1379 IdResolver.RemoveDecl(D); 1380 } 1381} 1382 1383void Sema::ActOnStartFunctionDeclarator() { 1384 ++InFunctionDeclarator; 1385} 1386 1387void Sema::ActOnEndFunctionDeclarator() { 1388 assert(InFunctionDeclarator); 1389 --InFunctionDeclarator; 1390} 1391 1392/// \brief Look for an Objective-C class in the translation unit. 1393/// 1394/// \param Id The name of the Objective-C class we're looking for. If 1395/// typo-correction fixes this name, the Id will be updated 1396/// to the fixed name. 1397/// 1398/// \param IdLoc The location of the name in the translation unit. 1399/// 1400/// \param DoTypoCorrection If true, this routine will attempt typo correction 1401/// if there is no class with the given name. 1402/// 1403/// \returns The declaration of the named Objective-C class, or NULL if the 1404/// class could not be found. 1405ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1406 SourceLocation IdLoc, 1407 bool DoTypoCorrection) { 1408 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1409 // creation from this context. 1410 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1411 1412 if (!IDecl && DoTypoCorrection) { 1413 // Perform typo correction at the given location, but only if we 1414 // find an Objective-C class name. 1415 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1416 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1417 LookupOrdinaryName, TUScope, NULL, 1418 Validator)) { 1419 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1420 Diag(IdLoc, diag::err_undef_interface_suggest) 1421 << Id << IDecl->getDeclName() 1422 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1423 Diag(IDecl->getLocation(), diag::note_previous_decl) 1424 << IDecl->getDeclName(); 1425 1426 Id = IDecl->getIdentifier(); 1427 } 1428 } 1429 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1430 // This routine must always return a class definition, if any. 1431 if (Def && Def->getDefinition()) 1432 Def = Def->getDefinition(); 1433 return Def; 1434} 1435 1436/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1437/// from S, where a non-field would be declared. This routine copes 1438/// with the difference between C and C++ scoping rules in structs and 1439/// unions. For example, the following code is well-formed in C but 1440/// ill-formed in C++: 1441/// @code 1442/// struct S6 { 1443/// enum { BAR } e; 1444/// }; 1445/// 1446/// void test_S6() { 1447/// struct S6 a; 1448/// a.e = BAR; 1449/// } 1450/// @endcode 1451/// For the declaration of BAR, this routine will return a different 1452/// scope. The scope S will be the scope of the unnamed enumeration 1453/// within S6. In C++, this routine will return the scope associated 1454/// with S6, because the enumeration's scope is a transparent 1455/// context but structures can contain non-field names. In C, this 1456/// routine will return the translation unit scope, since the 1457/// enumeration's scope is a transparent context and structures cannot 1458/// contain non-field names. 1459Scope *Sema::getNonFieldDeclScope(Scope *S) { 1460 while (((S->getFlags() & Scope::DeclScope) == 0) || 1461 (S->getEntity() && 1462 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1463 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1464 S = S->getParent(); 1465 return S; 1466} 1467 1468/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1469/// file scope. lazily create a decl for it. ForRedeclaration is true 1470/// if we're creating this built-in in anticipation of redeclaring the 1471/// built-in. 1472NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1473 Scope *S, bool ForRedeclaration, 1474 SourceLocation Loc) { 1475 Builtin::ID BID = (Builtin::ID)bid; 1476 1477 ASTContext::GetBuiltinTypeError Error; 1478 QualType R = Context.GetBuiltinType(BID, Error); 1479 switch (Error) { 1480 case ASTContext::GE_None: 1481 // Okay 1482 break; 1483 1484 case ASTContext::GE_Missing_stdio: 1485 if (ForRedeclaration) 1486 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1487 << Context.BuiltinInfo.GetName(BID); 1488 return 0; 1489 1490 case ASTContext::GE_Missing_setjmp: 1491 if (ForRedeclaration) 1492 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1493 << Context.BuiltinInfo.GetName(BID); 1494 return 0; 1495 1496 case ASTContext::GE_Missing_ucontext: 1497 if (ForRedeclaration) 1498 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1499 << Context.BuiltinInfo.GetName(BID); 1500 return 0; 1501 } 1502 1503 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1504 Diag(Loc, diag::ext_implicit_lib_function_decl) 1505 << Context.BuiltinInfo.GetName(BID) 1506 << R; 1507 if (Context.BuiltinInfo.getHeaderName(BID) && 1508 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1509 != DiagnosticsEngine::Ignored) 1510 Diag(Loc, diag::note_please_include_header) 1511 << Context.BuiltinInfo.getHeaderName(BID) 1512 << Context.BuiltinInfo.GetName(BID); 1513 } 1514 1515 FunctionDecl *New = FunctionDecl::Create(Context, 1516 Context.getTranslationUnitDecl(), 1517 Loc, Loc, II, R, /*TInfo=*/0, 1518 SC_Extern, 1519 SC_None, false, 1520 /*hasPrototype=*/true); 1521 New->setImplicit(); 1522 1523 // Create Decl objects for each parameter, adding them to the 1524 // FunctionDecl. 1525 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1526 SmallVector<ParmVarDecl*, 16> Params; 1527 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1528 ParmVarDecl *parm = 1529 ParmVarDecl::Create(Context, New, SourceLocation(), 1530 SourceLocation(), 0, 1531 FT->getArgType(i), /*TInfo=*/0, 1532 SC_None, SC_None, 0); 1533 parm->setScopeInfo(0, i); 1534 Params.push_back(parm); 1535 } 1536 New->setParams(Params); 1537 } 1538 1539 AddKnownFunctionAttributes(New); 1540 1541 // TUScope is the translation-unit scope to insert this function into. 1542 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1543 // relate Scopes to DeclContexts, and probably eliminate CurContext 1544 // entirely, but we're not there yet. 1545 DeclContext *SavedContext = CurContext; 1546 CurContext = Context.getTranslationUnitDecl(); 1547 PushOnScopeChains(New, TUScope); 1548 CurContext = SavedContext; 1549 return New; 1550} 1551 1552bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1553 QualType OldType; 1554 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1555 OldType = OldTypedef->getUnderlyingType(); 1556 else 1557 OldType = Context.getTypeDeclType(Old); 1558 QualType NewType = New->getUnderlyingType(); 1559 1560 if (NewType->isVariablyModifiedType()) { 1561 // Must not redefine a typedef with a variably-modified type. 1562 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1563 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1564 << Kind << NewType; 1565 if (Old->getLocation().isValid()) 1566 Diag(Old->getLocation(), diag::note_previous_definition); 1567 New->setInvalidDecl(); 1568 return true; 1569 } 1570 1571 if (OldType != NewType && 1572 !OldType->isDependentType() && 1573 !NewType->isDependentType() && 1574 !Context.hasSameType(OldType, NewType)) { 1575 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1576 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1577 << Kind << NewType << OldType; 1578 if (Old->getLocation().isValid()) 1579 Diag(Old->getLocation(), diag::note_previous_definition); 1580 New->setInvalidDecl(); 1581 return true; 1582 } 1583 return false; 1584} 1585 1586/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1587/// same name and scope as a previous declaration 'Old'. Figure out 1588/// how to resolve this situation, merging decls or emitting 1589/// diagnostics as appropriate. If there was an error, set New to be invalid. 1590/// 1591void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1592 // If the new decl is known invalid already, don't bother doing any 1593 // merging checks. 1594 if (New->isInvalidDecl()) return; 1595 1596 // Allow multiple definitions for ObjC built-in typedefs. 1597 // FIXME: Verify the underlying types are equivalent! 1598 if (getLangOpts().ObjC1) { 1599 const IdentifierInfo *TypeID = New->getIdentifier(); 1600 switch (TypeID->getLength()) { 1601 default: break; 1602 case 2: 1603 { 1604 if (!TypeID->isStr("id")) 1605 break; 1606 QualType T = New->getUnderlyingType(); 1607 if (!T->isPointerType()) 1608 break; 1609 if (!T->isVoidPointerType()) { 1610 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1611 if (!PT->isStructureType()) 1612 break; 1613 } 1614 Context.setObjCIdRedefinitionType(T); 1615 // Install the built-in type for 'id', ignoring the current definition. 1616 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1617 return; 1618 } 1619 case 5: 1620 if (!TypeID->isStr("Class")) 1621 break; 1622 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1623 // Install the built-in type for 'Class', ignoring the current definition. 1624 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1625 return; 1626 case 3: 1627 if (!TypeID->isStr("SEL")) 1628 break; 1629 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1630 // Install the built-in type for 'SEL', ignoring the current definition. 1631 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1632 return; 1633 } 1634 // Fall through - the typedef name was not a builtin type. 1635 } 1636 1637 // Verify the old decl was also a type. 1638 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1639 if (!Old) { 1640 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1641 << New->getDeclName(); 1642 1643 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1644 if (OldD->getLocation().isValid()) 1645 Diag(OldD->getLocation(), diag::note_previous_definition); 1646 1647 return New->setInvalidDecl(); 1648 } 1649 1650 // If the old declaration is invalid, just give up here. 1651 if (Old->isInvalidDecl()) 1652 return New->setInvalidDecl(); 1653 1654 // If the typedef types are not identical, reject them in all languages and 1655 // with any extensions enabled. 1656 if (isIncompatibleTypedef(Old, New)) 1657 return; 1658 1659 // The types match. Link up the redeclaration chain if the old 1660 // declaration was a typedef. 1661 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1662 New->setPreviousDeclaration(Typedef); 1663 1664 if (getLangOpts().MicrosoftExt) 1665 return; 1666 1667 if (getLangOpts().CPlusPlus) { 1668 // C++ [dcl.typedef]p2: 1669 // In a given non-class scope, a typedef specifier can be used to 1670 // redefine the name of any type declared in that scope to refer 1671 // to the type to which it already refers. 1672 if (!isa<CXXRecordDecl>(CurContext)) 1673 return; 1674 1675 // C++0x [dcl.typedef]p4: 1676 // In a given class scope, a typedef specifier can be used to redefine 1677 // any class-name declared in that scope that is not also a typedef-name 1678 // to refer to the type to which it already refers. 1679 // 1680 // This wording came in via DR424, which was a correction to the 1681 // wording in DR56, which accidentally banned code like: 1682 // 1683 // struct S { 1684 // typedef struct A { } A; 1685 // }; 1686 // 1687 // in the C++03 standard. We implement the C++0x semantics, which 1688 // allow the above but disallow 1689 // 1690 // struct S { 1691 // typedef int I; 1692 // typedef int I; 1693 // }; 1694 // 1695 // since that was the intent of DR56. 1696 if (!isa<TypedefNameDecl>(Old)) 1697 return; 1698 1699 Diag(New->getLocation(), diag::err_redefinition) 1700 << New->getDeclName(); 1701 Diag(Old->getLocation(), diag::note_previous_definition); 1702 return New->setInvalidDecl(); 1703 } 1704 1705 // Modules always permit redefinition of typedefs, as does C11. 1706 if (getLangOpts().Modules || getLangOpts().C11) 1707 return; 1708 1709 // If we have a redefinition of a typedef in C, emit a warning. This warning 1710 // is normally mapped to an error, but can be controlled with 1711 // -Wtypedef-redefinition. If either the original or the redefinition is 1712 // in a system header, don't emit this for compatibility with GCC. 1713 if (getDiagnostics().getSuppressSystemWarnings() && 1714 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1715 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1716 return; 1717 1718 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1719 << New->getDeclName(); 1720 Diag(Old->getLocation(), diag::note_previous_definition); 1721 return; 1722} 1723 1724/// DeclhasAttr - returns true if decl Declaration already has the target 1725/// attribute. 1726static bool 1727DeclHasAttr(const Decl *D, const Attr *A) { 1728 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1729 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1730 // responsible for making sure they are consistent. 1731 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1732 if (AA) 1733 return false; 1734 1735 // The following thread safety attributes can also be duplicated. 1736 switch (A->getKind()) { 1737 case attr::ExclusiveLocksRequired: 1738 case attr::SharedLocksRequired: 1739 case attr::LocksExcluded: 1740 case attr::ExclusiveLockFunction: 1741 case attr::SharedLockFunction: 1742 case attr::UnlockFunction: 1743 case attr::ExclusiveTrylockFunction: 1744 case attr::SharedTrylockFunction: 1745 case attr::GuardedBy: 1746 case attr::PtGuardedBy: 1747 case attr::AcquiredBefore: 1748 case attr::AcquiredAfter: 1749 return false; 1750 default: 1751 ; 1752 } 1753 1754 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1755 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1756 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1757 if ((*i)->getKind() == A->getKind()) { 1758 if (Ann) { 1759 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1760 return true; 1761 continue; 1762 } 1763 // FIXME: Don't hardcode this check 1764 if (OA && isa<OwnershipAttr>(*i)) 1765 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1766 return true; 1767 } 1768 1769 return false; 1770} 1771 1772bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) { 1773 InheritableAttr *NewAttr = NULL; 1774 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1775 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1776 AA->getIntroduced(), AA->getDeprecated(), 1777 AA->getObsoleted(), AA->getUnavailable(), 1778 AA->getMessage()); 1779 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1780 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility()); 1781 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1782 NewAttr = mergeDLLImportAttr(D, ImportA->getRange()); 1783 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1784 NewAttr = mergeDLLExportAttr(D, ExportA->getRange()); 1785 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1786 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(), 1787 FA->getFormatIdx(), FA->getFirstArg()); 1788 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1789 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName()); 1790 else if (!DeclHasAttr(D, Attr)) 1791 NewAttr = cast<InheritableAttr>(Attr->clone(Context)); 1792 1793 if (NewAttr) { 1794 NewAttr->setInherited(true); 1795 D->addAttr(NewAttr); 1796 return true; 1797 } 1798 1799 return false; 1800} 1801 1802static const Decl *getDefinition(const Decl *D) { 1803 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1804 return TD->getDefinition(); 1805 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1806 return VD->getDefinition(); 1807 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1808 const FunctionDecl* Def; 1809 if (FD->hasBody(Def)) 1810 return Def; 1811 } 1812 return NULL; 1813} 1814 1815static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1816 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 1817 I != E; ++I) { 1818 Attr *Attribute = *I; 1819 if (Attribute->getKind() == Kind) 1820 return true; 1821 } 1822 return false; 1823} 1824 1825/// checkNewAttributesAfterDef - If we already have a definition, check that 1826/// there are no new attributes in this declaration. 1827static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 1828 if (!New->hasAttrs()) 1829 return; 1830 1831 const Decl *Def = getDefinition(Old); 1832 if (!Def || Def == New) 1833 return; 1834 1835 AttrVec &NewAttributes = New->getAttrs(); 1836 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 1837 const Attr *NewAttribute = NewAttributes[I]; 1838 if (hasAttribute(Def, NewAttribute->getKind())) { 1839 ++I; 1840 continue; // regular attr merging will take care of validating this. 1841 } 1842 S.Diag(NewAttribute->getLocation(), 1843 diag::warn_attribute_precede_definition); 1844 S.Diag(Def->getLocation(), diag::note_previous_definition); 1845 NewAttributes.erase(NewAttributes.begin() + I); 1846 --E; 1847 } 1848} 1849 1850/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1851void Sema::mergeDeclAttributes(Decl *New, Decl *Old, 1852 bool MergeDeprecation) { 1853 // attributes declared post-definition are currently ignored 1854 checkNewAttributesAfterDef(*this, New, Old); 1855 1856 if (!Old->hasAttrs()) 1857 return; 1858 1859 bool foundAny = New->hasAttrs(); 1860 1861 // Ensure that any moving of objects within the allocated map is done before 1862 // we process them. 1863 if (!foundAny) New->setAttrs(AttrVec()); 1864 1865 for (specific_attr_iterator<InheritableAttr> 1866 i = Old->specific_attr_begin<InheritableAttr>(), 1867 e = Old->specific_attr_end<InheritableAttr>(); 1868 i != e; ++i) { 1869 // Ignore deprecated/unavailable/availability attributes if requested. 1870 if (!MergeDeprecation && 1871 (isa<DeprecatedAttr>(*i) || 1872 isa<UnavailableAttr>(*i) || 1873 isa<AvailabilityAttr>(*i))) 1874 continue; 1875 1876 if (mergeDeclAttribute(New, *i)) 1877 foundAny = true; 1878 } 1879 1880 if (!foundAny) New->dropAttrs(); 1881} 1882 1883/// mergeParamDeclAttributes - Copy attributes from the old parameter 1884/// to the new one. 1885static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1886 const ParmVarDecl *oldDecl, 1887 ASTContext &C) { 1888 if (!oldDecl->hasAttrs()) 1889 return; 1890 1891 bool foundAny = newDecl->hasAttrs(); 1892 1893 // Ensure that any moving of objects within the allocated map is 1894 // done before we process them. 1895 if (!foundAny) newDecl->setAttrs(AttrVec()); 1896 1897 for (specific_attr_iterator<InheritableParamAttr> 1898 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1899 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1900 if (!DeclHasAttr(newDecl, *i)) { 1901 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1902 newAttr->setInherited(true); 1903 newDecl->addAttr(newAttr); 1904 foundAny = true; 1905 } 1906 } 1907 1908 if (!foundAny) newDecl->dropAttrs(); 1909} 1910 1911namespace { 1912 1913/// Used in MergeFunctionDecl to keep track of function parameters in 1914/// C. 1915struct GNUCompatibleParamWarning { 1916 ParmVarDecl *OldParm; 1917 ParmVarDecl *NewParm; 1918 QualType PromotedType; 1919}; 1920 1921} 1922 1923/// getSpecialMember - get the special member enum for a method. 1924Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1925 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1926 if (Ctor->isDefaultConstructor()) 1927 return Sema::CXXDefaultConstructor; 1928 1929 if (Ctor->isCopyConstructor()) 1930 return Sema::CXXCopyConstructor; 1931 1932 if (Ctor->isMoveConstructor()) 1933 return Sema::CXXMoveConstructor; 1934 } else if (isa<CXXDestructorDecl>(MD)) { 1935 return Sema::CXXDestructor; 1936 } else if (MD->isCopyAssignmentOperator()) { 1937 return Sema::CXXCopyAssignment; 1938 } else if (MD->isMoveAssignmentOperator()) { 1939 return Sema::CXXMoveAssignment; 1940 } 1941 1942 return Sema::CXXInvalid; 1943} 1944 1945/// canRedefineFunction - checks if a function can be redefined. Currently, 1946/// only extern inline functions can be redefined, and even then only in 1947/// GNU89 mode. 1948static bool canRedefineFunction(const FunctionDecl *FD, 1949 const LangOptions& LangOpts) { 1950 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1951 !LangOpts.CPlusPlus && 1952 FD->isInlineSpecified() && 1953 FD->getStorageClass() == SC_Extern); 1954} 1955 1956/// Is the given calling convention the ABI default for the given 1957/// declaration? 1958static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) { 1959 CallingConv ABIDefaultCC; 1960 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 1961 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic()); 1962 } else { 1963 // Free C function or a static method. 1964 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C); 1965 } 1966 return ABIDefaultCC == CC; 1967} 1968 1969/// MergeFunctionDecl - We just parsed a function 'New' from 1970/// declarator D which has the same name and scope as a previous 1971/// declaration 'Old'. Figure out how to resolve this situation, 1972/// merging decls or emitting diagnostics as appropriate. 1973/// 1974/// In C++, New and Old must be declarations that are not 1975/// overloaded. Use IsOverload to determine whether New and Old are 1976/// overloaded, and to select the Old declaration that New should be 1977/// merged with. 1978/// 1979/// Returns true if there was an error, false otherwise. 1980bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 1981 // Verify the old decl was also a function. 1982 FunctionDecl *Old = 0; 1983 if (FunctionTemplateDecl *OldFunctionTemplate 1984 = dyn_cast<FunctionTemplateDecl>(OldD)) 1985 Old = OldFunctionTemplate->getTemplatedDecl(); 1986 else 1987 Old = dyn_cast<FunctionDecl>(OldD); 1988 if (!Old) { 1989 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1990 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1991 Diag(Shadow->getTargetDecl()->getLocation(), 1992 diag::note_using_decl_target); 1993 Diag(Shadow->getUsingDecl()->getLocation(), 1994 diag::note_using_decl) << 0; 1995 return true; 1996 } 1997 1998 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1999 << New->getDeclName(); 2000 Diag(OldD->getLocation(), diag::note_previous_definition); 2001 return true; 2002 } 2003 2004 // Determine whether the previous declaration was a definition, 2005 // implicit declaration, or a declaration. 2006 diag::kind PrevDiag; 2007 if (Old->isThisDeclarationADefinition()) 2008 PrevDiag = diag::note_previous_definition; 2009 else if (Old->isImplicit()) 2010 PrevDiag = diag::note_previous_implicit_declaration; 2011 else 2012 PrevDiag = diag::note_previous_declaration; 2013 2014 QualType OldQType = Context.getCanonicalType(Old->getType()); 2015 QualType NewQType = Context.getCanonicalType(New->getType()); 2016 2017 // Don't complain about this if we're in GNU89 mode and the old function 2018 // is an extern inline function. 2019 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2020 New->getStorageClass() == SC_Static && 2021 Old->getStorageClass() != SC_Static && 2022 !canRedefineFunction(Old, getLangOpts())) { 2023 if (getLangOpts().MicrosoftExt) { 2024 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2025 Diag(Old->getLocation(), PrevDiag); 2026 } else { 2027 Diag(New->getLocation(), diag::err_static_non_static) << New; 2028 Diag(Old->getLocation(), PrevDiag); 2029 return true; 2030 } 2031 } 2032 2033 // If a function is first declared with a calling convention, but is 2034 // later declared or defined without one, the second decl assumes the 2035 // calling convention of the first. 2036 // 2037 // It's OK if a function is first declared without a calling convention, 2038 // but is later declared or defined with the default calling convention. 2039 // 2040 // For the new decl, we have to look at the NON-canonical type to tell the 2041 // difference between a function that really doesn't have a calling 2042 // convention and one that is declared cdecl. That's because in 2043 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 2044 // because it is the default calling convention. 2045 // 2046 // Note also that we DO NOT return at this point, because we still have 2047 // other tests to run. 2048 const FunctionType *OldType = cast<FunctionType>(OldQType); 2049 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2050 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2051 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2052 bool RequiresAdjustment = false; 2053 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) { 2054 // Fast path: nothing to do. 2055 2056 // Inherit the CC from the previous declaration if it was specified 2057 // there but not here. 2058 } else if (NewTypeInfo.getCC() == CC_Default) { 2059 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2060 RequiresAdjustment = true; 2061 2062 // Don't complain about mismatches when the default CC is 2063 // effectively the same as the explict one. 2064 } else if (OldTypeInfo.getCC() == CC_Default && 2065 isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) { 2066 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2067 RequiresAdjustment = true; 2068 2069 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2070 NewTypeInfo.getCC())) { 2071 // Calling conventions really aren't compatible, so complain. 2072 Diag(New->getLocation(), diag::err_cconv_change) 2073 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2074 << (OldTypeInfo.getCC() == CC_Default) 2075 << (OldTypeInfo.getCC() == CC_Default ? "" : 2076 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2077 Diag(Old->getLocation(), diag::note_previous_declaration); 2078 return true; 2079 } 2080 2081 // FIXME: diagnose the other way around? 2082 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2083 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2084 RequiresAdjustment = true; 2085 } 2086 2087 // Merge regparm attribute. 2088 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2089 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2090 if (NewTypeInfo.getHasRegParm()) { 2091 Diag(New->getLocation(), diag::err_regparm_mismatch) 2092 << NewType->getRegParmType() 2093 << OldType->getRegParmType(); 2094 Diag(Old->getLocation(), diag::note_previous_declaration); 2095 return true; 2096 } 2097 2098 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2099 RequiresAdjustment = true; 2100 } 2101 2102 // Merge ns_returns_retained attribute. 2103 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2104 if (NewTypeInfo.getProducesResult()) { 2105 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2106 Diag(Old->getLocation(), diag::note_previous_declaration); 2107 return true; 2108 } 2109 2110 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2111 RequiresAdjustment = true; 2112 } 2113 2114 if (RequiresAdjustment) { 2115 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2116 New->setType(QualType(NewType, 0)); 2117 NewQType = Context.getCanonicalType(New->getType()); 2118 } 2119 2120 if (getLangOpts().CPlusPlus) { 2121 // (C++98 13.1p2): 2122 // Certain function declarations cannot be overloaded: 2123 // -- Function declarations that differ only in the return type 2124 // cannot be overloaded. 2125 QualType OldReturnType = OldType->getResultType(); 2126 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2127 QualType ResQT; 2128 if (OldReturnType != NewReturnType) { 2129 if (NewReturnType->isObjCObjectPointerType() 2130 && OldReturnType->isObjCObjectPointerType()) 2131 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2132 if (ResQT.isNull()) { 2133 if (New->isCXXClassMember() && New->isOutOfLine()) 2134 Diag(New->getLocation(), 2135 diag::err_member_def_does_not_match_ret_type) << New; 2136 else 2137 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2138 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2139 return true; 2140 } 2141 else 2142 NewQType = ResQT; 2143 } 2144 2145 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2146 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2147 if (OldMethod && NewMethod) { 2148 // Preserve triviality. 2149 NewMethod->setTrivial(OldMethod->isTrivial()); 2150 2151 // MSVC allows explicit template specialization at class scope: 2152 // 2 CXMethodDecls referring to the same function will be injected. 2153 // We don't want a redeclartion error. 2154 bool IsClassScopeExplicitSpecialization = 2155 OldMethod->isFunctionTemplateSpecialization() && 2156 NewMethod->isFunctionTemplateSpecialization(); 2157 bool isFriend = NewMethod->getFriendObjectKind(); 2158 2159 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2160 !IsClassScopeExplicitSpecialization) { 2161 // -- Member function declarations with the same name and the 2162 // same parameter types cannot be overloaded if any of them 2163 // is a static member function declaration. 2164 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2165 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2166 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2167 return true; 2168 } 2169 2170 // C++ [class.mem]p1: 2171 // [...] A member shall not be declared twice in the 2172 // member-specification, except that a nested class or member 2173 // class template can be declared and then later defined. 2174 if (ActiveTemplateInstantiations.empty()) { 2175 unsigned NewDiag; 2176 if (isa<CXXConstructorDecl>(OldMethod)) 2177 NewDiag = diag::err_constructor_redeclared; 2178 else if (isa<CXXDestructorDecl>(NewMethod)) 2179 NewDiag = diag::err_destructor_redeclared; 2180 else if (isa<CXXConversionDecl>(NewMethod)) 2181 NewDiag = diag::err_conv_function_redeclared; 2182 else 2183 NewDiag = diag::err_member_redeclared; 2184 2185 Diag(New->getLocation(), NewDiag); 2186 } else { 2187 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2188 << New << New->getType(); 2189 } 2190 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2191 2192 // Complain if this is an explicit declaration of a special 2193 // member that was initially declared implicitly. 2194 // 2195 // As an exception, it's okay to befriend such methods in order 2196 // to permit the implicit constructor/destructor/operator calls. 2197 } else if (OldMethod->isImplicit()) { 2198 if (isFriend) { 2199 NewMethod->setImplicit(); 2200 } else { 2201 Diag(NewMethod->getLocation(), 2202 diag::err_definition_of_implicitly_declared_member) 2203 << New << getSpecialMember(OldMethod); 2204 return true; 2205 } 2206 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2207 Diag(NewMethod->getLocation(), 2208 diag::err_definition_of_explicitly_defaulted_member) 2209 << getSpecialMember(OldMethod); 2210 return true; 2211 } 2212 } 2213 2214 // (C++98 8.3.5p3): 2215 // All declarations for a function shall agree exactly in both the 2216 // return type and the parameter-type-list. 2217 // We also want to respect all the extended bits except noreturn. 2218 2219 // noreturn should now match unless the old type info didn't have it. 2220 QualType OldQTypeForComparison = OldQType; 2221 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2222 assert(OldQType == QualType(OldType, 0)); 2223 const FunctionType *OldTypeForComparison 2224 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2225 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2226 assert(OldQTypeForComparison.isCanonical()); 2227 } 2228 2229 if (OldQTypeForComparison == NewQType) 2230 return MergeCompatibleFunctionDecls(New, Old, S); 2231 2232 // Fall through for conflicting redeclarations and redefinitions. 2233 } 2234 2235 // C: Function types need to be compatible, not identical. This handles 2236 // duplicate function decls like "void f(int); void f(enum X);" properly. 2237 if (!getLangOpts().CPlusPlus && 2238 Context.typesAreCompatible(OldQType, NewQType)) { 2239 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2240 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2241 const FunctionProtoType *OldProto = 0; 2242 if (isa<FunctionNoProtoType>(NewFuncType) && 2243 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2244 // The old declaration provided a function prototype, but the 2245 // new declaration does not. Merge in the prototype. 2246 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2247 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2248 OldProto->arg_type_end()); 2249 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2250 ParamTypes.data(), ParamTypes.size(), 2251 OldProto->getExtProtoInfo()); 2252 New->setType(NewQType); 2253 New->setHasInheritedPrototype(); 2254 2255 // Synthesize a parameter for each argument type. 2256 SmallVector<ParmVarDecl*, 16> Params; 2257 for (FunctionProtoType::arg_type_iterator 2258 ParamType = OldProto->arg_type_begin(), 2259 ParamEnd = OldProto->arg_type_end(); 2260 ParamType != ParamEnd; ++ParamType) { 2261 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2262 SourceLocation(), 2263 SourceLocation(), 0, 2264 *ParamType, /*TInfo=*/0, 2265 SC_None, SC_None, 2266 0); 2267 Param->setScopeInfo(0, Params.size()); 2268 Param->setImplicit(); 2269 Params.push_back(Param); 2270 } 2271 2272 New->setParams(Params); 2273 } 2274 2275 return MergeCompatibleFunctionDecls(New, Old, S); 2276 } 2277 2278 // GNU C permits a K&R definition to follow a prototype declaration 2279 // if the declared types of the parameters in the K&R definition 2280 // match the types in the prototype declaration, even when the 2281 // promoted types of the parameters from the K&R definition differ 2282 // from the types in the prototype. GCC then keeps the types from 2283 // the prototype. 2284 // 2285 // If a variadic prototype is followed by a non-variadic K&R definition, 2286 // the K&R definition becomes variadic. This is sort of an edge case, but 2287 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2288 // C99 6.9.1p8. 2289 if (!getLangOpts().CPlusPlus && 2290 Old->hasPrototype() && !New->hasPrototype() && 2291 New->getType()->getAs<FunctionProtoType>() && 2292 Old->getNumParams() == New->getNumParams()) { 2293 SmallVector<QualType, 16> ArgTypes; 2294 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2295 const FunctionProtoType *OldProto 2296 = Old->getType()->getAs<FunctionProtoType>(); 2297 const FunctionProtoType *NewProto 2298 = New->getType()->getAs<FunctionProtoType>(); 2299 2300 // Determine whether this is the GNU C extension. 2301 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2302 NewProto->getResultType()); 2303 bool LooseCompatible = !MergedReturn.isNull(); 2304 for (unsigned Idx = 0, End = Old->getNumParams(); 2305 LooseCompatible && Idx != End; ++Idx) { 2306 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2307 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2308 if (Context.typesAreCompatible(OldParm->getType(), 2309 NewProto->getArgType(Idx))) { 2310 ArgTypes.push_back(NewParm->getType()); 2311 } else if (Context.typesAreCompatible(OldParm->getType(), 2312 NewParm->getType(), 2313 /*CompareUnqualified=*/true)) { 2314 GNUCompatibleParamWarning Warn 2315 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2316 Warnings.push_back(Warn); 2317 ArgTypes.push_back(NewParm->getType()); 2318 } else 2319 LooseCompatible = false; 2320 } 2321 2322 if (LooseCompatible) { 2323 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2324 Diag(Warnings[Warn].NewParm->getLocation(), 2325 diag::ext_param_promoted_not_compatible_with_prototype) 2326 << Warnings[Warn].PromotedType 2327 << Warnings[Warn].OldParm->getType(); 2328 if (Warnings[Warn].OldParm->getLocation().isValid()) 2329 Diag(Warnings[Warn].OldParm->getLocation(), 2330 diag::note_previous_declaration); 2331 } 2332 2333 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 2334 ArgTypes.size(), 2335 OldProto->getExtProtoInfo())); 2336 return MergeCompatibleFunctionDecls(New, Old, S); 2337 } 2338 2339 // Fall through to diagnose conflicting types. 2340 } 2341 2342 // A function that has already been declared has been redeclared or defined 2343 // with a different type- show appropriate diagnostic 2344 if (unsigned BuiltinID = Old->getBuiltinID()) { 2345 // The user has declared a builtin function with an incompatible 2346 // signature. 2347 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2348 // The function the user is redeclaring is a library-defined 2349 // function like 'malloc' or 'printf'. Warn about the 2350 // redeclaration, then pretend that we don't know about this 2351 // library built-in. 2352 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2353 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2354 << Old << Old->getType(); 2355 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2356 Old->setInvalidDecl(); 2357 return false; 2358 } 2359 2360 PrevDiag = diag::note_previous_builtin_declaration; 2361 } 2362 2363 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2364 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2365 return true; 2366} 2367 2368/// \brief Completes the merge of two function declarations that are 2369/// known to be compatible. 2370/// 2371/// This routine handles the merging of attributes and other 2372/// properties of function declarations form the old declaration to 2373/// the new declaration, once we know that New is in fact a 2374/// redeclaration of Old. 2375/// 2376/// \returns false 2377bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2378 Scope *S) { 2379 // Merge the attributes 2380 mergeDeclAttributes(New, Old); 2381 2382 // Merge the storage class. 2383 if (Old->getStorageClass() != SC_Extern && 2384 Old->getStorageClass() != SC_None) 2385 New->setStorageClass(Old->getStorageClass()); 2386 2387 // Merge "pure" flag. 2388 if (Old->isPure()) 2389 New->setPure(); 2390 2391 // Merge attributes from the parameters. These can mismatch with K&R 2392 // declarations. 2393 if (New->getNumParams() == Old->getNumParams()) 2394 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2395 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2396 Context); 2397 2398 if (getLangOpts().CPlusPlus) 2399 return MergeCXXFunctionDecl(New, Old, S); 2400 2401 return false; 2402} 2403 2404 2405void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2406 ObjCMethodDecl *oldMethod) { 2407 2408 // Merge the attributes, including deprecated/unavailable 2409 mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true); 2410 2411 // Merge attributes from the parameters. 2412 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2413 oe = oldMethod->param_end(); 2414 for (ObjCMethodDecl::param_iterator 2415 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2416 ni != ne && oi != oe; ++ni, ++oi) 2417 mergeParamDeclAttributes(*ni, *oi, Context); 2418 2419 CheckObjCMethodOverride(newMethod, oldMethod, true); 2420} 2421 2422/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2423/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2424/// emitting diagnostics as appropriate. 2425/// 2426/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2427/// to here in AddInitializerToDecl. We can't check them before the initializer 2428/// is attached. 2429void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2430 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2431 return; 2432 2433 QualType MergedT; 2434 if (getLangOpts().CPlusPlus) { 2435 AutoType *AT = New->getType()->getContainedAutoType(); 2436 if (AT && !AT->isDeduced()) { 2437 // We don't know what the new type is until the initializer is attached. 2438 return; 2439 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2440 // These could still be something that needs exception specs checked. 2441 return MergeVarDeclExceptionSpecs(New, Old); 2442 } 2443 // C++ [basic.link]p10: 2444 // [...] the types specified by all declarations referring to a given 2445 // object or function shall be identical, except that declarations for an 2446 // array object can specify array types that differ by the presence or 2447 // absence of a major array bound (8.3.4). 2448 else if (Old->getType()->isIncompleteArrayType() && 2449 New->getType()->isArrayType()) { 2450 CanQual<ArrayType> OldArray 2451 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2452 CanQual<ArrayType> NewArray 2453 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2454 if (OldArray->getElementType() == NewArray->getElementType()) 2455 MergedT = New->getType(); 2456 } else if (Old->getType()->isArrayType() && 2457 New->getType()->isIncompleteArrayType()) { 2458 CanQual<ArrayType> OldArray 2459 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2460 CanQual<ArrayType> NewArray 2461 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2462 if (OldArray->getElementType() == NewArray->getElementType()) 2463 MergedT = Old->getType(); 2464 } else if (New->getType()->isObjCObjectPointerType() 2465 && Old->getType()->isObjCObjectPointerType()) { 2466 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2467 Old->getType()); 2468 } 2469 } else { 2470 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2471 } 2472 if (MergedT.isNull()) { 2473 Diag(New->getLocation(), diag::err_redefinition_different_type) 2474 << New->getDeclName() << New->getType() << Old->getType(); 2475 Diag(Old->getLocation(), diag::note_previous_definition); 2476 return New->setInvalidDecl(); 2477 } 2478 New->setType(MergedT); 2479} 2480 2481/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2482/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2483/// situation, merging decls or emitting diagnostics as appropriate. 2484/// 2485/// Tentative definition rules (C99 6.9.2p2) are checked by 2486/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2487/// definitions here, since the initializer hasn't been attached. 2488/// 2489void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2490 // If the new decl is already invalid, don't do any other checking. 2491 if (New->isInvalidDecl()) 2492 return; 2493 2494 // Verify the old decl was also a variable. 2495 VarDecl *Old = 0; 2496 if (!Previous.isSingleResult() || 2497 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2498 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2499 << New->getDeclName(); 2500 Diag(Previous.getRepresentativeDecl()->getLocation(), 2501 diag::note_previous_definition); 2502 return New->setInvalidDecl(); 2503 } 2504 2505 // C++ [class.mem]p1: 2506 // A member shall not be declared twice in the member-specification [...] 2507 // 2508 // Here, we need only consider static data members. 2509 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2510 Diag(New->getLocation(), diag::err_duplicate_member) 2511 << New->getIdentifier(); 2512 Diag(Old->getLocation(), diag::note_previous_declaration); 2513 New->setInvalidDecl(); 2514 } 2515 2516 mergeDeclAttributes(New, Old); 2517 // Warn if an already-declared variable is made a weak_import in a subsequent 2518 // declaration 2519 if (New->getAttr<WeakImportAttr>() && 2520 Old->getStorageClass() == SC_None && 2521 !Old->getAttr<WeakImportAttr>()) { 2522 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2523 Diag(Old->getLocation(), diag::note_previous_definition); 2524 // Remove weak_import attribute on new declaration. 2525 New->dropAttr<WeakImportAttr>(); 2526 } 2527 2528 // Merge the types. 2529 MergeVarDeclTypes(New, Old); 2530 if (New->isInvalidDecl()) 2531 return; 2532 2533 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2534 if (New->getStorageClass() == SC_Static && 2535 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2536 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2537 Diag(Old->getLocation(), diag::note_previous_definition); 2538 return New->setInvalidDecl(); 2539 } 2540 // C99 6.2.2p4: 2541 // For an identifier declared with the storage-class specifier 2542 // extern in a scope in which a prior declaration of that 2543 // identifier is visible,23) if the prior declaration specifies 2544 // internal or external linkage, the linkage of the identifier at 2545 // the later declaration is the same as the linkage specified at 2546 // the prior declaration. If no prior declaration is visible, or 2547 // if the prior declaration specifies no linkage, then the 2548 // identifier has external linkage. 2549 if (New->hasExternalStorage() && Old->hasLinkage()) 2550 /* Okay */; 2551 else if (New->getStorageClass() != SC_Static && 2552 Old->getStorageClass() == SC_Static) { 2553 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2554 Diag(Old->getLocation(), diag::note_previous_definition); 2555 return New->setInvalidDecl(); 2556 } 2557 2558 // Check if extern is followed by non-extern and vice-versa. 2559 if (New->hasExternalStorage() && 2560 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2561 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2562 Diag(Old->getLocation(), diag::note_previous_definition); 2563 return New->setInvalidDecl(); 2564 } 2565 if (Old->hasExternalStorage() && 2566 !New->hasLinkage() && New->isLocalVarDecl()) { 2567 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2568 Diag(Old->getLocation(), diag::note_previous_definition); 2569 return New->setInvalidDecl(); 2570 } 2571 2572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2573 2574 // FIXME: The test for external storage here seems wrong? We still 2575 // need to check for mismatches. 2576 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2577 // Don't complain about out-of-line definitions of static members. 2578 !(Old->getLexicalDeclContext()->isRecord() && 2579 !New->getLexicalDeclContext()->isRecord())) { 2580 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2581 Diag(Old->getLocation(), diag::note_previous_definition); 2582 return New->setInvalidDecl(); 2583 } 2584 2585 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2586 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2587 Diag(Old->getLocation(), diag::note_previous_definition); 2588 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2589 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2590 Diag(Old->getLocation(), diag::note_previous_definition); 2591 } 2592 2593 // C++ doesn't have tentative definitions, so go right ahead and check here. 2594 const VarDecl *Def; 2595 if (getLangOpts().CPlusPlus && 2596 New->isThisDeclarationADefinition() == VarDecl::Definition && 2597 (Def = Old->getDefinition())) { 2598 Diag(New->getLocation(), diag::err_redefinition) 2599 << New->getDeclName(); 2600 Diag(Def->getLocation(), diag::note_previous_definition); 2601 New->setInvalidDecl(); 2602 return; 2603 } 2604 // c99 6.2.2 P4. 2605 // For an identifier declared with the storage-class specifier extern in a 2606 // scope in which a prior declaration of that identifier is visible, if 2607 // the prior declaration specifies internal or external linkage, the linkage 2608 // of the identifier at the later declaration is the same as the linkage 2609 // specified at the prior declaration. 2610 // FIXME. revisit this code. 2611 if (New->hasExternalStorage() && 2612 Old->getLinkage() == InternalLinkage && 2613 New->getDeclContext() == Old->getDeclContext()) 2614 New->setStorageClass(Old->getStorageClass()); 2615 2616 // Keep a chain of previous declarations. 2617 New->setPreviousDeclaration(Old); 2618 2619 // Inherit access appropriately. 2620 New->setAccess(Old->getAccess()); 2621} 2622 2623/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2624/// no declarator (e.g. "struct foo;") is parsed. 2625Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2626 DeclSpec &DS) { 2627 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 2628} 2629 2630/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2631/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2632/// parameters to cope with template friend declarations. 2633Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2634 DeclSpec &DS, 2635 MultiTemplateParamsArg TemplateParams) { 2636 Decl *TagD = 0; 2637 TagDecl *Tag = 0; 2638 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2639 DS.getTypeSpecType() == DeclSpec::TST_struct || 2640 DS.getTypeSpecType() == DeclSpec::TST_interface || 2641 DS.getTypeSpecType() == DeclSpec::TST_union || 2642 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2643 TagD = DS.getRepAsDecl(); 2644 2645 if (!TagD) // We probably had an error 2646 return 0; 2647 2648 // Note that the above type specs guarantee that the 2649 // type rep is a Decl, whereas in many of the others 2650 // it's a Type. 2651 if (isa<TagDecl>(TagD)) 2652 Tag = cast<TagDecl>(TagD); 2653 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 2654 Tag = CTD->getTemplatedDecl(); 2655 } 2656 2657 if (Tag) { 2658 getASTContext().addUnnamedTag(Tag); 2659 Tag->setFreeStanding(); 2660 if (Tag->isInvalidDecl()) 2661 return Tag; 2662 } 2663 2664 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2665 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2666 // or incomplete types shall not be restrict-qualified." 2667 if (TypeQuals & DeclSpec::TQ_restrict) 2668 Diag(DS.getRestrictSpecLoc(), 2669 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2670 << DS.getSourceRange(); 2671 } 2672 2673 if (DS.isConstexprSpecified()) { 2674 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2675 // and definitions of functions and variables. 2676 if (Tag) 2677 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2678 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2679 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2680 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 2681 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 2682 else 2683 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2684 // Don't emit warnings after this error. 2685 return TagD; 2686 } 2687 2688 if (DS.isFriendSpecified()) { 2689 // If we're dealing with a decl but not a TagDecl, assume that 2690 // whatever routines created it handled the friendship aspect. 2691 if (TagD && !Tag) 2692 return 0; 2693 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2694 } 2695 2696 // Track whether we warned about the fact that there aren't any 2697 // declarators. 2698 bool emittedWarning = false; 2699 2700 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2701 if (!Record->getDeclName() && Record->isCompleteDefinition() && 2702 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2703 if (getLangOpts().CPlusPlus || 2704 Record->getDeclContext()->isRecord()) 2705 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2706 2707 Diag(DS.getLocStart(), diag::ext_no_declarators) 2708 << DS.getSourceRange(); 2709 emittedWarning = true; 2710 } 2711 } 2712 2713 // Check for Microsoft C extension: anonymous struct. 2714 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 2715 CurContext->isRecord() && 2716 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2717 // Handle 2 kinds of anonymous struct: 2718 // struct STRUCT; 2719 // and 2720 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2721 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2722 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 2723 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2724 DS.getRepAsType().get()->isStructureType())) { 2725 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 2726 << DS.getSourceRange(); 2727 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2728 } 2729 } 2730 2731 if (getLangOpts().CPlusPlus && 2732 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2733 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2734 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2735 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2736 Diag(Enum->getLocation(), diag::ext_no_declarators) 2737 << DS.getSourceRange(); 2738 emittedWarning = true; 2739 } 2740 2741 // Skip all the checks below if we have a type error. 2742 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2743 2744 if (!DS.isMissingDeclaratorOk()) { 2745 // Warn about typedefs of enums without names, since this is an 2746 // extension in both Microsoft and GNU. 2747 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2748 Tag && isa<EnumDecl>(Tag)) { 2749 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 2750 << DS.getSourceRange(); 2751 return Tag; 2752 } 2753 2754 Diag(DS.getLocStart(), diag::ext_no_declarators) 2755 << DS.getSourceRange(); 2756 emittedWarning = true; 2757 } 2758 2759 // We're going to complain about a bunch of spurious specifiers; 2760 // only do this if we're declaring a tag, because otherwise we 2761 // should be getting diag::ext_no_declarators. 2762 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2763 return TagD; 2764 2765 // Note that a linkage-specification sets a storage class, but 2766 // 'extern "C" struct foo;' is actually valid and not theoretically 2767 // useless. 2768 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2769 if (!DS.isExternInLinkageSpec()) 2770 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2771 << DeclSpec::getSpecifierName(scs); 2772 2773 if (DS.isThreadSpecified()) 2774 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2775 if (DS.getTypeQualifiers()) { 2776 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2777 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2778 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2779 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2780 // Restrict is covered above. 2781 } 2782 if (DS.isInlineSpecified()) 2783 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2784 if (DS.isVirtualSpecified()) 2785 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2786 if (DS.isExplicitSpecified()) 2787 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2788 2789 if (DS.isModulePrivateSpecified() && 2790 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 2791 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 2792 << Tag->getTagKind() 2793 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 2794 2795 // Warn about ignored type attributes, for example: 2796 // __attribute__((aligned)) struct A; 2797 // Attributes should be placed after tag to apply to type declaration. 2798 if (!DS.getAttributes().empty()) { 2799 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 2800 if (TypeSpecType == DeclSpec::TST_class || 2801 TypeSpecType == DeclSpec::TST_struct || 2802 TypeSpecType == DeclSpec::TST_interface || 2803 TypeSpecType == DeclSpec::TST_union || 2804 TypeSpecType == DeclSpec::TST_enum) { 2805 AttributeList* attrs = DS.getAttributes().getList(); 2806 while (attrs) { 2807 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 2808 << attrs->getName() 2809 << (TypeSpecType == DeclSpec::TST_class ? 0 : 2810 TypeSpecType == DeclSpec::TST_struct ? 1 : 2811 TypeSpecType == DeclSpec::TST_union ? 2 : 2812 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 2813 attrs = attrs->getNext(); 2814 } 2815 } 2816 } 2817 2818 ActOnDocumentableDecl(TagD); 2819 2820 return TagD; 2821} 2822 2823/// We are trying to inject an anonymous member into the given scope; 2824/// check if there's an existing declaration that can't be overloaded. 2825/// 2826/// \return true if this is a forbidden redeclaration 2827static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2828 Scope *S, 2829 DeclContext *Owner, 2830 DeclarationName Name, 2831 SourceLocation NameLoc, 2832 unsigned diagnostic) { 2833 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2834 Sema::ForRedeclaration); 2835 if (!SemaRef.LookupName(R, S)) return false; 2836 2837 if (R.getAsSingle<TagDecl>()) 2838 return false; 2839 2840 // Pick a representative declaration. 2841 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2842 assert(PrevDecl && "Expected a non-null Decl"); 2843 2844 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2845 return false; 2846 2847 SemaRef.Diag(NameLoc, diagnostic) << Name; 2848 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2849 2850 return true; 2851} 2852 2853/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2854/// anonymous struct or union AnonRecord into the owning context Owner 2855/// and scope S. This routine will be invoked just after we realize 2856/// that an unnamed union or struct is actually an anonymous union or 2857/// struct, e.g., 2858/// 2859/// @code 2860/// union { 2861/// int i; 2862/// float f; 2863/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2864/// // f into the surrounding scope.x 2865/// @endcode 2866/// 2867/// This routine is recursive, injecting the names of nested anonymous 2868/// structs/unions into the owning context and scope as well. 2869static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2870 DeclContext *Owner, 2871 RecordDecl *AnonRecord, 2872 AccessSpecifier AS, 2873 SmallVector<NamedDecl*, 2> &Chaining, 2874 bool MSAnonStruct) { 2875 unsigned diagKind 2876 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2877 : diag::err_anonymous_struct_member_redecl; 2878 2879 bool Invalid = false; 2880 2881 // Look every FieldDecl and IndirectFieldDecl with a name. 2882 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2883 DEnd = AnonRecord->decls_end(); 2884 D != DEnd; ++D) { 2885 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2886 cast<NamedDecl>(*D)->getDeclName()) { 2887 ValueDecl *VD = cast<ValueDecl>(*D); 2888 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2889 VD->getLocation(), diagKind)) { 2890 // C++ [class.union]p2: 2891 // The names of the members of an anonymous union shall be 2892 // distinct from the names of any other entity in the 2893 // scope in which the anonymous union is declared. 2894 Invalid = true; 2895 } else { 2896 // C++ [class.union]p2: 2897 // For the purpose of name lookup, after the anonymous union 2898 // definition, the members of the anonymous union are 2899 // considered to have been defined in the scope in which the 2900 // anonymous union is declared. 2901 unsigned OldChainingSize = Chaining.size(); 2902 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2903 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2904 PE = IF->chain_end(); PI != PE; ++PI) 2905 Chaining.push_back(*PI); 2906 else 2907 Chaining.push_back(VD); 2908 2909 assert(Chaining.size() >= 2); 2910 NamedDecl **NamedChain = 2911 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2912 for (unsigned i = 0; i < Chaining.size(); i++) 2913 NamedChain[i] = Chaining[i]; 2914 2915 IndirectFieldDecl* IndirectField = 2916 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2917 VD->getIdentifier(), VD->getType(), 2918 NamedChain, Chaining.size()); 2919 2920 IndirectField->setAccess(AS); 2921 IndirectField->setImplicit(); 2922 SemaRef.PushOnScopeChains(IndirectField, S); 2923 2924 // That includes picking up the appropriate access specifier. 2925 if (AS != AS_none) IndirectField->setAccess(AS); 2926 2927 Chaining.resize(OldChainingSize); 2928 } 2929 } 2930 } 2931 2932 return Invalid; 2933} 2934 2935/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2936/// a VarDecl::StorageClass. Any error reporting is up to the caller: 2937/// illegal input values are mapped to SC_None. 2938static StorageClass 2939StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2940 switch (StorageClassSpec) { 2941 case DeclSpec::SCS_unspecified: return SC_None; 2942 case DeclSpec::SCS_extern: return SC_Extern; 2943 case DeclSpec::SCS_static: return SC_Static; 2944 case DeclSpec::SCS_auto: return SC_Auto; 2945 case DeclSpec::SCS_register: return SC_Register; 2946 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2947 // Illegal SCSs map to None: error reporting is up to the caller. 2948 case DeclSpec::SCS_mutable: // Fall through. 2949 case DeclSpec::SCS_typedef: return SC_None; 2950 } 2951 llvm_unreachable("unknown storage class specifier"); 2952} 2953 2954/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2955/// a StorageClass. Any error reporting is up to the caller: 2956/// illegal input values are mapped to SC_None. 2957static StorageClass 2958StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2959 switch (StorageClassSpec) { 2960 case DeclSpec::SCS_unspecified: return SC_None; 2961 case DeclSpec::SCS_extern: return SC_Extern; 2962 case DeclSpec::SCS_static: return SC_Static; 2963 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2964 // Illegal SCSs map to None: error reporting is up to the caller. 2965 case DeclSpec::SCS_auto: // Fall through. 2966 case DeclSpec::SCS_mutable: // Fall through. 2967 case DeclSpec::SCS_register: // Fall through. 2968 case DeclSpec::SCS_typedef: return SC_None; 2969 } 2970 llvm_unreachable("unknown storage class specifier"); 2971} 2972 2973/// BuildAnonymousStructOrUnion - Handle the declaration of an 2974/// anonymous structure or union. Anonymous unions are a C++ feature 2975/// (C++ [class.union]) and a C11 feature; anonymous structures 2976/// are a C11 feature and GNU C++ extension. 2977Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2978 AccessSpecifier AS, 2979 RecordDecl *Record) { 2980 DeclContext *Owner = Record->getDeclContext(); 2981 2982 // Diagnose whether this anonymous struct/union is an extension. 2983 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 2984 Diag(Record->getLocation(), diag::ext_anonymous_union); 2985 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 2986 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 2987 else if (!Record->isUnion() && !getLangOpts().C11) 2988 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 2989 2990 // C and C++ require different kinds of checks for anonymous 2991 // structs/unions. 2992 bool Invalid = false; 2993 if (getLangOpts().CPlusPlus) { 2994 const char* PrevSpec = 0; 2995 unsigned DiagID; 2996 if (Record->isUnion()) { 2997 // C++ [class.union]p6: 2998 // Anonymous unions declared in a named namespace or in the 2999 // global namespace shall be declared static. 3000 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3001 (isa<TranslationUnitDecl>(Owner) || 3002 (isa<NamespaceDecl>(Owner) && 3003 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3004 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3005 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3006 3007 // Recover by adding 'static'. 3008 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3009 PrevSpec, DiagID); 3010 } 3011 // C++ [class.union]p6: 3012 // A storage class is not allowed in a declaration of an 3013 // anonymous union in a class scope. 3014 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3015 isa<RecordDecl>(Owner)) { 3016 Diag(DS.getStorageClassSpecLoc(), 3017 diag::err_anonymous_union_with_storage_spec) 3018 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3019 3020 // Recover by removing the storage specifier. 3021 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3022 SourceLocation(), 3023 PrevSpec, DiagID); 3024 } 3025 } 3026 3027 // Ignore const/volatile/restrict qualifiers. 3028 if (DS.getTypeQualifiers()) { 3029 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3030 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3031 << Record->isUnion() << 0 3032 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3033 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3034 Diag(DS.getVolatileSpecLoc(), 3035 diag::ext_anonymous_struct_union_qualified) 3036 << Record->isUnion() << 1 3037 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3038 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3039 Diag(DS.getRestrictSpecLoc(), 3040 diag::ext_anonymous_struct_union_qualified) 3041 << Record->isUnion() << 2 3042 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3043 3044 DS.ClearTypeQualifiers(); 3045 } 3046 3047 // C++ [class.union]p2: 3048 // The member-specification of an anonymous union shall only 3049 // define non-static data members. [Note: nested types and 3050 // functions cannot be declared within an anonymous union. ] 3051 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3052 MemEnd = Record->decls_end(); 3053 Mem != MemEnd; ++Mem) { 3054 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3055 // C++ [class.union]p3: 3056 // An anonymous union shall not have private or protected 3057 // members (clause 11). 3058 assert(FD->getAccess() != AS_none); 3059 if (FD->getAccess() != AS_public) { 3060 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3061 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3062 Invalid = true; 3063 } 3064 3065 // C++ [class.union]p1 3066 // An object of a class with a non-trivial constructor, a non-trivial 3067 // copy constructor, a non-trivial destructor, or a non-trivial copy 3068 // assignment operator cannot be a member of a union, nor can an 3069 // array of such objects. 3070 if (CheckNontrivialField(FD)) 3071 Invalid = true; 3072 } else if ((*Mem)->isImplicit()) { 3073 // Any implicit members are fine. 3074 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3075 // This is a type that showed up in an 3076 // elaborated-type-specifier inside the anonymous struct or 3077 // union, but which actually declares a type outside of the 3078 // anonymous struct or union. It's okay. 3079 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3080 if (!MemRecord->isAnonymousStructOrUnion() && 3081 MemRecord->getDeclName()) { 3082 // Visual C++ allows type definition in anonymous struct or union. 3083 if (getLangOpts().MicrosoftExt) 3084 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3085 << (int)Record->isUnion(); 3086 else { 3087 // This is a nested type declaration. 3088 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3089 << (int)Record->isUnion(); 3090 Invalid = true; 3091 } 3092 } 3093 } else if (isa<AccessSpecDecl>(*Mem)) { 3094 // Any access specifier is fine. 3095 } else { 3096 // We have something that isn't a non-static data 3097 // member. Complain about it. 3098 unsigned DK = diag::err_anonymous_record_bad_member; 3099 if (isa<TypeDecl>(*Mem)) 3100 DK = diag::err_anonymous_record_with_type; 3101 else if (isa<FunctionDecl>(*Mem)) 3102 DK = diag::err_anonymous_record_with_function; 3103 else if (isa<VarDecl>(*Mem)) 3104 DK = diag::err_anonymous_record_with_static; 3105 3106 // Visual C++ allows type definition in anonymous struct or union. 3107 if (getLangOpts().MicrosoftExt && 3108 DK == diag::err_anonymous_record_with_type) 3109 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3110 << (int)Record->isUnion(); 3111 else { 3112 Diag((*Mem)->getLocation(), DK) 3113 << (int)Record->isUnion(); 3114 Invalid = true; 3115 } 3116 } 3117 } 3118 } 3119 3120 if (!Record->isUnion() && !Owner->isRecord()) { 3121 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3122 << (int)getLangOpts().CPlusPlus; 3123 Invalid = true; 3124 } 3125 3126 // Mock up a declarator. 3127 Declarator Dc(DS, Declarator::MemberContext); 3128 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3129 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3130 3131 // Create a declaration for this anonymous struct/union. 3132 NamedDecl *Anon = 0; 3133 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3134 Anon = FieldDecl::Create(Context, OwningClass, 3135 DS.getLocStart(), 3136 Record->getLocation(), 3137 /*IdentifierInfo=*/0, 3138 Context.getTypeDeclType(Record), 3139 TInfo, 3140 /*BitWidth=*/0, /*Mutable=*/false, 3141 /*InitStyle=*/ICIS_NoInit); 3142 Anon->setAccess(AS); 3143 if (getLangOpts().CPlusPlus) 3144 FieldCollector->Add(cast<FieldDecl>(Anon)); 3145 } else { 3146 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3147 assert(SCSpec != DeclSpec::SCS_typedef && 3148 "Parser allowed 'typedef' as storage class VarDecl."); 3149 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3150 if (SCSpec == DeclSpec::SCS_mutable) { 3151 // mutable can only appear on non-static class members, so it's always 3152 // an error here 3153 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3154 Invalid = true; 3155 SC = SC_None; 3156 } 3157 SCSpec = DS.getStorageClassSpecAsWritten(); 3158 VarDecl::StorageClass SCAsWritten 3159 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3160 3161 Anon = VarDecl::Create(Context, Owner, 3162 DS.getLocStart(), 3163 Record->getLocation(), /*IdentifierInfo=*/0, 3164 Context.getTypeDeclType(Record), 3165 TInfo, SC, SCAsWritten); 3166 3167 // Default-initialize the implicit variable. This initialization will be 3168 // trivial in almost all cases, except if a union member has an in-class 3169 // initializer: 3170 // union { int n = 0; }; 3171 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3172 } 3173 Anon->setImplicit(); 3174 3175 // Add the anonymous struct/union object to the current 3176 // context. We'll be referencing this object when we refer to one of 3177 // its members. 3178 Owner->addDecl(Anon); 3179 3180 // Inject the members of the anonymous struct/union into the owning 3181 // context and into the identifier resolver chain for name lookup 3182 // purposes. 3183 SmallVector<NamedDecl*, 2> Chain; 3184 Chain.push_back(Anon); 3185 3186 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3187 Chain, false)) 3188 Invalid = true; 3189 3190 // Mark this as an anonymous struct/union type. Note that we do not 3191 // do this until after we have already checked and injected the 3192 // members of this anonymous struct/union type, because otherwise 3193 // the members could be injected twice: once by DeclContext when it 3194 // builds its lookup table, and once by 3195 // InjectAnonymousStructOrUnionMembers. 3196 Record->setAnonymousStructOrUnion(true); 3197 3198 if (Invalid) 3199 Anon->setInvalidDecl(); 3200 3201 return Anon; 3202} 3203 3204/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3205/// Microsoft C anonymous structure. 3206/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3207/// Example: 3208/// 3209/// struct A { int a; }; 3210/// struct B { struct A; int b; }; 3211/// 3212/// void foo() { 3213/// B var; 3214/// var.a = 3; 3215/// } 3216/// 3217Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3218 RecordDecl *Record) { 3219 3220 // If there is no Record, get the record via the typedef. 3221 if (!Record) 3222 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3223 3224 // Mock up a declarator. 3225 Declarator Dc(DS, Declarator::TypeNameContext); 3226 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3227 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3228 3229 // Create a declaration for this anonymous struct. 3230 NamedDecl* Anon = FieldDecl::Create(Context, 3231 cast<RecordDecl>(CurContext), 3232 DS.getLocStart(), 3233 DS.getLocStart(), 3234 /*IdentifierInfo=*/0, 3235 Context.getTypeDeclType(Record), 3236 TInfo, 3237 /*BitWidth=*/0, /*Mutable=*/false, 3238 /*InitStyle=*/ICIS_NoInit); 3239 Anon->setImplicit(); 3240 3241 // Add the anonymous struct object to the current context. 3242 CurContext->addDecl(Anon); 3243 3244 // Inject the members of the anonymous struct into the current 3245 // context and into the identifier resolver chain for name lookup 3246 // purposes. 3247 SmallVector<NamedDecl*, 2> Chain; 3248 Chain.push_back(Anon); 3249 3250 RecordDecl *RecordDef = Record->getDefinition(); 3251 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3252 RecordDef, AS_none, 3253 Chain, true)) 3254 Anon->setInvalidDecl(); 3255 3256 return Anon; 3257} 3258 3259/// GetNameForDeclarator - Determine the full declaration name for the 3260/// given Declarator. 3261DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3262 return GetNameFromUnqualifiedId(D.getName()); 3263} 3264 3265/// \brief Retrieves the declaration name from a parsed unqualified-id. 3266DeclarationNameInfo 3267Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3268 DeclarationNameInfo NameInfo; 3269 NameInfo.setLoc(Name.StartLocation); 3270 3271 switch (Name.getKind()) { 3272 3273 case UnqualifiedId::IK_ImplicitSelfParam: 3274 case UnqualifiedId::IK_Identifier: 3275 NameInfo.setName(Name.Identifier); 3276 NameInfo.setLoc(Name.StartLocation); 3277 return NameInfo; 3278 3279 case UnqualifiedId::IK_OperatorFunctionId: 3280 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3281 Name.OperatorFunctionId.Operator)); 3282 NameInfo.setLoc(Name.StartLocation); 3283 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3284 = Name.OperatorFunctionId.SymbolLocations[0]; 3285 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3286 = Name.EndLocation.getRawEncoding(); 3287 return NameInfo; 3288 3289 case UnqualifiedId::IK_LiteralOperatorId: 3290 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3291 Name.Identifier)); 3292 NameInfo.setLoc(Name.StartLocation); 3293 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3294 return NameInfo; 3295 3296 case UnqualifiedId::IK_ConversionFunctionId: { 3297 TypeSourceInfo *TInfo; 3298 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3299 if (Ty.isNull()) 3300 return DeclarationNameInfo(); 3301 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3302 Context.getCanonicalType(Ty))); 3303 NameInfo.setLoc(Name.StartLocation); 3304 NameInfo.setNamedTypeInfo(TInfo); 3305 return NameInfo; 3306 } 3307 3308 case UnqualifiedId::IK_ConstructorName: { 3309 TypeSourceInfo *TInfo; 3310 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3311 if (Ty.isNull()) 3312 return DeclarationNameInfo(); 3313 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3314 Context.getCanonicalType(Ty))); 3315 NameInfo.setLoc(Name.StartLocation); 3316 NameInfo.setNamedTypeInfo(TInfo); 3317 return NameInfo; 3318 } 3319 3320 case UnqualifiedId::IK_ConstructorTemplateId: { 3321 // In well-formed code, we can only have a constructor 3322 // template-id that refers to the current context, so go there 3323 // to find the actual type being constructed. 3324 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3325 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3326 return DeclarationNameInfo(); 3327 3328 // Determine the type of the class being constructed. 3329 QualType CurClassType = Context.getTypeDeclType(CurClass); 3330 3331 // FIXME: Check two things: that the template-id names the same type as 3332 // CurClassType, and that the template-id does not occur when the name 3333 // was qualified. 3334 3335 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3336 Context.getCanonicalType(CurClassType))); 3337 NameInfo.setLoc(Name.StartLocation); 3338 // FIXME: should we retrieve TypeSourceInfo? 3339 NameInfo.setNamedTypeInfo(0); 3340 return NameInfo; 3341 } 3342 3343 case UnqualifiedId::IK_DestructorName: { 3344 TypeSourceInfo *TInfo; 3345 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3346 if (Ty.isNull()) 3347 return DeclarationNameInfo(); 3348 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3349 Context.getCanonicalType(Ty))); 3350 NameInfo.setLoc(Name.StartLocation); 3351 NameInfo.setNamedTypeInfo(TInfo); 3352 return NameInfo; 3353 } 3354 3355 case UnqualifiedId::IK_TemplateId: { 3356 TemplateName TName = Name.TemplateId->Template.get(); 3357 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3358 return Context.getNameForTemplate(TName, TNameLoc); 3359 } 3360 3361 } // switch (Name.getKind()) 3362 3363 llvm_unreachable("Unknown name kind"); 3364} 3365 3366static QualType getCoreType(QualType Ty) { 3367 do { 3368 if (Ty->isPointerType() || Ty->isReferenceType()) 3369 Ty = Ty->getPointeeType(); 3370 else if (Ty->isArrayType()) 3371 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3372 else 3373 return Ty.withoutLocalFastQualifiers(); 3374 } while (true); 3375} 3376 3377/// hasSimilarParameters - Determine whether the C++ functions Declaration 3378/// and Definition have "nearly" matching parameters. This heuristic is 3379/// used to improve diagnostics in the case where an out-of-line function 3380/// definition doesn't match any declaration within the class or namespace. 3381/// Also sets Params to the list of indices to the parameters that differ 3382/// between the declaration and the definition. If hasSimilarParameters 3383/// returns true and Params is empty, then all of the parameters match. 3384static bool hasSimilarParameters(ASTContext &Context, 3385 FunctionDecl *Declaration, 3386 FunctionDecl *Definition, 3387 llvm::SmallVectorImpl<unsigned> &Params) { 3388 Params.clear(); 3389 if (Declaration->param_size() != Definition->param_size()) 3390 return false; 3391 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3392 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3393 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3394 3395 // The parameter types are identical 3396 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3397 continue; 3398 3399 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3400 QualType DefParamBaseTy = getCoreType(DefParamTy); 3401 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3402 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3403 3404 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3405 (DeclTyName && DeclTyName == DefTyName)) 3406 Params.push_back(Idx); 3407 else // The two parameters aren't even close 3408 return false; 3409 } 3410 3411 return true; 3412} 3413 3414/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3415/// declarator needs to be rebuilt in the current instantiation. 3416/// Any bits of declarator which appear before the name are valid for 3417/// consideration here. That's specifically the type in the decl spec 3418/// and the base type in any member-pointer chunks. 3419static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3420 DeclarationName Name) { 3421 // The types we specifically need to rebuild are: 3422 // - typenames, typeofs, and decltypes 3423 // - types which will become injected class names 3424 // Of course, we also need to rebuild any type referencing such a 3425 // type. It's safest to just say "dependent", but we call out a 3426 // few cases here. 3427 3428 DeclSpec &DS = D.getMutableDeclSpec(); 3429 switch (DS.getTypeSpecType()) { 3430 case DeclSpec::TST_typename: 3431 case DeclSpec::TST_typeofType: 3432 case DeclSpec::TST_underlyingType: 3433 case DeclSpec::TST_atomic: { 3434 // Grab the type from the parser. 3435 TypeSourceInfo *TSI = 0; 3436 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3437 if (T.isNull() || !T->isDependentType()) break; 3438 3439 // Make sure there's a type source info. This isn't really much 3440 // of a waste; most dependent types should have type source info 3441 // attached already. 3442 if (!TSI) 3443 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3444 3445 // Rebuild the type in the current instantiation. 3446 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3447 if (!TSI) return true; 3448 3449 // Store the new type back in the decl spec. 3450 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3451 DS.UpdateTypeRep(LocType); 3452 break; 3453 } 3454 3455 case DeclSpec::TST_decltype: 3456 case DeclSpec::TST_typeofExpr: { 3457 Expr *E = DS.getRepAsExpr(); 3458 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3459 if (Result.isInvalid()) return true; 3460 DS.UpdateExprRep(Result.get()); 3461 break; 3462 } 3463 3464 default: 3465 // Nothing to do for these decl specs. 3466 break; 3467 } 3468 3469 // It doesn't matter what order we do this in. 3470 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3471 DeclaratorChunk &Chunk = D.getTypeObject(I); 3472 3473 // The only type information in the declarator which can come 3474 // before the declaration name is the base type of a member 3475 // pointer. 3476 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3477 continue; 3478 3479 // Rebuild the scope specifier in-place. 3480 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3481 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3482 return true; 3483 } 3484 3485 return false; 3486} 3487 3488Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3489 D.setFunctionDefinitionKind(FDK_Declaration); 3490 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3491 3492 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3493 Dcl && Dcl->getDeclContext()->isFileContext()) 3494 Dcl->setTopLevelDeclInObjCContainer(); 3495 3496 return Dcl; 3497} 3498 3499/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3500/// If T is the name of a class, then each of the following shall have a 3501/// name different from T: 3502/// - every static data member of class T; 3503/// - every member function of class T 3504/// - every member of class T that is itself a type; 3505/// \returns true if the declaration name violates these rules. 3506bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3507 DeclarationNameInfo NameInfo) { 3508 DeclarationName Name = NameInfo.getName(); 3509 3510 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3511 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3512 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3513 return true; 3514 } 3515 3516 return false; 3517} 3518 3519/// \brief Diagnose a declaration whose declarator-id has the given 3520/// nested-name-specifier. 3521/// 3522/// \param SS The nested-name-specifier of the declarator-id. 3523/// 3524/// \param DC The declaration context to which the nested-name-specifier 3525/// resolves. 3526/// 3527/// \param Name The name of the entity being declared. 3528/// 3529/// \param Loc The location of the name of the entity being declared. 3530/// 3531/// \returns true if we cannot safely recover from this error, false otherwise. 3532bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3533 DeclarationName Name, 3534 SourceLocation Loc) { 3535 DeclContext *Cur = CurContext; 3536 while (isa<LinkageSpecDecl>(Cur)) 3537 Cur = Cur->getParent(); 3538 3539 // C++ [dcl.meaning]p1: 3540 // A declarator-id shall not be qualified except for the definition 3541 // of a member function (9.3) or static data member (9.4) outside of 3542 // its class, the definition or explicit instantiation of a function 3543 // or variable member of a namespace outside of its namespace, or the 3544 // definition of an explicit specialization outside of its namespace, 3545 // or the declaration of a friend function that is a member of 3546 // another class or namespace (11.3). [...] 3547 3548 // The user provided a superfluous scope specifier that refers back to the 3549 // class or namespaces in which the entity is already declared. 3550 // 3551 // class X { 3552 // void X::f(); 3553 // }; 3554 if (Cur->Equals(DC)) { 3555 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3556 : diag::err_member_extra_qualification) 3557 << Name << FixItHint::CreateRemoval(SS.getRange()); 3558 SS.clear(); 3559 return false; 3560 } 3561 3562 // Check whether the qualifying scope encloses the scope of the original 3563 // declaration. 3564 if (!Cur->Encloses(DC)) { 3565 if (Cur->isRecord()) 3566 Diag(Loc, diag::err_member_qualification) 3567 << Name << SS.getRange(); 3568 else if (isa<TranslationUnitDecl>(DC)) 3569 Diag(Loc, diag::err_invalid_declarator_global_scope) 3570 << Name << SS.getRange(); 3571 else if (isa<FunctionDecl>(Cur)) 3572 Diag(Loc, diag::err_invalid_declarator_in_function) 3573 << Name << SS.getRange(); 3574 else 3575 Diag(Loc, diag::err_invalid_declarator_scope) 3576 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3577 3578 return true; 3579 } 3580 3581 if (Cur->isRecord()) { 3582 // Cannot qualify members within a class. 3583 Diag(Loc, diag::err_member_qualification) 3584 << Name << SS.getRange(); 3585 SS.clear(); 3586 3587 // C++ constructors and destructors with incorrect scopes can break 3588 // our AST invariants by having the wrong underlying types. If 3589 // that's the case, then drop this declaration entirely. 3590 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3591 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3592 !Context.hasSameType(Name.getCXXNameType(), 3593 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3594 return true; 3595 3596 return false; 3597 } 3598 3599 // C++11 [dcl.meaning]p1: 3600 // [...] "The nested-name-specifier of the qualified declarator-id shall 3601 // not begin with a decltype-specifer" 3602 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3603 while (SpecLoc.getPrefix()) 3604 SpecLoc = SpecLoc.getPrefix(); 3605 if (dyn_cast_or_null<DecltypeType>( 3606 SpecLoc.getNestedNameSpecifier()->getAsType())) 3607 Diag(Loc, diag::err_decltype_in_declarator) 3608 << SpecLoc.getTypeLoc().getSourceRange(); 3609 3610 return false; 3611} 3612 3613Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3614 MultiTemplateParamsArg TemplateParamLists) { 3615 // TODO: consider using NameInfo for diagnostic. 3616 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3617 DeclarationName Name = NameInfo.getName(); 3618 3619 // All of these full declarators require an identifier. If it doesn't have 3620 // one, the ParsedFreeStandingDeclSpec action should be used. 3621 if (!Name) { 3622 if (!D.isInvalidType()) // Reject this if we think it is valid. 3623 Diag(D.getDeclSpec().getLocStart(), 3624 diag::err_declarator_need_ident) 3625 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3626 return 0; 3627 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3628 return 0; 3629 3630 // The scope passed in may not be a decl scope. Zip up the scope tree until 3631 // we find one that is. 3632 while ((S->getFlags() & Scope::DeclScope) == 0 || 3633 (S->getFlags() & Scope::TemplateParamScope) != 0) 3634 S = S->getParent(); 3635 3636 DeclContext *DC = CurContext; 3637 if (D.getCXXScopeSpec().isInvalid()) 3638 D.setInvalidType(); 3639 else if (D.getCXXScopeSpec().isSet()) { 3640 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3641 UPPC_DeclarationQualifier)) 3642 return 0; 3643 3644 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3645 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3646 if (!DC) { 3647 // If we could not compute the declaration context, it's because the 3648 // declaration context is dependent but does not refer to a class, 3649 // class template, or class template partial specialization. Complain 3650 // and return early, to avoid the coming semantic disaster. 3651 Diag(D.getIdentifierLoc(), 3652 diag::err_template_qualified_declarator_no_match) 3653 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3654 << D.getCXXScopeSpec().getRange(); 3655 return 0; 3656 } 3657 bool IsDependentContext = DC->isDependentContext(); 3658 3659 if (!IsDependentContext && 3660 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3661 return 0; 3662 3663 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 3664 Diag(D.getIdentifierLoc(), 3665 diag::err_member_def_undefined_record) 3666 << Name << DC << D.getCXXScopeSpec().getRange(); 3667 D.setInvalidType(); 3668 } else if (!D.getDeclSpec().isFriendSpecified()) { 3669 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 3670 Name, D.getIdentifierLoc())) { 3671 if (DC->isRecord()) 3672 return 0; 3673 3674 D.setInvalidType(); 3675 } 3676 } 3677 3678 // Check whether we need to rebuild the type of the given 3679 // declaration in the current instantiation. 3680 if (EnteringContext && IsDependentContext && 3681 TemplateParamLists.size() != 0) { 3682 ContextRAII SavedContext(*this, DC); 3683 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3684 D.setInvalidType(); 3685 } 3686 } 3687 3688 if (DiagnoseClassNameShadow(DC, NameInfo)) 3689 // If this is a typedef, we'll end up spewing multiple diagnostics. 3690 // Just return early; it's safer. 3691 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3692 return 0; 3693 3694 NamedDecl *New; 3695 3696 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3697 QualType R = TInfo->getType(); 3698 3699 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3700 UPPC_DeclarationType)) 3701 D.setInvalidType(); 3702 3703 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3704 ForRedeclaration); 3705 3706 // See if this is a redefinition of a variable in the same scope. 3707 if (!D.getCXXScopeSpec().isSet()) { 3708 bool IsLinkageLookup = false; 3709 3710 // If the declaration we're planning to build will be a function 3711 // or object with linkage, then look for another declaration with 3712 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3713 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3714 /* Do nothing*/; 3715 else if (R->isFunctionType()) { 3716 if (CurContext->isFunctionOrMethod() || 3717 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3718 IsLinkageLookup = true; 3719 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3720 IsLinkageLookup = true; 3721 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3722 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3723 IsLinkageLookup = true; 3724 3725 if (IsLinkageLookup) 3726 Previous.clear(LookupRedeclarationWithLinkage); 3727 3728 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3729 } else { // Something like "int foo::x;" 3730 LookupQualifiedName(Previous, DC); 3731 3732 // C++ [dcl.meaning]p1: 3733 // When the declarator-id is qualified, the declaration shall refer to a 3734 // previously declared member of the class or namespace to which the 3735 // qualifier refers (or, in the case of a namespace, of an element of the 3736 // inline namespace set of that namespace (7.3.1)) or to a specialization 3737 // thereof; [...] 3738 // 3739 // Note that we already checked the context above, and that we do not have 3740 // enough information to make sure that Previous contains the declaration 3741 // we want to match. For example, given: 3742 // 3743 // class X { 3744 // void f(); 3745 // void f(float); 3746 // }; 3747 // 3748 // void X::f(int) { } // ill-formed 3749 // 3750 // In this case, Previous will point to the overload set 3751 // containing the two f's declared in X, but neither of them 3752 // matches. 3753 3754 // C++ [dcl.meaning]p1: 3755 // [...] the member shall not merely have been introduced by a 3756 // using-declaration in the scope of the class or namespace nominated by 3757 // the nested-name-specifier of the declarator-id. 3758 RemoveUsingDecls(Previous); 3759 } 3760 3761 if (Previous.isSingleResult() && 3762 Previous.getFoundDecl()->isTemplateParameter()) { 3763 // Maybe we will complain about the shadowed template parameter. 3764 if (!D.isInvalidType()) 3765 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3766 Previous.getFoundDecl()); 3767 3768 // Just pretend that we didn't see the previous declaration. 3769 Previous.clear(); 3770 } 3771 3772 // In C++, the previous declaration we find might be a tag type 3773 // (class or enum). In this case, the new declaration will hide the 3774 // tag type. Note that this does does not apply if we're declaring a 3775 // typedef (C++ [dcl.typedef]p4). 3776 if (Previous.isSingleTagDecl() && 3777 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3778 Previous.clear(); 3779 3780 bool AddToScope = true; 3781 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3782 if (TemplateParamLists.size()) { 3783 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3784 return 0; 3785 } 3786 3787 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 3788 } else if (R->isFunctionType()) { 3789 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 3790 TemplateParamLists, 3791 AddToScope); 3792 } else { 3793 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 3794 TemplateParamLists); 3795 } 3796 3797 if (New == 0) 3798 return 0; 3799 3800 // If this has an identifier and is not an invalid redeclaration or 3801 // function template specialization, add it to the scope stack. 3802 if (New->getDeclName() && AddToScope && 3803 !(D.isRedeclaration() && New->isInvalidDecl())) 3804 PushOnScopeChains(New, S); 3805 3806 return New; 3807} 3808 3809/// Helper method to turn variable array types into constant array 3810/// types in certain situations which would otherwise be errors (for 3811/// GCC compatibility). 3812static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3813 ASTContext &Context, 3814 bool &SizeIsNegative, 3815 llvm::APSInt &Oversized) { 3816 // This method tries to turn a variable array into a constant 3817 // array even when the size isn't an ICE. This is necessary 3818 // for compatibility with code that depends on gcc's buggy 3819 // constant expression folding, like struct {char x[(int)(char*)2];} 3820 SizeIsNegative = false; 3821 Oversized = 0; 3822 3823 if (T->isDependentType()) 3824 return QualType(); 3825 3826 QualifierCollector Qs; 3827 const Type *Ty = Qs.strip(T); 3828 3829 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3830 QualType Pointee = PTy->getPointeeType(); 3831 QualType FixedType = 3832 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3833 Oversized); 3834 if (FixedType.isNull()) return FixedType; 3835 FixedType = Context.getPointerType(FixedType); 3836 return Qs.apply(Context, FixedType); 3837 } 3838 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3839 QualType Inner = PTy->getInnerType(); 3840 QualType FixedType = 3841 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3842 Oversized); 3843 if (FixedType.isNull()) return FixedType; 3844 FixedType = Context.getParenType(FixedType); 3845 return Qs.apply(Context, FixedType); 3846 } 3847 3848 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3849 if (!VLATy) 3850 return QualType(); 3851 // FIXME: We should probably handle this case 3852 if (VLATy->getElementType()->isVariablyModifiedType()) 3853 return QualType(); 3854 3855 llvm::APSInt Res; 3856 if (!VLATy->getSizeExpr() || 3857 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 3858 return QualType(); 3859 3860 // Check whether the array size is negative. 3861 if (Res.isSigned() && Res.isNegative()) { 3862 SizeIsNegative = true; 3863 return QualType(); 3864 } 3865 3866 // Check whether the array is too large to be addressed. 3867 unsigned ActiveSizeBits 3868 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3869 Res); 3870 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3871 Oversized = Res; 3872 return QualType(); 3873 } 3874 3875 return Context.getConstantArrayType(VLATy->getElementType(), 3876 Res, ArrayType::Normal, 0); 3877} 3878 3879static void 3880FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 3881 if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) { 3882 PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL); 3883 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(), 3884 DstPTL->getPointeeLoc()); 3885 DstPTL->setStarLoc(SrcPTL->getStarLoc()); 3886 return; 3887 } 3888 if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) { 3889 ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL); 3890 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(), 3891 DstPTL->getInnerLoc()); 3892 DstPTL->setLParenLoc(SrcPTL->getLParenLoc()); 3893 DstPTL->setRParenLoc(SrcPTL->getRParenLoc()); 3894 return; 3895 } 3896 ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL); 3897 ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL); 3898 TypeLoc SrcElemTL = SrcATL->getElementLoc(); 3899 TypeLoc DstElemTL = DstATL->getElementLoc(); 3900 DstElemTL.initializeFullCopy(SrcElemTL); 3901 DstATL->setLBracketLoc(SrcATL->getLBracketLoc()); 3902 DstATL->setSizeExpr(SrcATL->getSizeExpr()); 3903 DstATL->setRBracketLoc(SrcATL->getRBracketLoc()); 3904} 3905 3906/// Helper method to turn variable array types into constant array 3907/// types in certain situations which would otherwise be errors (for 3908/// GCC compatibility). 3909static TypeSourceInfo* 3910TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 3911 ASTContext &Context, 3912 bool &SizeIsNegative, 3913 llvm::APSInt &Oversized) { 3914 QualType FixedTy 3915 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 3916 SizeIsNegative, Oversized); 3917 if (FixedTy.isNull()) 3918 return 0; 3919 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 3920 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 3921 FixedTInfo->getTypeLoc()); 3922 return FixedTInfo; 3923} 3924 3925/// \brief Register the given locally-scoped external C declaration so 3926/// that it can be found later for redeclarations 3927void 3928Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3929 const LookupResult &Previous, 3930 Scope *S) { 3931 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3932 "Decl is not a locally-scoped decl!"); 3933 // Note that we have a locally-scoped external with this name. 3934 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3935 3936 if (!Previous.isSingleResult()) 3937 return; 3938 3939 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3940 3941 // If there was a previous declaration of this variable, it may be 3942 // in our identifier chain. Update the identifier chain with the new 3943 // declaration. 3944 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3945 // The previous declaration was found on the identifer resolver 3946 // chain, so remove it from its scope. 3947 3948 if (S->isDeclScope(PrevDecl)) { 3949 // Special case for redeclarations in the SAME scope. 3950 // Because this declaration is going to be added to the identifier chain 3951 // later, we should temporarily take it OFF the chain. 3952 IdResolver.RemoveDecl(ND); 3953 3954 } else { 3955 // Find the scope for the original declaration. 3956 while (S && !S->isDeclScope(PrevDecl)) 3957 S = S->getParent(); 3958 } 3959 3960 if (S) 3961 S->RemoveDecl(PrevDecl); 3962 } 3963} 3964 3965llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3966Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 3967 if (ExternalSource) { 3968 // Load locally-scoped external decls from the external source. 3969 SmallVector<NamedDecl *, 4> Decls; 3970 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 3971 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 3972 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3973 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 3974 if (Pos == LocallyScopedExternalDecls.end()) 3975 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 3976 } 3977 } 3978 3979 return LocallyScopedExternalDecls.find(Name); 3980} 3981 3982/// \brief Diagnose function specifiers on a declaration of an identifier that 3983/// does not identify a function. 3984void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3985 // FIXME: We should probably indicate the identifier in question to avoid 3986 // confusion for constructs like "inline int a(), b;" 3987 if (D.getDeclSpec().isInlineSpecified()) 3988 Diag(D.getDeclSpec().getInlineSpecLoc(), 3989 diag::err_inline_non_function); 3990 3991 if (D.getDeclSpec().isVirtualSpecified()) 3992 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3993 diag::err_virtual_non_function); 3994 3995 if (D.getDeclSpec().isExplicitSpecified()) 3996 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3997 diag::err_explicit_non_function); 3998} 3999 4000NamedDecl* 4001Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4002 TypeSourceInfo *TInfo, LookupResult &Previous) { 4003 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4004 if (D.getCXXScopeSpec().isSet()) { 4005 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4006 << D.getCXXScopeSpec().getRange(); 4007 D.setInvalidType(); 4008 // Pretend we didn't see the scope specifier. 4009 DC = CurContext; 4010 Previous.clear(); 4011 } 4012 4013 if (getLangOpts().CPlusPlus) { 4014 // Check that there are no default arguments (C++ only). 4015 CheckExtraCXXDefaultArguments(D); 4016 } 4017 4018 DiagnoseFunctionSpecifiers(D); 4019 4020 if (D.getDeclSpec().isThreadSpecified()) 4021 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4022 if (D.getDeclSpec().isConstexprSpecified()) 4023 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4024 << 1; 4025 4026 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4027 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4028 << D.getName().getSourceRange(); 4029 return 0; 4030 } 4031 4032 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4033 if (!NewTD) return 0; 4034 4035 // Handle attributes prior to checking for duplicates in MergeVarDecl 4036 ProcessDeclAttributes(S, NewTD, D); 4037 4038 CheckTypedefForVariablyModifiedType(S, NewTD); 4039 4040 bool Redeclaration = D.isRedeclaration(); 4041 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4042 D.setRedeclaration(Redeclaration); 4043 return ND; 4044} 4045 4046void 4047Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4048 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4049 // then it shall have block scope. 4050 // Note that variably modified types must be fixed before merging the decl so 4051 // that redeclarations will match. 4052 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4053 QualType T = TInfo->getType(); 4054 if (T->isVariablyModifiedType()) { 4055 getCurFunction()->setHasBranchProtectedScope(); 4056 4057 if (S->getFnParent() == 0) { 4058 bool SizeIsNegative; 4059 llvm::APSInt Oversized; 4060 TypeSourceInfo *FixedTInfo = 4061 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4062 SizeIsNegative, 4063 Oversized); 4064 if (FixedTInfo) { 4065 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4066 NewTD->setTypeSourceInfo(FixedTInfo); 4067 } else { 4068 if (SizeIsNegative) 4069 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4070 else if (T->isVariableArrayType()) 4071 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4072 else if (Oversized.getBoolValue()) 4073 Diag(NewTD->getLocation(), diag::err_array_too_large) 4074 << Oversized.toString(10); 4075 else 4076 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4077 NewTD->setInvalidDecl(); 4078 } 4079 } 4080 } 4081} 4082 4083 4084/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4085/// declares a typedef-name, either using the 'typedef' type specifier or via 4086/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4087NamedDecl* 4088Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4089 LookupResult &Previous, bool &Redeclaration) { 4090 // Merge the decl with the existing one if appropriate. If the decl is 4091 // in an outer scope, it isn't the same thing. 4092 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4093 /*ExplicitInstantiationOrSpecialization=*/false); 4094 if (!Previous.empty()) { 4095 Redeclaration = true; 4096 MergeTypedefNameDecl(NewTD, Previous); 4097 } 4098 4099 // If this is the C FILE type, notify the AST context. 4100 if (IdentifierInfo *II = NewTD->getIdentifier()) 4101 if (!NewTD->isInvalidDecl() && 4102 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4103 if (II->isStr("FILE")) 4104 Context.setFILEDecl(NewTD); 4105 else if (II->isStr("jmp_buf")) 4106 Context.setjmp_bufDecl(NewTD); 4107 else if (II->isStr("sigjmp_buf")) 4108 Context.setsigjmp_bufDecl(NewTD); 4109 else if (II->isStr("ucontext_t")) 4110 Context.setucontext_tDecl(NewTD); 4111 } 4112 4113 return NewTD; 4114} 4115 4116/// \brief Determines whether the given declaration is an out-of-scope 4117/// previous declaration. 4118/// 4119/// This routine should be invoked when name lookup has found a 4120/// previous declaration (PrevDecl) that is not in the scope where a 4121/// new declaration by the same name is being introduced. If the new 4122/// declaration occurs in a local scope, previous declarations with 4123/// linkage may still be considered previous declarations (C99 4124/// 6.2.2p4-5, C++ [basic.link]p6). 4125/// 4126/// \param PrevDecl the previous declaration found by name 4127/// lookup 4128/// 4129/// \param DC the context in which the new declaration is being 4130/// declared. 4131/// 4132/// \returns true if PrevDecl is an out-of-scope previous declaration 4133/// for a new delcaration with the same name. 4134static bool 4135isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4136 ASTContext &Context) { 4137 if (!PrevDecl) 4138 return false; 4139 4140 if (!PrevDecl->hasLinkage()) 4141 return false; 4142 4143 if (Context.getLangOpts().CPlusPlus) { 4144 // C++ [basic.link]p6: 4145 // If there is a visible declaration of an entity with linkage 4146 // having the same name and type, ignoring entities declared 4147 // outside the innermost enclosing namespace scope, the block 4148 // scope declaration declares that same entity and receives the 4149 // linkage of the previous declaration. 4150 DeclContext *OuterContext = DC->getRedeclContext(); 4151 if (!OuterContext->isFunctionOrMethod()) 4152 // This rule only applies to block-scope declarations. 4153 return false; 4154 4155 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4156 if (PrevOuterContext->isRecord()) 4157 // We found a member function: ignore it. 4158 return false; 4159 4160 // Find the innermost enclosing namespace for the new and 4161 // previous declarations. 4162 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4163 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4164 4165 // The previous declaration is in a different namespace, so it 4166 // isn't the same function. 4167 if (!OuterContext->Equals(PrevOuterContext)) 4168 return false; 4169 } 4170 4171 return true; 4172} 4173 4174static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4175 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4176 if (!SS.isSet()) return; 4177 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4178} 4179 4180bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4181 QualType type = decl->getType(); 4182 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4183 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4184 // Various kinds of declaration aren't allowed to be __autoreleasing. 4185 unsigned kind = -1U; 4186 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4187 if (var->hasAttr<BlocksAttr>()) 4188 kind = 0; // __block 4189 else if (!var->hasLocalStorage()) 4190 kind = 1; // global 4191 } else if (isa<ObjCIvarDecl>(decl)) { 4192 kind = 3; // ivar 4193 } else if (isa<FieldDecl>(decl)) { 4194 kind = 2; // field 4195 } 4196 4197 if (kind != -1U) { 4198 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4199 << kind; 4200 } 4201 } else if (lifetime == Qualifiers::OCL_None) { 4202 // Try to infer lifetime. 4203 if (!type->isObjCLifetimeType()) 4204 return false; 4205 4206 lifetime = type->getObjCARCImplicitLifetime(); 4207 type = Context.getLifetimeQualifiedType(type, lifetime); 4208 decl->setType(type); 4209 } 4210 4211 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4212 // Thread-local variables cannot have lifetime. 4213 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4214 var->isThreadSpecified()) { 4215 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4216 << var->getType(); 4217 return true; 4218 } 4219 } 4220 4221 return false; 4222} 4223 4224NamedDecl* 4225Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4226 TypeSourceInfo *TInfo, LookupResult &Previous, 4227 MultiTemplateParamsArg TemplateParamLists) { 4228 QualType R = TInfo->getType(); 4229 DeclarationName Name = GetNameForDeclarator(D).getName(); 4230 4231 // Check that there are no default arguments (C++ only). 4232 if (getLangOpts().CPlusPlus) 4233 CheckExtraCXXDefaultArguments(D); 4234 4235 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4236 assert(SCSpec != DeclSpec::SCS_typedef && 4237 "Parser allowed 'typedef' as storage class VarDecl."); 4238 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4239 if (SCSpec == DeclSpec::SCS_mutable) { 4240 // mutable can only appear on non-static class members, so it's always 4241 // an error here 4242 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4243 D.setInvalidType(); 4244 SC = SC_None; 4245 } 4246 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4247 VarDecl::StorageClass SCAsWritten 4248 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4249 4250 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4251 if (!II) { 4252 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4253 << Name; 4254 return 0; 4255 } 4256 4257 DiagnoseFunctionSpecifiers(D); 4258 4259 if (!DC->isRecord() && S->getFnParent() == 0) { 4260 // C99 6.9p2: The storage-class specifiers auto and register shall not 4261 // appear in the declaration specifiers in an external declaration. 4262 if (SC == SC_Auto || SC == SC_Register) { 4263 4264 // If this is a register variable with an asm label specified, then this 4265 // is a GNU extension. 4266 if (SC == SC_Register && D.getAsmLabel()) 4267 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4268 else 4269 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4270 D.setInvalidType(); 4271 } 4272 } 4273 4274 if (getLangOpts().OpenCL) { 4275 // Set up the special work-group-local storage class for variables in the 4276 // OpenCL __local address space. 4277 if (R.getAddressSpace() == LangAS::opencl_local) 4278 SC = SC_OpenCLWorkGroupLocal; 4279 } 4280 4281 bool isExplicitSpecialization = false; 4282 VarDecl *NewVD; 4283 if (!getLangOpts().CPlusPlus) { 4284 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4285 D.getIdentifierLoc(), II, 4286 R, TInfo, SC, SCAsWritten); 4287 4288 if (D.isInvalidType()) 4289 NewVD->setInvalidDecl(); 4290 } else { 4291 if (DC->isRecord() && !CurContext->isRecord()) { 4292 // This is an out-of-line definition of a static data member. 4293 if (SC == SC_Static) { 4294 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4295 diag::err_static_out_of_line) 4296 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4297 } else if (SC == SC_None) 4298 SC = SC_Static; 4299 } 4300 if (SC == SC_Static && CurContext->isRecord()) { 4301 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4302 if (RD->isLocalClass()) 4303 Diag(D.getIdentifierLoc(), 4304 diag::err_static_data_member_not_allowed_in_local_class) 4305 << Name << RD->getDeclName(); 4306 4307 // C++98 [class.union]p1: If a union contains a static data member, 4308 // the program is ill-formed. C++11 drops this restriction. 4309 if (RD->isUnion()) 4310 Diag(D.getIdentifierLoc(), 4311 getLangOpts().CPlusPlus0x 4312 ? diag::warn_cxx98_compat_static_data_member_in_union 4313 : diag::ext_static_data_member_in_union) << Name; 4314 // We conservatively disallow static data members in anonymous structs. 4315 else if (!RD->getDeclName()) 4316 Diag(D.getIdentifierLoc(), 4317 diag::err_static_data_member_not_allowed_in_anon_struct) 4318 << Name << RD->isUnion(); 4319 } 4320 } 4321 4322 // Match up the template parameter lists with the scope specifier, then 4323 // determine whether we have a template or a template specialization. 4324 isExplicitSpecialization = false; 4325 bool Invalid = false; 4326 if (TemplateParameterList *TemplateParams 4327 = MatchTemplateParametersToScopeSpecifier( 4328 D.getDeclSpec().getLocStart(), 4329 D.getIdentifierLoc(), 4330 D.getCXXScopeSpec(), 4331 TemplateParamLists.data(), 4332 TemplateParamLists.size(), 4333 /*never a friend*/ false, 4334 isExplicitSpecialization, 4335 Invalid)) { 4336 if (TemplateParams->size() > 0) { 4337 // There is no such thing as a variable template. 4338 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4339 << II 4340 << SourceRange(TemplateParams->getTemplateLoc(), 4341 TemplateParams->getRAngleLoc()); 4342 return 0; 4343 } else { 4344 // There is an extraneous 'template<>' for this variable. Complain 4345 // about it, but allow the declaration of the variable. 4346 Diag(TemplateParams->getTemplateLoc(), 4347 diag::err_template_variable_noparams) 4348 << II 4349 << SourceRange(TemplateParams->getTemplateLoc(), 4350 TemplateParams->getRAngleLoc()); 4351 } 4352 } 4353 4354 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4355 D.getIdentifierLoc(), II, 4356 R, TInfo, SC, SCAsWritten); 4357 4358 // If this decl has an auto type in need of deduction, make a note of the 4359 // Decl so we can diagnose uses of it in its own initializer. 4360 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4361 R->getContainedAutoType()) 4362 ParsingInitForAutoVars.insert(NewVD); 4363 4364 if (D.isInvalidType() || Invalid) 4365 NewVD->setInvalidDecl(); 4366 4367 SetNestedNameSpecifier(NewVD, D); 4368 4369 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4370 NewVD->setTemplateParameterListsInfo(Context, 4371 TemplateParamLists.size(), 4372 TemplateParamLists.data()); 4373 } 4374 4375 if (D.getDeclSpec().isConstexprSpecified()) 4376 NewVD->setConstexpr(true); 4377 } 4378 4379 // Set the lexical context. If the declarator has a C++ scope specifier, the 4380 // lexical context will be different from the semantic context. 4381 NewVD->setLexicalDeclContext(CurContext); 4382 4383 if (D.getDeclSpec().isThreadSpecified()) { 4384 if (NewVD->hasLocalStorage()) 4385 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4386 else if (!Context.getTargetInfo().isTLSSupported()) 4387 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4388 else 4389 NewVD->setThreadSpecified(true); 4390 } 4391 4392 if (D.getDeclSpec().isModulePrivateSpecified()) { 4393 if (isExplicitSpecialization) 4394 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4395 << 2 4396 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4397 else if (NewVD->hasLocalStorage()) 4398 Diag(NewVD->getLocation(), diag::err_module_private_local) 4399 << 0 << NewVD->getDeclName() 4400 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4401 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4402 else 4403 NewVD->setModulePrivate(); 4404 } 4405 4406 // Handle attributes prior to checking for duplicates in MergeVarDecl 4407 ProcessDeclAttributes(S, NewVD, D); 4408 4409 if (getLangOpts().CUDA) { 4410 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4411 // storage [duration]." 4412 if (SC == SC_None && S->getFnParent() != 0 && 4413 (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>())) 4414 NewVD->setStorageClass(SC_Static); 4415 } 4416 4417 // In auto-retain/release, infer strong retension for variables of 4418 // retainable type. 4419 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4420 NewVD->setInvalidDecl(); 4421 4422 // Handle GNU asm-label extension (encoded as an attribute). 4423 if (Expr *E = (Expr*)D.getAsmLabel()) { 4424 // The parser guarantees this is a string. 4425 StringLiteral *SE = cast<StringLiteral>(E); 4426 StringRef Label = SE->getString(); 4427 if (S->getFnParent() != 0) { 4428 switch (SC) { 4429 case SC_None: 4430 case SC_Auto: 4431 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4432 break; 4433 case SC_Register: 4434 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4435 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4436 break; 4437 case SC_Static: 4438 case SC_Extern: 4439 case SC_PrivateExtern: 4440 case SC_OpenCLWorkGroupLocal: 4441 break; 4442 } 4443 } 4444 4445 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4446 Context, Label)); 4447 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4448 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4449 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4450 if (I != ExtnameUndeclaredIdentifiers.end()) { 4451 NewVD->addAttr(I->second); 4452 ExtnameUndeclaredIdentifiers.erase(I); 4453 } 4454 } 4455 4456 // Diagnose shadowed variables before filtering for scope. 4457 if (!D.getCXXScopeSpec().isSet()) 4458 CheckShadow(S, NewVD, Previous); 4459 4460 // Don't consider existing declarations that are in a different 4461 // scope and are out-of-semantic-context declarations (if the new 4462 // declaration has linkage). 4463 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 4464 isExplicitSpecialization); 4465 4466 if (!getLangOpts().CPlusPlus) { 4467 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4468 } else { 4469 // Merge the decl with the existing one if appropriate. 4470 if (!Previous.empty()) { 4471 if (Previous.isSingleResult() && 4472 isa<FieldDecl>(Previous.getFoundDecl()) && 4473 D.getCXXScopeSpec().isSet()) { 4474 // The user tried to define a non-static data member 4475 // out-of-line (C++ [dcl.meaning]p1). 4476 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4477 << D.getCXXScopeSpec().getRange(); 4478 Previous.clear(); 4479 NewVD->setInvalidDecl(); 4480 } 4481 } else if (D.getCXXScopeSpec().isSet()) { 4482 // No previous declaration in the qualifying scope. 4483 Diag(D.getIdentifierLoc(), diag::err_no_member) 4484 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4485 << D.getCXXScopeSpec().getRange(); 4486 NewVD->setInvalidDecl(); 4487 } 4488 4489 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4490 4491 // This is an explicit specialization of a static data member. Check it. 4492 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4493 CheckMemberSpecialization(NewVD, Previous)) 4494 NewVD->setInvalidDecl(); 4495 } 4496 4497 // If this is a locally-scoped extern C variable, update the map of 4498 // such variables. 4499 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4500 !NewVD->isInvalidDecl()) 4501 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4502 4503 // If there's a #pragma GCC visibility in scope, and this isn't a class 4504 // member, set the visibility of this variable. 4505 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4506 AddPushedVisibilityAttribute(NewVD); 4507 4508 MarkUnusedFileScopedDecl(NewVD); 4509 4510 return NewVD; 4511} 4512 4513/// \brief Diagnose variable or built-in function shadowing. Implements 4514/// -Wshadow. 4515/// 4516/// This method is called whenever a VarDecl is added to a "useful" 4517/// scope. 4518/// 4519/// \param S the scope in which the shadowing name is being declared 4520/// \param R the lookup of the name 4521/// 4522void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4523 // Return if warning is ignored. 4524 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4525 DiagnosticsEngine::Ignored) 4526 return; 4527 4528 // Don't diagnose declarations at file scope. 4529 if (D->hasGlobalStorage()) 4530 return; 4531 4532 DeclContext *NewDC = D->getDeclContext(); 4533 4534 // Only diagnose if we're shadowing an unambiguous field or variable. 4535 if (R.getResultKind() != LookupResult::Found) 4536 return; 4537 4538 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4539 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4540 return; 4541 4542 // Fields are not shadowed by variables in C++ static methods. 4543 if (isa<FieldDecl>(ShadowedDecl)) 4544 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4545 if (MD->isStatic()) 4546 return; 4547 4548 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4549 if (shadowedVar->isExternC()) { 4550 // For shadowing external vars, make sure that we point to the global 4551 // declaration, not a locally scoped extern declaration. 4552 for (VarDecl::redecl_iterator 4553 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4554 I != E; ++I) 4555 if (I->isFileVarDecl()) { 4556 ShadowedDecl = *I; 4557 break; 4558 } 4559 } 4560 4561 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 4562 4563 // Only warn about certain kinds of shadowing for class members. 4564 if (NewDC && NewDC->isRecord()) { 4565 // In particular, don't warn about shadowing non-class members. 4566 if (!OldDC->isRecord()) 4567 return; 4568 4569 // TODO: should we warn about static data members shadowing 4570 // static data members from base classes? 4571 4572 // TODO: don't diagnose for inaccessible shadowed members. 4573 // This is hard to do perfectly because we might friend the 4574 // shadowing context, but that's just a false negative. 4575 } 4576 4577 // Determine what kind of declaration we're shadowing. 4578 unsigned Kind; 4579 if (isa<RecordDecl>(OldDC)) { 4580 if (isa<FieldDecl>(ShadowedDecl)) 4581 Kind = 3; // field 4582 else 4583 Kind = 2; // static data member 4584 } else if (OldDC->isFileContext()) 4585 Kind = 1; // global 4586 else 4587 Kind = 0; // local 4588 4589 DeclarationName Name = R.getLookupName(); 4590 4591 // Emit warning and note. 4592 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 4593 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 4594} 4595 4596/// \brief Check -Wshadow without the advantage of a previous lookup. 4597void Sema::CheckShadow(Scope *S, VarDecl *D) { 4598 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 4599 DiagnosticsEngine::Ignored) 4600 return; 4601 4602 LookupResult R(*this, D->getDeclName(), D->getLocation(), 4603 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4604 LookupName(R, S); 4605 CheckShadow(S, D, R); 4606} 4607 4608/// \brief Perform semantic checking on a newly-created variable 4609/// declaration. 4610/// 4611/// This routine performs all of the type-checking required for a 4612/// variable declaration once it has been built. It is used both to 4613/// check variables after they have been parsed and their declarators 4614/// have been translated into a declaration, and to check variables 4615/// that have been instantiated from a template. 4616/// 4617/// Sets NewVD->isInvalidDecl() if an error was encountered. 4618/// 4619/// Returns true if the variable declaration is a redeclaration. 4620bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 4621 LookupResult &Previous) { 4622 // If the decl is already known invalid, don't check it. 4623 if (NewVD->isInvalidDecl()) 4624 return false; 4625 4626 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 4627 QualType T = TInfo->getType(); 4628 4629 if (T->isObjCObjectType()) { 4630 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4631 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4632 T = Context.getObjCObjectPointerType(T); 4633 NewVD->setType(T); 4634 } 4635 4636 // Emit an error if an address space was applied to decl with local storage. 4637 // This includes arrays of objects with address space qualifiers, but not 4638 // automatic variables that point to other address spaces. 4639 // ISO/IEC TR 18037 S5.1.2 4640 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4641 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4642 NewVD->setInvalidDecl(); 4643 return false; 4644 } 4645 4646 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 4647 // scope. 4648 if ((getLangOpts().OpenCLVersion >= 120) 4649 && NewVD->isStaticLocal()) { 4650 Diag(NewVD->getLocation(), diag::err_static_function_scope); 4651 NewVD->setInvalidDecl(); 4652 return false; 4653 } 4654 4655 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4656 && !NewVD->hasAttr<BlocksAttr>()) { 4657 if (getLangOpts().getGC() != LangOptions::NonGC) 4658 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4659 else { 4660 assert(!getLangOpts().ObjCAutoRefCount); 4661 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4662 } 4663 } 4664 4665 bool isVM = T->isVariablyModifiedType(); 4666 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4667 NewVD->hasAttr<BlocksAttr>()) 4668 getCurFunction()->setHasBranchProtectedScope(); 4669 4670 if ((isVM && NewVD->hasLinkage()) || 4671 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4672 bool SizeIsNegative; 4673 llvm::APSInt Oversized; 4674 TypeSourceInfo *FixedTInfo = 4675 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4676 SizeIsNegative, Oversized); 4677 if (FixedTInfo == 0 && T->isVariableArrayType()) { 4678 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4679 // FIXME: This won't give the correct result for 4680 // int a[10][n]; 4681 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4682 4683 if (NewVD->isFileVarDecl()) 4684 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4685 << SizeRange; 4686 else if (NewVD->getStorageClass() == SC_Static) 4687 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4688 << SizeRange; 4689 else 4690 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4691 << SizeRange; 4692 NewVD->setInvalidDecl(); 4693 return false; 4694 } 4695 4696 if (FixedTInfo == 0) { 4697 if (NewVD->isFileVarDecl()) 4698 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4699 else 4700 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4701 NewVD->setInvalidDecl(); 4702 return false; 4703 } 4704 4705 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4706 NewVD->setType(FixedTInfo->getType()); 4707 NewVD->setTypeSourceInfo(FixedTInfo); 4708 } 4709 4710 if (Previous.empty() && NewVD->isExternC()) { 4711 // Since we did not find anything by this name and we're declaring 4712 // an extern "C" variable, look for a non-visible extern "C" 4713 // declaration with the same name. 4714 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4715 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 4716 if (Pos != LocallyScopedExternalDecls.end()) 4717 Previous.addDecl(Pos->second); 4718 } 4719 4720 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4721 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4722 << T; 4723 NewVD->setInvalidDecl(); 4724 return false; 4725 } 4726 4727 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4728 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4729 NewVD->setInvalidDecl(); 4730 return false; 4731 } 4732 4733 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4734 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4735 NewVD->setInvalidDecl(); 4736 return false; 4737 } 4738 4739 if (NewVD->isConstexpr() && !T->isDependentType() && 4740 RequireLiteralType(NewVD->getLocation(), T, 4741 diag::err_constexpr_var_non_literal)) { 4742 NewVD->setInvalidDecl(); 4743 return false; 4744 } 4745 4746 if (!Previous.empty()) { 4747 MergeVarDecl(NewVD, Previous); 4748 return true; 4749 } 4750 return false; 4751} 4752 4753/// \brief Data used with FindOverriddenMethod 4754struct FindOverriddenMethodData { 4755 Sema *S; 4756 CXXMethodDecl *Method; 4757}; 4758 4759/// \brief Member lookup function that determines whether a given C++ 4760/// method overrides a method in a base class, to be used with 4761/// CXXRecordDecl::lookupInBases(). 4762static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4763 CXXBasePath &Path, 4764 void *UserData) { 4765 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4766 4767 FindOverriddenMethodData *Data 4768 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4769 4770 DeclarationName Name = Data->Method->getDeclName(); 4771 4772 // FIXME: Do we care about other names here too? 4773 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4774 // We really want to find the base class destructor here. 4775 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4776 CanQualType CT = Data->S->Context.getCanonicalType(T); 4777 4778 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4779 } 4780 4781 for (Path.Decls = BaseRecord->lookup(Name); 4782 Path.Decls.first != Path.Decls.second; 4783 ++Path.Decls.first) { 4784 NamedDecl *D = *Path.Decls.first; 4785 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4786 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4787 return true; 4788 } 4789 } 4790 4791 return false; 4792} 4793 4794namespace { 4795 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 4796} 4797/// \brief Report an error regarding overriding, along with any relevant 4798/// overriden methods. 4799/// 4800/// \param DiagID the primary error to report. 4801/// \param MD the overriding method. 4802/// \param OEK which overrides to include as notes. 4803static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 4804 OverrideErrorKind OEK = OEK_All) { 4805 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 4806 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4807 E = MD->end_overridden_methods(); 4808 I != E; ++I) { 4809 // This check (& the OEK parameter) could be replaced by a predicate, but 4810 // without lambdas that would be overkill. This is still nicer than writing 4811 // out the diag loop 3 times. 4812 if ((OEK == OEK_All) || 4813 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 4814 (OEK == OEK_Deleted && (*I)->isDeleted())) 4815 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 4816 } 4817} 4818 4819/// AddOverriddenMethods - See if a method overrides any in the base classes, 4820/// and if so, check that it's a valid override and remember it. 4821bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4822 // Look for virtual methods in base classes that this method might override. 4823 CXXBasePaths Paths; 4824 FindOverriddenMethodData Data; 4825 Data.Method = MD; 4826 Data.S = this; 4827 bool hasDeletedOverridenMethods = false; 4828 bool hasNonDeletedOverridenMethods = false; 4829 bool AddedAny = false; 4830 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4831 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4832 E = Paths.found_decls_end(); I != E; ++I) { 4833 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4834 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4835 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4836 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4837 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4838 hasDeletedOverridenMethods |= OldMD->isDeleted(); 4839 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 4840 AddedAny = true; 4841 } 4842 } 4843 } 4844 } 4845 4846 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 4847 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 4848 } 4849 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 4850 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 4851 } 4852 4853 return AddedAny; 4854} 4855 4856namespace { 4857 // Struct for holding all of the extra arguments needed by 4858 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 4859 struct ActOnFDArgs { 4860 Scope *S; 4861 Declarator &D; 4862 MultiTemplateParamsArg TemplateParamLists; 4863 bool AddToScope; 4864 }; 4865} 4866 4867namespace { 4868 4869// Callback to only accept typo corrections that have a non-zero edit distance. 4870// Also only accept corrections that have the same parent decl. 4871class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 4872 public: 4873 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 4874 CXXRecordDecl *Parent) 4875 : Context(Context), OriginalFD(TypoFD), 4876 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 4877 4878 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 4879 if (candidate.getEditDistance() == 0) 4880 return false; 4881 4882 llvm::SmallVector<unsigned, 1> MismatchedParams; 4883 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 4884 CDeclEnd = candidate.end(); 4885 CDecl != CDeclEnd; ++CDecl) { 4886 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4887 4888 if (FD && !FD->hasBody() && 4889 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 4890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 4891 CXXRecordDecl *Parent = MD->getParent(); 4892 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 4893 return true; 4894 } else if (!ExpectedParent) { 4895 return true; 4896 } 4897 } 4898 } 4899 4900 return false; 4901 } 4902 4903 private: 4904 ASTContext &Context; 4905 FunctionDecl *OriginalFD; 4906 CXXRecordDecl *ExpectedParent; 4907}; 4908 4909} 4910 4911/// \brief Generate diagnostics for an invalid function redeclaration. 4912/// 4913/// This routine handles generating the diagnostic messages for an invalid 4914/// function redeclaration, including finding possible similar declarations 4915/// or performing typo correction if there are no previous declarations with 4916/// the same name. 4917/// 4918/// Returns a NamedDecl iff typo correction was performed and substituting in 4919/// the new declaration name does not cause new errors. 4920static NamedDecl* DiagnoseInvalidRedeclaration( 4921 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 4922 ActOnFDArgs &ExtraArgs) { 4923 NamedDecl *Result = NULL; 4924 DeclarationName Name = NewFD->getDeclName(); 4925 DeclContext *NewDC = NewFD->getDeclContext(); 4926 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 4927 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4928 llvm::SmallVector<unsigned, 1> MismatchedParams; 4929 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 4930 TypoCorrection Correction; 4931 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 4932 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 4933 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 4934 : diag::err_member_def_does_not_match; 4935 4936 NewFD->setInvalidDecl(); 4937 SemaRef.LookupQualifiedName(Prev, NewDC); 4938 assert(!Prev.isAmbiguous() && 4939 "Cannot have an ambiguity in previous-declaration lookup"); 4940 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 4941 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 4942 MD ? MD->getParent() : 0); 4943 if (!Prev.empty()) { 4944 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4945 Func != FuncEnd; ++Func) { 4946 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 4947 if (FD && 4948 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4949 // Add 1 to the index so that 0 can mean the mismatch didn't 4950 // involve a parameter 4951 unsigned ParamNum = 4952 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4953 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4954 } 4955 } 4956 // If the qualified name lookup yielded nothing, try typo correction 4957 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 4958 Prev.getLookupKind(), 0, 0, 4959 Validator, NewDC))) { 4960 // Trap errors. 4961 Sema::SFINAETrap Trap(SemaRef); 4962 4963 // Set up everything for the call to ActOnFunctionDeclarator 4964 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 4965 ExtraArgs.D.getIdentifierLoc()); 4966 Previous.clear(); 4967 Previous.setLookupName(Correction.getCorrection()); 4968 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 4969 CDeclEnd = Correction.end(); 4970 CDecl != CDeclEnd; ++CDecl) { 4971 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4972 if (FD && !FD->hasBody() && 4973 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4974 Previous.addDecl(FD); 4975 } 4976 } 4977 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 4978 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 4979 // pieces need to verify the typo-corrected C++ declaraction and hopefully 4980 // eliminate the need for the parameter pack ExtraArgs. 4981 Result = SemaRef.ActOnFunctionDeclarator( 4982 ExtraArgs.S, ExtraArgs.D, 4983 Correction.getCorrectionDecl()->getDeclContext(), 4984 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 4985 ExtraArgs.AddToScope); 4986 if (Trap.hasErrorOccurred()) { 4987 // Pretend the typo correction never occurred 4988 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 4989 ExtraArgs.D.getIdentifierLoc()); 4990 ExtraArgs.D.setRedeclaration(wasRedeclaration); 4991 Previous.clear(); 4992 Previous.setLookupName(Name); 4993 Result = NULL; 4994 } else { 4995 for (LookupResult::iterator Func = Previous.begin(), 4996 FuncEnd = Previous.end(); 4997 Func != FuncEnd; ++Func) { 4998 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 4999 NearMatches.push_back(std::make_pair(FD, 0)); 5000 } 5001 } 5002 if (NearMatches.empty()) { 5003 // Ignore the correction if it didn't yield any close FunctionDecl matches 5004 Correction = TypoCorrection(); 5005 } else { 5006 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 5007 : diag::err_member_def_does_not_match_suggest; 5008 } 5009 } 5010 5011 if (Correction) { 5012 // FIXME: use Correction.getCorrectionRange() instead of computing the range 5013 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in 5014 // turn causes the correction to fully qualify the name. If we fix 5015 // CorrectTypo to minimally qualify then this change should be good. 5016 SourceRange FixItLoc(NewFD->getLocation()); 5017 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 5018 if (Correction.getCorrectionSpecifier() && SS.isValid()) 5019 FixItLoc.setBegin(SS.getBeginLoc()); 5020 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 5021 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 5022 << FixItHint::CreateReplacement( 5023 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 5024 } else { 5025 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 5026 << Name << NewDC << NewFD->getLocation(); 5027 } 5028 5029 bool NewFDisConst = false; 5030 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 5031 NewFDisConst = NewMD->isConst(); 5032 5033 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 5034 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 5035 NearMatch != NearMatchEnd; ++NearMatch) { 5036 FunctionDecl *FD = NearMatch->first; 5037 bool FDisConst = false; 5038 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 5039 FDisConst = MD->isConst(); 5040 5041 if (unsigned Idx = NearMatch->second) { 5042 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 5043 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 5044 if (Loc.isInvalid()) Loc = FD->getLocation(); 5045 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 5046 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 5047 } else if (Correction) { 5048 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 5049 << Correction.getQuoted(SemaRef.getLangOpts()); 5050 } else if (FDisConst != NewFDisConst) { 5051 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 5052 << NewFDisConst << FD->getSourceRange().getEnd(); 5053 } else 5054 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 5055 } 5056 return Result; 5057} 5058 5059static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 5060 Declarator &D) { 5061 switch (D.getDeclSpec().getStorageClassSpec()) { 5062 default: llvm_unreachable("Unknown storage class!"); 5063 case DeclSpec::SCS_auto: 5064 case DeclSpec::SCS_register: 5065 case DeclSpec::SCS_mutable: 5066 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5067 diag::err_typecheck_sclass_func); 5068 D.setInvalidType(); 5069 break; 5070 case DeclSpec::SCS_unspecified: break; 5071 case DeclSpec::SCS_extern: return SC_Extern; 5072 case DeclSpec::SCS_static: { 5073 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 5074 // C99 6.7.1p5: 5075 // The declaration of an identifier for a function that has 5076 // block scope shall have no explicit storage-class specifier 5077 // other than extern 5078 // See also (C++ [dcl.stc]p4). 5079 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5080 diag::err_static_block_func); 5081 break; 5082 } else 5083 return SC_Static; 5084 } 5085 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5086 } 5087 5088 // No explicit storage class has already been returned 5089 return SC_None; 5090} 5091 5092static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 5093 DeclContext *DC, QualType &R, 5094 TypeSourceInfo *TInfo, 5095 FunctionDecl::StorageClass SC, 5096 bool &IsVirtualOkay) { 5097 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 5098 DeclarationName Name = NameInfo.getName(); 5099 5100 FunctionDecl *NewFD = 0; 5101 bool isInline = D.getDeclSpec().isInlineSpecified(); 5102 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 5103 FunctionDecl::StorageClass SCAsWritten 5104 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 5105 5106 if (!SemaRef.getLangOpts().CPlusPlus) { 5107 // Determine whether the function was written with a 5108 // prototype. This true when: 5109 // - there is a prototype in the declarator, or 5110 // - the type R of the function is some kind of typedef or other reference 5111 // to a type name (which eventually refers to a function type). 5112 bool HasPrototype = 5113 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 5114 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 5115 5116 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 5117 D.getLocStart(), NameInfo, R, 5118 TInfo, SC, SCAsWritten, isInline, 5119 HasPrototype); 5120 if (D.isInvalidType()) 5121 NewFD->setInvalidDecl(); 5122 5123 // Set the lexical context. 5124 NewFD->setLexicalDeclContext(SemaRef.CurContext); 5125 5126 return NewFD; 5127 } 5128 5129 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5130 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5131 5132 // Check that the return type is not an abstract class type. 5133 // For record types, this is done by the AbstractClassUsageDiagnoser once 5134 // the class has been completely parsed. 5135 if (!DC->isRecord() && 5136 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 5137 R->getAs<FunctionType>()->getResultType(), 5138 diag::err_abstract_type_in_decl, 5139 SemaRef.AbstractReturnType)) 5140 D.setInvalidType(); 5141 5142 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 5143 // This is a C++ constructor declaration. 5144 assert(DC->isRecord() && 5145 "Constructors can only be declared in a member context"); 5146 5147 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 5148 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5149 D.getLocStart(), NameInfo, 5150 R, TInfo, isExplicit, isInline, 5151 /*isImplicitlyDeclared=*/false, 5152 isConstexpr); 5153 5154 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5155 // This is a C++ destructor declaration. 5156 if (DC->isRecord()) { 5157 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 5158 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 5159 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 5160 SemaRef.Context, Record, 5161 D.getLocStart(), 5162 NameInfo, R, TInfo, isInline, 5163 /*isImplicitlyDeclared=*/false); 5164 5165 // If the class is complete, then we now create the implicit exception 5166 // specification. If the class is incomplete or dependent, we can't do 5167 // it yet. 5168 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() && 5169 Record->getDefinition() && !Record->isBeingDefined() && 5170 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5171 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5172 } 5173 5174 IsVirtualOkay = true; 5175 return NewDD; 5176 5177 } else { 5178 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5179 D.setInvalidType(); 5180 5181 // Create a FunctionDecl to satisfy the function definition parsing 5182 // code path. 5183 return FunctionDecl::Create(SemaRef.Context, DC, 5184 D.getLocStart(), 5185 D.getIdentifierLoc(), Name, R, TInfo, 5186 SC, SCAsWritten, isInline, 5187 /*hasPrototype=*/true, isConstexpr); 5188 } 5189 5190 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5191 if (!DC->isRecord()) { 5192 SemaRef.Diag(D.getIdentifierLoc(), 5193 diag::err_conv_function_not_member); 5194 return 0; 5195 } 5196 5197 SemaRef.CheckConversionDeclarator(D, R, SC); 5198 IsVirtualOkay = true; 5199 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5200 D.getLocStart(), NameInfo, 5201 R, TInfo, isInline, isExplicit, 5202 isConstexpr, SourceLocation()); 5203 5204 } else if (DC->isRecord()) { 5205 // If the name of the function is the same as the name of the record, 5206 // then this must be an invalid constructor that has a return type. 5207 // (The parser checks for a return type and makes the declarator a 5208 // constructor if it has no return type). 5209 if (Name.getAsIdentifierInfo() && 5210 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5211 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5212 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5213 << SourceRange(D.getIdentifierLoc()); 5214 return 0; 5215 } 5216 5217 bool isStatic = SC == SC_Static; 5218 5219 // [class.free]p1: 5220 // Any allocation function for a class T is a static member 5221 // (even if not explicitly declared static). 5222 if (Name.getCXXOverloadedOperator() == OO_New || 5223 Name.getCXXOverloadedOperator() == OO_Array_New) 5224 isStatic = true; 5225 5226 // [class.free]p6 Any deallocation function for a class X is a static member 5227 // (even if not explicitly declared static). 5228 if (Name.getCXXOverloadedOperator() == OO_Delete || 5229 Name.getCXXOverloadedOperator() == OO_Array_Delete) 5230 isStatic = true; 5231 5232 IsVirtualOkay = !isStatic; 5233 5234 // This is a C++ method declaration. 5235 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5236 D.getLocStart(), NameInfo, R, 5237 TInfo, isStatic, SCAsWritten, isInline, 5238 isConstexpr, SourceLocation()); 5239 5240 } else { 5241 // Determine whether the function was written with a 5242 // prototype. This true when: 5243 // - we're in C++ (where every function has a prototype), 5244 return FunctionDecl::Create(SemaRef.Context, DC, 5245 D.getLocStart(), 5246 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 5247 true/*HasPrototype*/, isConstexpr); 5248 } 5249} 5250 5251void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 5252 // In C++, the empty parameter-type-list must be spelled "void"; a 5253 // typedef of void is not permitted. 5254 if (getLangOpts().CPlusPlus && 5255 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5256 bool IsTypeAlias = false; 5257 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5258 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5259 else if (const TemplateSpecializationType *TST = 5260 Param->getType()->getAs<TemplateSpecializationType>()) 5261 IsTypeAlias = TST->isTypeAlias(); 5262 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5263 << IsTypeAlias; 5264 } 5265} 5266 5267NamedDecl* 5268Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5269 TypeSourceInfo *TInfo, LookupResult &Previous, 5270 MultiTemplateParamsArg TemplateParamLists, 5271 bool &AddToScope) { 5272 QualType R = TInfo->getType(); 5273 5274 assert(R.getTypePtr()->isFunctionType()); 5275 5276 // TODO: consider using NameInfo for diagnostic. 5277 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5278 DeclarationName Name = NameInfo.getName(); 5279 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5280 5281 if (D.getDeclSpec().isThreadSpecified()) 5282 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5283 5284 // Do not allow returning a objc interface by-value. 5285 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5286 Diag(D.getIdentifierLoc(), 5287 diag::err_object_cannot_be_passed_returned_by_value) << 0 5288 << R->getAs<FunctionType>()->getResultType() 5289 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5290 5291 QualType T = R->getAs<FunctionType>()->getResultType(); 5292 T = Context.getObjCObjectPointerType(T); 5293 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5294 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5295 R = Context.getFunctionType(T, FPT->arg_type_begin(), 5296 FPT->getNumArgs(), EPI); 5297 } 5298 else if (isa<FunctionNoProtoType>(R)) 5299 R = Context.getFunctionNoProtoType(T); 5300 } 5301 5302 bool isFriend = false; 5303 FunctionTemplateDecl *FunctionTemplate = 0; 5304 bool isExplicitSpecialization = false; 5305 bool isFunctionTemplateSpecialization = false; 5306 5307 bool isDependentClassScopeExplicitSpecialization = false; 5308 bool HasExplicitTemplateArgs = false; 5309 TemplateArgumentListInfo TemplateArgs; 5310 5311 bool isVirtualOkay = false; 5312 5313 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5314 isVirtualOkay); 5315 if (!NewFD) return 0; 5316 5317 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5318 NewFD->setTopLevelDeclInObjCContainer(); 5319 5320 if (getLangOpts().CPlusPlus) { 5321 bool isInline = D.getDeclSpec().isInlineSpecified(); 5322 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5323 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5324 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5325 isFriend = D.getDeclSpec().isFriendSpecified(); 5326 if (isFriend && !isInline && D.isFunctionDefinition()) { 5327 // C++ [class.friend]p5 5328 // A function can be defined in a friend declaration of a 5329 // class . . . . Such a function is implicitly inline. 5330 NewFD->setImplicitlyInline(); 5331 } 5332 5333 // If this is a method defined in an __interface, and is not a constructor 5334 // or an overloaded operator, then set the pure flag (isVirtual will already 5335 // return true). 5336 if (const CXXRecordDecl *Parent = 5337 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 5338 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 5339 NewFD->setPure(true); 5340 } 5341 5342 SetNestedNameSpecifier(NewFD, D); 5343 isExplicitSpecialization = false; 5344 isFunctionTemplateSpecialization = false; 5345 if (D.isInvalidType()) 5346 NewFD->setInvalidDecl(); 5347 5348 // Set the lexical context. If the declarator has a C++ 5349 // scope specifier, or is the object of a friend declaration, the 5350 // lexical context will be different from the semantic context. 5351 NewFD->setLexicalDeclContext(CurContext); 5352 5353 // Match up the template parameter lists with the scope specifier, then 5354 // determine whether we have a template or a template specialization. 5355 bool Invalid = false; 5356 if (TemplateParameterList *TemplateParams 5357 = MatchTemplateParametersToScopeSpecifier( 5358 D.getDeclSpec().getLocStart(), 5359 D.getIdentifierLoc(), 5360 D.getCXXScopeSpec(), 5361 TemplateParamLists.data(), 5362 TemplateParamLists.size(), 5363 isFriend, 5364 isExplicitSpecialization, 5365 Invalid)) { 5366 if (TemplateParams->size() > 0) { 5367 // This is a function template 5368 5369 // Check that we can declare a template here. 5370 if (CheckTemplateDeclScope(S, TemplateParams)) 5371 return 0; 5372 5373 // A destructor cannot be a template. 5374 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5375 Diag(NewFD->getLocation(), diag::err_destructor_template); 5376 return 0; 5377 } 5378 5379 // If we're adding a template to a dependent context, we may need to 5380 // rebuilding some of the types used within the template parameter list, 5381 // now that we know what the current instantiation is. 5382 if (DC->isDependentContext()) { 5383 ContextRAII SavedContext(*this, DC); 5384 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5385 Invalid = true; 5386 } 5387 5388 5389 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5390 NewFD->getLocation(), 5391 Name, TemplateParams, 5392 NewFD); 5393 FunctionTemplate->setLexicalDeclContext(CurContext); 5394 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5395 5396 // For source fidelity, store the other template param lists. 5397 if (TemplateParamLists.size() > 1) { 5398 NewFD->setTemplateParameterListsInfo(Context, 5399 TemplateParamLists.size() - 1, 5400 TemplateParamLists.data()); 5401 } 5402 } else { 5403 // This is a function template specialization. 5404 isFunctionTemplateSpecialization = true; 5405 // For source fidelity, store all the template param lists. 5406 NewFD->setTemplateParameterListsInfo(Context, 5407 TemplateParamLists.size(), 5408 TemplateParamLists.data()); 5409 5410 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5411 if (isFriend) { 5412 // We want to remove the "template<>", found here. 5413 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5414 5415 // If we remove the template<> and the name is not a 5416 // template-id, we're actually silently creating a problem: 5417 // the friend declaration will refer to an untemplated decl, 5418 // and clearly the user wants a template specialization. So 5419 // we need to insert '<>' after the name. 5420 SourceLocation InsertLoc; 5421 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5422 InsertLoc = D.getName().getSourceRange().getEnd(); 5423 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5424 } 5425 5426 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5427 << Name << RemoveRange 5428 << FixItHint::CreateRemoval(RemoveRange) 5429 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5430 } 5431 } 5432 } 5433 else { 5434 // All template param lists were matched against the scope specifier: 5435 // this is NOT (an explicit specialization of) a template. 5436 if (TemplateParamLists.size() > 0) 5437 // For source fidelity, store all the template param lists. 5438 NewFD->setTemplateParameterListsInfo(Context, 5439 TemplateParamLists.size(), 5440 TemplateParamLists.data()); 5441 } 5442 5443 if (Invalid) { 5444 NewFD->setInvalidDecl(); 5445 if (FunctionTemplate) 5446 FunctionTemplate->setInvalidDecl(); 5447 } 5448 5449 // C++ [dcl.fct.spec]p5: 5450 // The virtual specifier shall only be used in declarations of 5451 // nonstatic class member functions that appear within a 5452 // member-specification of a class declaration; see 10.3. 5453 // 5454 if (isVirtual && !NewFD->isInvalidDecl()) { 5455 if (!isVirtualOkay) { 5456 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5457 diag::err_virtual_non_function); 5458 } else if (!CurContext->isRecord()) { 5459 // 'virtual' was specified outside of the class. 5460 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5461 diag::err_virtual_out_of_class) 5462 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5463 } else if (NewFD->getDescribedFunctionTemplate()) { 5464 // C++ [temp.mem]p3: 5465 // A member function template shall not be virtual. 5466 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5467 diag::err_virtual_member_function_template) 5468 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5469 } else { 5470 // Okay: Add virtual to the method. 5471 NewFD->setVirtualAsWritten(true); 5472 } 5473 } 5474 5475 // C++ [dcl.fct.spec]p3: 5476 // The inline specifier shall not appear on a block scope function 5477 // declaration. 5478 if (isInline && !NewFD->isInvalidDecl()) { 5479 if (CurContext->isFunctionOrMethod()) { 5480 // 'inline' is not allowed on block scope function declaration. 5481 Diag(D.getDeclSpec().getInlineSpecLoc(), 5482 diag::err_inline_declaration_block_scope) << Name 5483 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5484 } 5485 } 5486 5487 // C++ [dcl.fct.spec]p6: 5488 // The explicit specifier shall be used only in the declaration of a 5489 // constructor or conversion function within its class definition; 5490 // see 12.3.1 and 12.3.2. 5491 if (isExplicit && !NewFD->isInvalidDecl()) { 5492 if (!CurContext->isRecord()) { 5493 // 'explicit' was specified outside of the class. 5494 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5495 diag::err_explicit_out_of_class) 5496 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5497 } else if (!isa<CXXConstructorDecl>(NewFD) && 5498 !isa<CXXConversionDecl>(NewFD)) { 5499 // 'explicit' was specified on a function that wasn't a constructor 5500 // or conversion function. 5501 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5502 diag::err_explicit_non_ctor_or_conv_function) 5503 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5504 } 5505 } 5506 5507 if (isConstexpr) { 5508 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 5509 // are implicitly inline. 5510 NewFD->setImplicitlyInline(); 5511 5512 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 5513 // be either constructors or to return a literal type. Therefore, 5514 // destructors cannot be declared constexpr. 5515 if (isa<CXXDestructorDecl>(NewFD)) 5516 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 5517 } 5518 5519 // If __module_private__ was specified, mark the function accordingly. 5520 if (D.getDeclSpec().isModulePrivateSpecified()) { 5521 if (isFunctionTemplateSpecialization) { 5522 SourceLocation ModulePrivateLoc 5523 = D.getDeclSpec().getModulePrivateSpecLoc(); 5524 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 5525 << 0 5526 << FixItHint::CreateRemoval(ModulePrivateLoc); 5527 } else { 5528 NewFD->setModulePrivate(); 5529 if (FunctionTemplate) 5530 FunctionTemplate->setModulePrivate(); 5531 } 5532 } 5533 5534 if (isFriend) { 5535 // For now, claim that the objects have no previous declaration. 5536 if (FunctionTemplate) { 5537 FunctionTemplate->setObjectOfFriendDecl(false); 5538 FunctionTemplate->setAccess(AS_public); 5539 } 5540 NewFD->setObjectOfFriendDecl(false); 5541 NewFD->setAccess(AS_public); 5542 } 5543 5544 // If a function is defined as defaulted or deleted, mark it as such now. 5545 switch (D.getFunctionDefinitionKind()) { 5546 case FDK_Declaration: 5547 case FDK_Definition: 5548 break; 5549 5550 case FDK_Defaulted: 5551 NewFD->setDefaulted(); 5552 break; 5553 5554 case FDK_Deleted: 5555 NewFD->setDeletedAsWritten(); 5556 break; 5557 } 5558 5559 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 5560 D.isFunctionDefinition()) { 5561 // C++ [class.mfct]p2: 5562 // A member function may be defined (8.4) in its class definition, in 5563 // which case it is an inline member function (7.1.2) 5564 NewFD->setImplicitlyInline(); 5565 } 5566 5567 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 5568 !CurContext->isRecord()) { 5569 // C++ [class.static]p1: 5570 // A data or function member of a class may be declared static 5571 // in a class definition, in which case it is a static member of 5572 // the class. 5573 5574 // Complain about the 'static' specifier if it's on an out-of-line 5575 // member function definition. 5576 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5577 diag::err_static_out_of_line) 5578 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5579 } 5580 5581 // C++11 [except.spec]p15: 5582 // A deallocation function with no exception-specification is treated 5583 // as if it were specified with noexcept(true). 5584 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 5585 if ((Name.getCXXOverloadedOperator() == OO_Delete || 5586 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 5587 getLangOpts().CPlusPlus0x && FPT && !FPT->hasExceptionSpec()) { 5588 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5589 EPI.ExceptionSpecType = EST_BasicNoexcept; 5590 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 5591 FPT->arg_type_begin(), 5592 FPT->getNumArgs(), EPI)); 5593 } 5594 } 5595 5596 // Filter out previous declarations that don't match the scope. 5597 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 5598 isExplicitSpecialization || 5599 isFunctionTemplateSpecialization); 5600 5601 // Handle GNU asm-label extension (encoded as an attribute). 5602 if (Expr *E = (Expr*) D.getAsmLabel()) { 5603 // The parser guarantees this is a string. 5604 StringLiteral *SE = cast<StringLiteral>(E); 5605 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 5606 SE->getString())); 5607 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5608 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5609 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 5610 if (I != ExtnameUndeclaredIdentifiers.end()) { 5611 NewFD->addAttr(I->second); 5612 ExtnameUndeclaredIdentifiers.erase(I); 5613 } 5614 } 5615 5616 // Copy the parameter declarations from the declarator D to the function 5617 // declaration NewFD, if they are available. First scavenge them into Params. 5618 SmallVector<ParmVarDecl*, 16> Params; 5619 if (D.isFunctionDeclarator()) { 5620 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5621 5622 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 5623 // function that takes no arguments, not a function that takes a 5624 // single void argument. 5625 // We let through "const void" here because Sema::GetTypeForDeclarator 5626 // already checks for that case. 5627 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5628 FTI.ArgInfo[0].Param && 5629 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 5630 // Empty arg list, don't push any params. 5631 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 5632 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 5633 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 5634 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 5635 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 5636 Param->setDeclContext(NewFD); 5637 Params.push_back(Param); 5638 5639 if (Param->isInvalidDecl()) 5640 NewFD->setInvalidDecl(); 5641 } 5642 } 5643 5644 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 5645 // When we're declaring a function with a typedef, typeof, etc as in the 5646 // following example, we'll need to synthesize (unnamed) 5647 // parameters for use in the declaration. 5648 // 5649 // @code 5650 // typedef void fn(int); 5651 // fn f; 5652 // @endcode 5653 5654 // Synthesize a parameter for each argument type. 5655 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 5656 AE = FT->arg_type_end(); AI != AE; ++AI) { 5657 ParmVarDecl *Param = 5658 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 5659 Param->setScopeInfo(0, Params.size()); 5660 Params.push_back(Param); 5661 } 5662 } else { 5663 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 5664 "Should not need args for typedef of non-prototype fn"); 5665 } 5666 5667 // Finally, we know we have the right number of parameters, install them. 5668 NewFD->setParams(Params); 5669 5670 // Find all anonymous symbols defined during the declaration of this function 5671 // and add to NewFD. This lets us track decls such 'enum Y' in: 5672 // 5673 // void f(enum Y {AA} x) {} 5674 // 5675 // which would otherwise incorrectly end up in the translation unit scope. 5676 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 5677 DeclsInPrototypeScope.clear(); 5678 5679 // Process the non-inheritable attributes on this declaration. 5680 ProcessDeclAttributes(S, NewFD, D, 5681 /*NonInheritable=*/true, /*Inheritable=*/false); 5682 5683 // Functions returning a variably modified type violate C99 6.7.5.2p2 5684 // because all functions have linkage. 5685 if (!NewFD->isInvalidDecl() && 5686 NewFD->getResultType()->isVariablyModifiedType()) { 5687 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5688 NewFD->setInvalidDecl(); 5689 } 5690 5691 // Handle attributes. 5692 ProcessDeclAttributes(S, NewFD, D, 5693 /*NonInheritable=*/false, /*Inheritable=*/true); 5694 5695 QualType RetType = NewFD->getResultType(); 5696 const CXXRecordDecl *Ret = RetType->isRecordType() ? 5697 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 5698 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 5699 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 5700 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5701 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) { 5702 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 5703 Context)); 5704 } 5705 } 5706 5707 if (!getLangOpts().CPlusPlus) { 5708 // Perform semantic checking on the function declaration. 5709 bool isExplicitSpecialization=false; 5710 if (!NewFD->isInvalidDecl()) { 5711 if (NewFD->isMain()) 5712 CheckMain(NewFD, D.getDeclSpec()); 5713 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5714 isExplicitSpecialization)); 5715 } 5716 // Make graceful recovery from an invalid redeclaration. 5717 else if (!Previous.empty()) 5718 D.setRedeclaration(true); 5719 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5720 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5721 "previous declaration set still overloaded"); 5722 } else { 5723 // If the declarator is a template-id, translate the parser's template 5724 // argument list into our AST format. 5725 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5726 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5727 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5728 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5729 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5730 TemplateId->NumArgs); 5731 translateTemplateArguments(TemplateArgsPtr, 5732 TemplateArgs); 5733 5734 HasExplicitTemplateArgs = true; 5735 5736 if (NewFD->isInvalidDecl()) { 5737 HasExplicitTemplateArgs = false; 5738 } else if (FunctionTemplate) { 5739 // Function template with explicit template arguments. 5740 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 5741 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 5742 5743 HasExplicitTemplateArgs = false; 5744 } else if (!isFunctionTemplateSpecialization && 5745 !D.getDeclSpec().isFriendSpecified()) { 5746 // We have encountered something that the user meant to be a 5747 // specialization (because it has explicitly-specified template 5748 // arguments) but that was not introduced with a "template<>" (or had 5749 // too few of them). 5750 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5751 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5752 << FixItHint::CreateInsertion( 5753 D.getDeclSpec().getLocStart(), 5754 "template<> "); 5755 isFunctionTemplateSpecialization = true; 5756 } else { 5757 // "friend void foo<>(int);" is an implicit specialization decl. 5758 isFunctionTemplateSpecialization = true; 5759 } 5760 } else if (isFriend && isFunctionTemplateSpecialization) { 5761 // This combination is only possible in a recovery case; the user 5762 // wrote something like: 5763 // template <> friend void foo(int); 5764 // which we're recovering from as if the user had written: 5765 // friend void foo<>(int); 5766 // Go ahead and fake up a template id. 5767 HasExplicitTemplateArgs = true; 5768 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 5769 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 5770 } 5771 5772 // If it's a friend (and only if it's a friend), it's possible 5773 // that either the specialized function type or the specialized 5774 // template is dependent, and therefore matching will fail. In 5775 // this case, don't check the specialization yet. 5776 bool InstantiationDependent = false; 5777 if (isFunctionTemplateSpecialization && isFriend && 5778 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 5779 TemplateSpecializationType::anyDependentTemplateArguments( 5780 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 5781 InstantiationDependent))) { 5782 assert(HasExplicitTemplateArgs && 5783 "friend function specialization without template args"); 5784 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 5785 Previous)) 5786 NewFD->setInvalidDecl(); 5787 } else if (isFunctionTemplateSpecialization) { 5788 if (CurContext->isDependentContext() && CurContext->isRecord() 5789 && !isFriend) { 5790 isDependentClassScopeExplicitSpecialization = true; 5791 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 5792 diag::ext_function_specialization_in_class : 5793 diag::err_function_specialization_in_class) 5794 << NewFD->getDeclName(); 5795 } else if (CheckFunctionTemplateSpecialization(NewFD, 5796 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5797 Previous)) 5798 NewFD->setInvalidDecl(); 5799 5800 // C++ [dcl.stc]p1: 5801 // A storage-class-specifier shall not be specified in an explicit 5802 // specialization (14.7.3) 5803 if (SC != SC_None) { 5804 if (SC != NewFD->getStorageClass()) 5805 Diag(NewFD->getLocation(), 5806 diag::err_explicit_specialization_inconsistent_storage_class) 5807 << SC 5808 << FixItHint::CreateRemoval( 5809 D.getDeclSpec().getStorageClassSpecLoc()); 5810 5811 else 5812 Diag(NewFD->getLocation(), 5813 diag::ext_explicit_specialization_storage_class) 5814 << FixItHint::CreateRemoval( 5815 D.getDeclSpec().getStorageClassSpecLoc()); 5816 } 5817 5818 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 5819 if (CheckMemberSpecialization(NewFD, Previous)) 5820 NewFD->setInvalidDecl(); 5821 } 5822 5823 // Perform semantic checking on the function declaration. 5824 if (!isDependentClassScopeExplicitSpecialization) { 5825 if (NewFD->isInvalidDecl()) { 5826 // If this is a class member, mark the class invalid immediately. 5827 // This avoids some consistency errors later. 5828 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 5829 methodDecl->getParent()->setInvalidDecl(); 5830 } else { 5831 if (NewFD->isMain()) 5832 CheckMain(NewFD, D.getDeclSpec()); 5833 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5834 isExplicitSpecialization)); 5835 } 5836 } 5837 5838 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5839 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5840 "previous declaration set still overloaded"); 5841 5842 NamedDecl *PrincipalDecl = (FunctionTemplate 5843 ? cast<NamedDecl>(FunctionTemplate) 5844 : NewFD); 5845 5846 if (isFriend && D.isRedeclaration()) { 5847 AccessSpecifier Access = AS_public; 5848 if (!NewFD->isInvalidDecl()) 5849 Access = NewFD->getPreviousDecl()->getAccess(); 5850 5851 NewFD->setAccess(Access); 5852 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 5853 5854 PrincipalDecl->setObjectOfFriendDecl(true); 5855 } 5856 5857 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 5858 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5859 PrincipalDecl->setNonMemberOperator(); 5860 5861 // If we have a function template, check the template parameter 5862 // list. This will check and merge default template arguments. 5863 if (FunctionTemplate) { 5864 FunctionTemplateDecl *PrevTemplate = 5865 FunctionTemplate->getPreviousDecl(); 5866 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 5867 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 5868 D.getDeclSpec().isFriendSpecified() 5869 ? (D.isFunctionDefinition() 5870 ? TPC_FriendFunctionTemplateDefinition 5871 : TPC_FriendFunctionTemplate) 5872 : (D.getCXXScopeSpec().isSet() && 5873 DC && DC->isRecord() && 5874 DC->isDependentContext()) 5875 ? TPC_ClassTemplateMember 5876 : TPC_FunctionTemplate); 5877 } 5878 5879 if (NewFD->isInvalidDecl()) { 5880 // Ignore all the rest of this. 5881 } else if (!D.isRedeclaration()) { 5882 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 5883 AddToScope }; 5884 // Fake up an access specifier if it's supposed to be a class member. 5885 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 5886 NewFD->setAccess(AS_public); 5887 5888 // Qualified decls generally require a previous declaration. 5889 if (D.getCXXScopeSpec().isSet()) { 5890 // ...with the major exception of templated-scope or 5891 // dependent-scope friend declarations. 5892 5893 // TODO: we currently also suppress this check in dependent 5894 // contexts because (1) the parameter depth will be off when 5895 // matching friend templates and (2) we might actually be 5896 // selecting a friend based on a dependent factor. But there 5897 // are situations where these conditions don't apply and we 5898 // can actually do this check immediately. 5899 if (isFriend && 5900 (TemplateParamLists.size() || 5901 D.getCXXScopeSpec().getScopeRep()->isDependent() || 5902 CurContext->isDependentContext())) { 5903 // ignore these 5904 } else { 5905 // The user tried to provide an out-of-line definition for a 5906 // function that is a member of a class or namespace, but there 5907 // was no such member function declared (C++ [class.mfct]p2, 5908 // C++ [namespace.memdef]p2). For example: 5909 // 5910 // class X { 5911 // void f() const; 5912 // }; 5913 // 5914 // void X::f() { } // ill-formed 5915 // 5916 // Complain about this problem, and attempt to suggest close 5917 // matches (e.g., those that differ only in cv-qualifiers and 5918 // whether the parameter types are references). 5919 5920 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5921 NewFD, 5922 ExtraArgs)) { 5923 AddToScope = ExtraArgs.AddToScope; 5924 return Result; 5925 } 5926 } 5927 5928 // Unqualified local friend declarations are required to resolve 5929 // to something. 5930 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 5931 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5932 NewFD, 5933 ExtraArgs)) { 5934 AddToScope = ExtraArgs.AddToScope; 5935 return Result; 5936 } 5937 } 5938 5939 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 5940 !isFriend && !isFunctionTemplateSpecialization && 5941 !isExplicitSpecialization) { 5942 // An out-of-line member function declaration must also be a 5943 // definition (C++ [dcl.meaning]p1). 5944 // Note that this is not the case for explicit specializations of 5945 // function templates or member functions of class templates, per 5946 // C++ [temp.expl.spec]p2. We also allow these declarations as an 5947 // extension for compatibility with old SWIG code which likes to 5948 // generate them. 5949 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 5950 << D.getCXXScopeSpec().getRange(); 5951 } 5952 } 5953 5954 AddKnownFunctionAttributes(NewFD); 5955 5956 if (NewFD->hasAttr<OverloadableAttr>() && 5957 !NewFD->getType()->getAs<FunctionProtoType>()) { 5958 Diag(NewFD->getLocation(), 5959 diag::err_attribute_overloadable_no_prototype) 5960 << NewFD; 5961 5962 // Turn this into a variadic function with no parameters. 5963 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 5964 FunctionProtoType::ExtProtoInfo EPI; 5965 EPI.Variadic = true; 5966 EPI.ExtInfo = FT->getExtInfo(); 5967 5968 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 5969 NewFD->setType(R); 5970 } 5971 5972 // If there's a #pragma GCC visibility in scope, and this isn't a class 5973 // member, set the visibility of this function. 5974 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 5975 AddPushedVisibilityAttribute(NewFD); 5976 5977 // If there's a #pragma clang arc_cf_code_audited in scope, consider 5978 // marking the function. 5979 AddCFAuditedAttribute(NewFD); 5980 5981 // If this is a locally-scoped extern C function, update the 5982 // map of such names. 5983 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 5984 && !NewFD->isInvalidDecl()) 5985 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 5986 5987 // Set this FunctionDecl's range up to the right paren. 5988 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 5989 5990 if (getLangOpts().CPlusPlus) { 5991 if (FunctionTemplate) { 5992 if (NewFD->isInvalidDecl()) 5993 FunctionTemplate->setInvalidDecl(); 5994 return FunctionTemplate; 5995 } 5996 } 5997 5998 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 5999 if ((getLangOpts().OpenCLVersion >= 120) 6000 && NewFD->hasAttr<OpenCLKernelAttr>() 6001 && (SC == SC_Static)) { 6002 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 6003 D.setInvalidType(); 6004 } 6005 6006 MarkUnusedFileScopedDecl(NewFD); 6007 6008 if (getLangOpts().CUDA) 6009 if (IdentifierInfo *II = NewFD->getIdentifier()) 6010 if (!NewFD->isInvalidDecl() && 6011 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6012 if (II->isStr("cudaConfigureCall")) { 6013 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 6014 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 6015 6016 Context.setcudaConfigureCallDecl(NewFD); 6017 } 6018 } 6019 6020 // Here we have an function template explicit specialization at class scope. 6021 // The actually specialization will be postponed to template instatiation 6022 // time via the ClassScopeFunctionSpecializationDecl node. 6023 if (isDependentClassScopeExplicitSpecialization) { 6024 ClassScopeFunctionSpecializationDecl *NewSpec = 6025 ClassScopeFunctionSpecializationDecl::Create( 6026 Context, CurContext, SourceLocation(), 6027 cast<CXXMethodDecl>(NewFD), 6028 HasExplicitTemplateArgs, TemplateArgs); 6029 CurContext->addDecl(NewSpec); 6030 AddToScope = false; 6031 } 6032 6033 return NewFD; 6034} 6035 6036/// \brief Perform semantic checking of a new function declaration. 6037/// 6038/// Performs semantic analysis of the new function declaration 6039/// NewFD. This routine performs all semantic checking that does not 6040/// require the actual declarator involved in the declaration, and is 6041/// used both for the declaration of functions as they are parsed 6042/// (called via ActOnDeclarator) and for the declaration of functions 6043/// that have been instantiated via C++ template instantiation (called 6044/// via InstantiateDecl). 6045/// 6046/// \param IsExplicitSpecialization whether this new function declaration is 6047/// an explicit specialization of the previous declaration. 6048/// 6049/// This sets NewFD->isInvalidDecl() to true if there was an error. 6050/// 6051/// \returns true if the function declaration is a redeclaration. 6052bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 6053 LookupResult &Previous, 6054 bool IsExplicitSpecialization) { 6055 assert(!NewFD->getResultType()->isVariablyModifiedType() 6056 && "Variably modified return types are not handled here"); 6057 6058 // Check for a previous declaration of this name. 6059 if (Previous.empty() && NewFD->isExternC()) { 6060 // Since we did not find anything by this name and we're declaring 6061 // an extern "C" function, look for a non-visible extern "C" 6062 // declaration with the same name. 6063 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6064 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 6065 if (Pos != LocallyScopedExternalDecls.end()) 6066 Previous.addDecl(Pos->second); 6067 } 6068 6069 bool Redeclaration = false; 6070 6071 // Merge or overload the declaration with an existing declaration of 6072 // the same name, if appropriate. 6073 if (!Previous.empty()) { 6074 // Determine whether NewFD is an overload of PrevDecl or 6075 // a declaration that requires merging. If it's an overload, 6076 // there's no more work to do here; we'll just add the new 6077 // function to the scope. 6078 6079 NamedDecl *OldDecl = 0; 6080 if (!AllowOverloadingOfFunction(Previous, Context)) { 6081 Redeclaration = true; 6082 OldDecl = Previous.getFoundDecl(); 6083 } else { 6084 switch (CheckOverload(S, NewFD, Previous, OldDecl, 6085 /*NewIsUsingDecl*/ false)) { 6086 case Ovl_Match: 6087 Redeclaration = true; 6088 break; 6089 6090 case Ovl_NonFunction: 6091 Redeclaration = true; 6092 break; 6093 6094 case Ovl_Overload: 6095 Redeclaration = false; 6096 break; 6097 } 6098 6099 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 6100 // If a function name is overloadable in C, then every function 6101 // with that name must be marked "overloadable". 6102 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 6103 << Redeclaration << NewFD; 6104 NamedDecl *OverloadedDecl = 0; 6105 if (Redeclaration) 6106 OverloadedDecl = OldDecl; 6107 else if (!Previous.empty()) 6108 OverloadedDecl = Previous.getRepresentativeDecl(); 6109 if (OverloadedDecl) 6110 Diag(OverloadedDecl->getLocation(), 6111 diag::note_attribute_overloadable_prev_overload); 6112 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 6113 Context)); 6114 } 6115 } 6116 6117 if (Redeclaration) { 6118 // NewFD and OldDecl represent declarations that need to be 6119 // merged. 6120 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 6121 NewFD->setInvalidDecl(); 6122 return Redeclaration; 6123 } 6124 6125 Previous.clear(); 6126 Previous.addDecl(OldDecl); 6127 6128 if (FunctionTemplateDecl *OldTemplateDecl 6129 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 6130 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 6131 FunctionTemplateDecl *NewTemplateDecl 6132 = NewFD->getDescribedFunctionTemplate(); 6133 assert(NewTemplateDecl && "Template/non-template mismatch"); 6134 if (CXXMethodDecl *Method 6135 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 6136 Method->setAccess(OldTemplateDecl->getAccess()); 6137 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 6138 } 6139 6140 // If this is an explicit specialization of a member that is a function 6141 // template, mark it as a member specialization. 6142 if (IsExplicitSpecialization && 6143 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 6144 NewTemplateDecl->setMemberSpecialization(); 6145 assert(OldTemplateDecl->isMemberSpecialization()); 6146 } 6147 6148 } else { 6149 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 6150 NewFD->setAccess(OldDecl->getAccess()); 6151 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 6152 } 6153 } 6154 } 6155 6156 // Semantic checking for this function declaration (in isolation). 6157 if (getLangOpts().CPlusPlus) { 6158 // C++-specific checks. 6159 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 6160 CheckConstructor(Constructor); 6161 } else if (CXXDestructorDecl *Destructor = 6162 dyn_cast<CXXDestructorDecl>(NewFD)) { 6163 CXXRecordDecl *Record = Destructor->getParent(); 6164 QualType ClassType = Context.getTypeDeclType(Record); 6165 6166 // FIXME: Shouldn't we be able to perform this check even when the class 6167 // type is dependent? Both gcc and edg can handle that. 6168 if (!ClassType->isDependentType()) { 6169 DeclarationName Name 6170 = Context.DeclarationNames.getCXXDestructorName( 6171 Context.getCanonicalType(ClassType)); 6172 if (NewFD->getDeclName() != Name) { 6173 Diag(NewFD->getLocation(), diag::err_destructor_name); 6174 NewFD->setInvalidDecl(); 6175 return Redeclaration; 6176 } 6177 } 6178 } else if (CXXConversionDecl *Conversion 6179 = dyn_cast<CXXConversionDecl>(NewFD)) { 6180 ActOnConversionDeclarator(Conversion); 6181 } 6182 6183 // Find any virtual functions that this function overrides. 6184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 6185 if (!Method->isFunctionTemplateSpecialization() && 6186 !Method->getDescribedFunctionTemplate() && 6187 Method->isCanonicalDecl()) { 6188 if (AddOverriddenMethods(Method->getParent(), Method)) { 6189 // If the function was marked as "static", we have a problem. 6190 if (NewFD->getStorageClass() == SC_Static) { 6191 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 6192 } 6193 } 6194 } 6195 6196 if (Method->isStatic()) 6197 checkThisInStaticMemberFunctionType(Method); 6198 } 6199 6200 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6201 if (NewFD->isOverloadedOperator() && 6202 CheckOverloadedOperatorDeclaration(NewFD)) { 6203 NewFD->setInvalidDecl(); 6204 return Redeclaration; 6205 } 6206 6207 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6208 if (NewFD->getLiteralIdentifier() && 6209 CheckLiteralOperatorDeclaration(NewFD)) { 6210 NewFD->setInvalidDecl(); 6211 return Redeclaration; 6212 } 6213 6214 // In C++, check default arguments now that we have merged decls. Unless 6215 // the lexical context is the class, because in this case this is done 6216 // during delayed parsing anyway. 6217 if (!CurContext->isRecord()) 6218 CheckCXXDefaultArguments(NewFD); 6219 6220 // If this function declares a builtin function, check the type of this 6221 // declaration against the expected type for the builtin. 6222 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6223 ASTContext::GetBuiltinTypeError Error; 6224 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6225 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6226 // The type of this function differs from the type of the builtin, 6227 // so forget about the builtin entirely. 6228 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6229 } 6230 } 6231 6232 // If this function is declared as being extern "C", then check to see if 6233 // the function returns a UDT (class, struct, or union type) that is not C 6234 // compatible, and if it does, warn the user. 6235 if (NewFD->isExternC()) { 6236 QualType R = NewFD->getResultType(); 6237 if (R->isIncompleteType() && !R->isVoidType()) 6238 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6239 << NewFD << R; 6240 else if (!R.isPODType(Context) && !R->isVoidType() && 6241 !R->isObjCObjectPointerType()) 6242 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6243 } 6244 } 6245 return Redeclaration; 6246} 6247 6248void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6249 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6250 // static or constexpr is ill-formed. 6251 // C99 6.7.4p4: In a hosted environment, the inline function specifier 6252 // shall not appear in a declaration of main. 6253 // static main is not an error under C99, but we should warn about it. 6254 if (FD->getStorageClass() == SC_Static) 6255 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6256 ? diag::err_static_main : diag::warn_static_main) 6257 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6258 if (FD->isInlineSpecified()) 6259 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6260 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6261 if (FD->isConstexpr()) { 6262 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6263 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6264 FD->setConstexpr(false); 6265 } 6266 6267 QualType T = FD->getType(); 6268 assert(T->isFunctionType() && "function decl is not of function type"); 6269 const FunctionType* FT = T->castAs<FunctionType>(); 6270 6271 // All the standards say that main() should should return 'int'. 6272 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6273 // In C and C++, main magically returns 0 if you fall off the end; 6274 // set the flag which tells us that. 6275 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6276 FD->setHasImplicitReturnZero(true); 6277 6278 // In C with GNU extensions we allow main() to have non-integer return 6279 // type, but we should warn about the extension, and we disable the 6280 // implicit-return-zero rule. 6281 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6282 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6283 6284 // Otherwise, this is just a flat-out error. 6285 } else { 6286 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6287 FD->setInvalidDecl(true); 6288 } 6289 6290 // Treat protoless main() as nullary. 6291 if (isa<FunctionNoProtoType>(FT)) return; 6292 6293 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6294 unsigned nparams = FTP->getNumArgs(); 6295 assert(FD->getNumParams() == nparams); 6296 6297 bool HasExtraParameters = (nparams > 3); 6298 6299 // Darwin passes an undocumented fourth argument of type char**. If 6300 // other platforms start sprouting these, the logic below will start 6301 // getting shifty. 6302 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6303 HasExtraParameters = false; 6304 6305 if (HasExtraParameters) { 6306 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6307 FD->setInvalidDecl(true); 6308 nparams = 3; 6309 } 6310 6311 // FIXME: a lot of the following diagnostics would be improved 6312 // if we had some location information about types. 6313 6314 QualType CharPP = 6315 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6316 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6317 6318 for (unsigned i = 0; i < nparams; ++i) { 6319 QualType AT = FTP->getArgType(i); 6320 6321 bool mismatch = true; 6322 6323 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6324 mismatch = false; 6325 else if (Expected[i] == CharPP) { 6326 // As an extension, the following forms are okay: 6327 // char const ** 6328 // char const * const * 6329 // char * const * 6330 6331 QualifierCollector qs; 6332 const PointerType* PT; 6333 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 6334 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 6335 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 6336 qs.removeConst(); 6337 mismatch = !qs.empty(); 6338 } 6339 } 6340 6341 if (mismatch) { 6342 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 6343 // TODO: suggest replacing given type with expected type 6344 FD->setInvalidDecl(true); 6345 } 6346 } 6347 6348 if (nparams == 1 && !FD->isInvalidDecl()) { 6349 Diag(FD->getLocation(), diag::warn_main_one_arg); 6350 } 6351 6352 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 6353 Diag(FD->getLocation(), diag::err_main_template_decl); 6354 FD->setInvalidDecl(); 6355 } 6356} 6357 6358bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 6359 // FIXME: Need strict checking. In C89, we need to check for 6360 // any assignment, increment, decrement, function-calls, or 6361 // commas outside of a sizeof. In C99, it's the same list, 6362 // except that the aforementioned are allowed in unevaluated 6363 // expressions. Everything else falls under the 6364 // "may accept other forms of constant expressions" exception. 6365 // (We never end up here for C++, so the constant expression 6366 // rules there don't matter.) 6367 if (Init->isConstantInitializer(Context, false)) 6368 return false; 6369 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 6370 << Init->getSourceRange(); 6371 return true; 6372} 6373 6374namespace { 6375 // Visits an initialization expression to see if OrigDecl is evaluated in 6376 // its own initialization and throws a warning if it does. 6377 class SelfReferenceChecker 6378 : public EvaluatedExprVisitor<SelfReferenceChecker> { 6379 Sema &S; 6380 Decl *OrigDecl; 6381 bool isRecordType; 6382 bool isPODType; 6383 bool isReferenceType; 6384 6385 public: 6386 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 6387 6388 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 6389 S(S), OrigDecl(OrigDecl) { 6390 isPODType = false; 6391 isRecordType = false; 6392 isReferenceType = false; 6393 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 6394 isPODType = VD->getType().isPODType(S.Context); 6395 isRecordType = VD->getType()->isRecordType(); 6396 isReferenceType = VD->getType()->isReferenceType(); 6397 } 6398 } 6399 6400 // For most expressions, the cast is directly above the DeclRefExpr. 6401 // For conditional operators, the cast can be outside the conditional 6402 // operator if both expressions are DeclRefExpr's. 6403 void HandleValue(Expr *E) { 6404 if (isReferenceType) 6405 return; 6406 E = E->IgnoreParenImpCasts(); 6407 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 6408 HandleDeclRefExpr(DRE); 6409 return; 6410 } 6411 6412 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6413 HandleValue(CO->getTrueExpr()); 6414 HandleValue(CO->getFalseExpr()); 6415 return; 6416 } 6417 6418 if (isa<MemberExpr>(E)) { 6419 Expr *Base = E->IgnoreParenImpCasts(); 6420 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 6421 // Check for static member variables and don't warn on them. 6422 if (!isa<FieldDecl>(ME->getMemberDecl())) 6423 return; 6424 Base = ME->getBase()->IgnoreParenImpCasts(); 6425 } 6426 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 6427 HandleDeclRefExpr(DRE); 6428 return; 6429 } 6430 } 6431 6432 // Reference types are handled here since all uses of references are 6433 // bad, not just r-value uses. 6434 void VisitDeclRefExpr(DeclRefExpr *E) { 6435 if (isReferenceType) 6436 HandleDeclRefExpr(E); 6437 } 6438 6439 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 6440 if (E->getCastKind() == CK_LValueToRValue || 6441 (isRecordType && E->getCastKind() == CK_NoOp)) 6442 HandleValue(E->getSubExpr()); 6443 6444 Inherited::VisitImplicitCastExpr(E); 6445 } 6446 6447 void VisitMemberExpr(MemberExpr *E) { 6448 // Don't warn on arrays since they can be treated as pointers. 6449 if (E->getType()->canDecayToPointerType()) return; 6450 6451 // Warn when a non-static method call is followed by non-static member 6452 // field accesses, which is followed by a DeclRefExpr. 6453 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 6454 bool Warn = (MD && !MD->isStatic()); 6455 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 6456 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 6457 if (!isa<FieldDecl>(ME->getMemberDecl())) 6458 Warn = false; 6459 Base = ME->getBase()->IgnoreParenImpCasts(); 6460 } 6461 6462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 6463 if (Warn) 6464 HandleDeclRefExpr(DRE); 6465 return; 6466 } 6467 6468 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 6469 // Visit that expression. 6470 Visit(Base); 6471 } 6472 6473 void VisitUnaryOperator(UnaryOperator *E) { 6474 // For POD record types, addresses of its own members are well-defined. 6475 if (E->getOpcode() == UO_AddrOf && isRecordType && 6476 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 6477 if (!isPODType) 6478 HandleValue(E->getSubExpr()); 6479 return; 6480 } 6481 Inherited::VisitUnaryOperator(E); 6482 } 6483 6484 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 6485 6486 void HandleDeclRefExpr(DeclRefExpr *DRE) { 6487 Decl* ReferenceDecl = DRE->getDecl(); 6488 if (OrigDecl != ReferenceDecl) return; 6489 unsigned diag = isReferenceType 6490 ? diag::warn_uninit_self_reference_in_reference_init 6491 : diag::warn_uninit_self_reference_in_init; 6492 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 6493 S.PDiag(diag) 6494 << DRE->getNameInfo().getName() 6495 << OrigDecl->getLocation() 6496 << DRE->getSourceRange()); 6497 } 6498 }; 6499 6500 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 6501 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 6502 bool DirectInit) { 6503 // Parameters arguments are occassionially constructed with itself, 6504 // for instance, in recursive functions. Skip them. 6505 if (isa<ParmVarDecl>(OrigDecl)) 6506 return; 6507 6508 E = E->IgnoreParens(); 6509 6510 // Skip checking T a = a where T is not a record or reference type. 6511 // Doing so is a way to silence uninitialized warnings. 6512 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 6513 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 6514 if (ICE->getCastKind() == CK_LValueToRValue) 6515 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 6516 if (DRE->getDecl() == OrigDecl) 6517 return; 6518 6519 SelfReferenceChecker(S, OrigDecl).Visit(E); 6520 } 6521} 6522 6523/// AddInitializerToDecl - Adds the initializer Init to the 6524/// declaration dcl. If DirectInit is true, this is C++ direct 6525/// initialization rather than copy initialization. 6526void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 6527 bool DirectInit, bool TypeMayContainAuto) { 6528 // If there is no declaration, there was an error parsing it. Just ignore 6529 // the initializer. 6530 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 6531 return; 6532 6533 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 6534 // With declarators parsed the way they are, the parser cannot 6535 // distinguish between a normal initializer and a pure-specifier. 6536 // Thus this grotesque test. 6537 IntegerLiteral *IL; 6538 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 6539 Context.getCanonicalType(IL->getType()) == Context.IntTy) 6540 CheckPureMethod(Method, Init->getSourceRange()); 6541 else { 6542 Diag(Method->getLocation(), diag::err_member_function_initialization) 6543 << Method->getDeclName() << Init->getSourceRange(); 6544 Method->setInvalidDecl(); 6545 } 6546 return; 6547 } 6548 6549 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6550 if (!VDecl) { 6551 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 6552 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6553 RealDecl->setInvalidDecl(); 6554 return; 6555 } 6556 6557 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 6558 6559 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6560 AutoType *Auto = 0; 6561 if (TypeMayContainAuto && 6562 (Auto = VDecl->getType()->getContainedAutoType()) && 6563 !Auto->isDeduced()) { 6564 Expr *DeduceInit = Init; 6565 // Initializer could be a C++ direct-initializer. Deduction only works if it 6566 // contains exactly one expression. 6567 if (CXXDirectInit) { 6568 if (CXXDirectInit->getNumExprs() == 0) { 6569 // It isn't possible to write this directly, but it is possible to 6570 // end up in this situation with "auto x(some_pack...);" 6571 Diag(CXXDirectInit->getLocStart(), 6572 diag::err_auto_var_init_no_expression) 6573 << VDecl->getDeclName() << VDecl->getType() 6574 << VDecl->getSourceRange(); 6575 RealDecl->setInvalidDecl(); 6576 return; 6577 } else if (CXXDirectInit->getNumExprs() > 1) { 6578 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 6579 diag::err_auto_var_init_multiple_expressions) 6580 << VDecl->getDeclName() << VDecl->getType() 6581 << VDecl->getSourceRange(); 6582 RealDecl->setInvalidDecl(); 6583 return; 6584 } else { 6585 DeduceInit = CXXDirectInit->getExpr(0); 6586 } 6587 } 6588 TypeSourceInfo *DeducedType = 0; 6589 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 6590 DAR_Failed) 6591 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 6592 if (!DeducedType) { 6593 RealDecl->setInvalidDecl(); 6594 return; 6595 } 6596 VDecl->setTypeSourceInfo(DeducedType); 6597 VDecl->setType(DeducedType->getType()); 6598 VDecl->ClearLinkageCache(); 6599 6600 // In ARC, infer lifetime. 6601 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 6602 VDecl->setInvalidDecl(); 6603 6604 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 6605 // 'id' instead of a specific object type prevents most of our usual checks. 6606 // We only want to warn outside of template instantiations, though: 6607 // inside a template, the 'id' could have come from a parameter. 6608 if (ActiveTemplateInstantiations.empty() && 6609 DeducedType->getType()->isObjCIdType()) { 6610 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 6611 Diag(Loc, diag::warn_auto_var_is_id) 6612 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 6613 } 6614 6615 // If this is a redeclaration, check that the type we just deduced matches 6616 // the previously declared type. 6617 if (VarDecl *Old = VDecl->getPreviousDecl()) 6618 MergeVarDeclTypes(VDecl, Old); 6619 } 6620 6621 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 6622 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 6623 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 6624 VDecl->setInvalidDecl(); 6625 return; 6626 } 6627 6628 if (!VDecl->getType()->isDependentType()) { 6629 // A definition must end up with a complete type, which means it must be 6630 // complete with the restriction that an array type might be completed by 6631 // the initializer; note that later code assumes this restriction. 6632 QualType BaseDeclType = VDecl->getType(); 6633 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 6634 BaseDeclType = Array->getElementType(); 6635 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 6636 diag::err_typecheck_decl_incomplete_type)) { 6637 RealDecl->setInvalidDecl(); 6638 return; 6639 } 6640 6641 // The variable can not have an abstract class type. 6642 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6643 diag::err_abstract_type_in_decl, 6644 AbstractVariableType)) 6645 VDecl->setInvalidDecl(); 6646 } 6647 6648 const VarDecl *Def; 6649 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6650 Diag(VDecl->getLocation(), diag::err_redefinition) 6651 << VDecl->getDeclName(); 6652 Diag(Def->getLocation(), diag::note_previous_definition); 6653 VDecl->setInvalidDecl(); 6654 return; 6655 } 6656 6657 const VarDecl* PrevInit = 0; 6658 if (getLangOpts().CPlusPlus) { 6659 // C++ [class.static.data]p4 6660 // If a static data member is of const integral or const 6661 // enumeration type, its declaration in the class definition can 6662 // specify a constant-initializer which shall be an integral 6663 // constant expression (5.19). In that case, the member can appear 6664 // in integral constant expressions. The member shall still be 6665 // defined in a namespace scope if it is used in the program and the 6666 // namespace scope definition shall not contain an initializer. 6667 // 6668 // We already performed a redefinition check above, but for static 6669 // data members we also need to check whether there was an in-class 6670 // declaration with an initializer. 6671 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6672 Diag(VDecl->getLocation(), diag::err_redefinition) 6673 << VDecl->getDeclName(); 6674 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6675 return; 6676 } 6677 6678 if (VDecl->hasLocalStorage()) 6679 getCurFunction()->setHasBranchProtectedScope(); 6680 6681 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 6682 VDecl->setInvalidDecl(); 6683 return; 6684 } 6685 } 6686 6687 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 6688 // a kernel function cannot be initialized." 6689 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 6690 Diag(VDecl->getLocation(), diag::err_local_cant_init); 6691 VDecl->setInvalidDecl(); 6692 return; 6693 } 6694 6695 // Get the decls type and save a reference for later, since 6696 // CheckInitializerTypes may change it. 6697 QualType DclT = VDecl->getType(), SavT = DclT; 6698 6699 // Top-level message sends default to 'id' when we're in a debugger 6700 // and we are assigning it to a variable of 'id' type. 6701 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType()) 6702 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) { 6703 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 6704 if (Result.isInvalid()) { 6705 VDecl->setInvalidDecl(); 6706 return; 6707 } 6708 Init = Result.take(); 6709 } 6710 6711 // Perform the initialization. 6712 if (!VDecl->isInvalidDecl()) { 6713 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6714 InitializationKind Kind 6715 = DirectInit ? 6716 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 6717 Init->getLocStart(), 6718 Init->getLocEnd()) 6719 : InitializationKind::CreateDirectList( 6720 VDecl->getLocation()) 6721 : InitializationKind::CreateCopy(VDecl->getLocation(), 6722 Init->getLocStart()); 6723 6724 Expr **Args = &Init; 6725 unsigned NumArgs = 1; 6726 if (CXXDirectInit) { 6727 Args = CXXDirectInit->getExprs(); 6728 NumArgs = CXXDirectInit->getNumExprs(); 6729 } 6730 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 6731 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6732 MultiExprArg(Args, NumArgs), &DclT); 6733 if (Result.isInvalid()) { 6734 VDecl->setInvalidDecl(); 6735 return; 6736 } 6737 6738 Init = Result.takeAs<Expr>(); 6739 } 6740 6741 // Check for self-references within variable initializers. 6742 // Variables declared within a function/method body (except for references) 6743 // are handled by a dataflow analysis. 6744 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 6745 VDecl->getType()->isReferenceType()) { 6746 CheckSelfReference(*this, RealDecl, Init, DirectInit); 6747 } 6748 6749 // If the type changed, it means we had an incomplete type that was 6750 // completed by the initializer. For example: 6751 // int ary[] = { 1, 3, 5 }; 6752 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 6753 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 6754 VDecl->setType(DclT); 6755 6756 // Check any implicit conversions within the expression. 6757 CheckImplicitConversions(Init, VDecl->getLocation()); 6758 6759 if (!VDecl->isInvalidDecl()) { 6760 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 6761 6762 if (VDecl->hasAttr<BlocksAttr>()) 6763 checkRetainCycles(VDecl, Init); 6764 6765 // It is safe to assign a weak reference into a strong variable. 6766 // Although this code can still have problems: 6767 // id x = self.weakProp; 6768 // id y = self.weakProp; 6769 // we do not warn to warn spuriously when 'x' and 'y' are on separate 6770 // paths through the function. This should be revisited if 6771 // -Wrepeated-use-of-weak is made flow-sensitive. 6772 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 6773 DiagnosticsEngine::Level Level = 6774 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 6775 Init->getLocStart()); 6776 if (Level != DiagnosticsEngine::Ignored) 6777 getCurFunction()->markSafeWeakUse(Init); 6778 } 6779 } 6780 6781 Init = MaybeCreateExprWithCleanups(Init); 6782 // Attach the initializer to the decl. 6783 VDecl->setInit(Init); 6784 6785 if (VDecl->isLocalVarDecl()) { 6786 // C99 6.7.8p4: All the expressions in an initializer for an object that has 6787 // static storage duration shall be constant expressions or string literals. 6788 // C++ does not have this restriction. 6789 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 6790 VDecl->getStorageClass() == SC_Static) 6791 CheckForConstantInitializer(Init, DclT); 6792 } else if (VDecl->isStaticDataMember() && 6793 VDecl->getLexicalDeclContext()->isRecord()) { 6794 // This is an in-class initialization for a static data member, e.g., 6795 // 6796 // struct S { 6797 // static const int value = 17; 6798 // }; 6799 6800 // C++ [class.mem]p4: 6801 // A member-declarator can contain a constant-initializer only 6802 // if it declares a static member (9.4) of const integral or 6803 // const enumeration type, see 9.4.2. 6804 // 6805 // C++11 [class.static.data]p3: 6806 // If a non-volatile const static data member is of integral or 6807 // enumeration type, its declaration in the class definition can 6808 // specify a brace-or-equal-initializer in which every initalizer-clause 6809 // that is an assignment-expression is a constant expression. A static 6810 // data member of literal type can be declared in the class definition 6811 // with the constexpr specifier; if so, its declaration shall specify a 6812 // brace-or-equal-initializer in which every initializer-clause that is 6813 // an assignment-expression is a constant expression. 6814 6815 // Do nothing on dependent types. 6816 if (DclT->isDependentType()) { 6817 6818 // Allow any 'static constexpr' members, whether or not they are of literal 6819 // type. We separately check that every constexpr variable is of literal 6820 // type. 6821 } else if (VDecl->isConstexpr()) { 6822 6823 // Require constness. 6824 } else if (!DclT.isConstQualified()) { 6825 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 6826 << Init->getSourceRange(); 6827 VDecl->setInvalidDecl(); 6828 6829 // We allow integer constant expressions in all cases. 6830 } else if (DclT->isIntegralOrEnumerationType()) { 6831 // Check whether the expression is a constant expression. 6832 SourceLocation Loc; 6833 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified()) 6834 // In C++11, a non-constexpr const static data member with an 6835 // in-class initializer cannot be volatile. 6836 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 6837 else if (Init->isValueDependent()) 6838 ; // Nothing to check. 6839 else if (Init->isIntegerConstantExpr(Context, &Loc)) 6840 ; // Ok, it's an ICE! 6841 else if (Init->isEvaluatable(Context)) { 6842 // If we can constant fold the initializer through heroics, accept it, 6843 // but report this as a use of an extension for -pedantic. 6844 Diag(Loc, diag::ext_in_class_initializer_non_constant) 6845 << Init->getSourceRange(); 6846 } else { 6847 // Otherwise, this is some crazy unknown case. Report the issue at the 6848 // location provided by the isIntegerConstantExpr failed check. 6849 Diag(Loc, diag::err_in_class_initializer_non_constant) 6850 << Init->getSourceRange(); 6851 VDecl->setInvalidDecl(); 6852 } 6853 6854 // We allow foldable floating-point constants as an extension. 6855 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 6856 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 6857 << DclT << Init->getSourceRange(); 6858 if (getLangOpts().CPlusPlus0x) 6859 Diag(VDecl->getLocation(), 6860 diag::note_in_class_initializer_float_type_constexpr) 6861 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6862 6863 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 6864 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 6865 << Init->getSourceRange(); 6866 VDecl->setInvalidDecl(); 6867 } 6868 6869 // Suggest adding 'constexpr' in C++11 for literal types. 6870 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) { 6871 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 6872 << DclT << Init->getSourceRange() 6873 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6874 VDecl->setConstexpr(true); 6875 6876 } else { 6877 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 6878 << DclT << Init->getSourceRange(); 6879 VDecl->setInvalidDecl(); 6880 } 6881 } else if (VDecl->isFileVarDecl()) { 6882 if (VDecl->getStorageClassAsWritten() == SC_Extern && 6883 (!getLangOpts().CPlusPlus || 6884 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 6885 Diag(VDecl->getLocation(), diag::warn_extern_init); 6886 6887 // C99 6.7.8p4. All file scoped initializers need to be constant. 6888 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 6889 CheckForConstantInitializer(Init, DclT); 6890 } 6891 6892 // We will represent direct-initialization similarly to copy-initialization: 6893 // int x(1); -as-> int x = 1; 6894 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 6895 // 6896 // Clients that want to distinguish between the two forms, can check for 6897 // direct initializer using VarDecl::getInitStyle(). 6898 // A major benefit is that clients that don't particularly care about which 6899 // exactly form was it (like the CodeGen) can handle both cases without 6900 // special case code. 6901 6902 // C++ 8.5p11: 6903 // The form of initialization (using parentheses or '=') is generally 6904 // insignificant, but does matter when the entity being initialized has a 6905 // class type. 6906 if (CXXDirectInit) { 6907 assert(DirectInit && "Call-style initializer must be direct init."); 6908 VDecl->setInitStyle(VarDecl::CallInit); 6909 } else if (DirectInit) { 6910 // This must be list-initialization. No other way is direct-initialization. 6911 VDecl->setInitStyle(VarDecl::ListInit); 6912 } 6913 6914 CheckCompleteVariableDeclaration(VDecl); 6915} 6916 6917/// ActOnInitializerError - Given that there was an error parsing an 6918/// initializer for the given declaration, try to return to some form 6919/// of sanity. 6920void Sema::ActOnInitializerError(Decl *D) { 6921 // Our main concern here is re-establishing invariants like "a 6922 // variable's type is either dependent or complete". 6923 if (!D || D->isInvalidDecl()) return; 6924 6925 VarDecl *VD = dyn_cast<VarDecl>(D); 6926 if (!VD) return; 6927 6928 // Auto types are meaningless if we can't make sense of the initializer. 6929 if (ParsingInitForAutoVars.count(D)) { 6930 D->setInvalidDecl(); 6931 return; 6932 } 6933 6934 QualType Ty = VD->getType(); 6935 if (Ty->isDependentType()) return; 6936 6937 // Require a complete type. 6938 if (RequireCompleteType(VD->getLocation(), 6939 Context.getBaseElementType(Ty), 6940 diag::err_typecheck_decl_incomplete_type)) { 6941 VD->setInvalidDecl(); 6942 return; 6943 } 6944 6945 // Require an abstract type. 6946 if (RequireNonAbstractType(VD->getLocation(), Ty, 6947 diag::err_abstract_type_in_decl, 6948 AbstractVariableType)) { 6949 VD->setInvalidDecl(); 6950 return; 6951 } 6952 6953 // Don't bother complaining about constructors or destructors, 6954 // though. 6955} 6956 6957void Sema::ActOnUninitializedDecl(Decl *RealDecl, 6958 bool TypeMayContainAuto) { 6959 // If there is no declaration, there was an error parsing it. Just ignore it. 6960 if (RealDecl == 0) 6961 return; 6962 6963 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 6964 QualType Type = Var->getType(); 6965 6966 // C++11 [dcl.spec.auto]p3 6967 if (TypeMayContainAuto && Type->getContainedAutoType()) { 6968 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 6969 << Var->getDeclName() << Type; 6970 Var->setInvalidDecl(); 6971 return; 6972 } 6973 6974 // C++11 [class.static.data]p3: A static data member can be declared with 6975 // the constexpr specifier; if so, its declaration shall specify 6976 // a brace-or-equal-initializer. 6977 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 6978 // the definition of a variable [...] or the declaration of a static data 6979 // member. 6980 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 6981 if (Var->isStaticDataMember()) 6982 Diag(Var->getLocation(), 6983 diag::err_constexpr_static_mem_var_requires_init) 6984 << Var->getDeclName(); 6985 else 6986 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 6987 Var->setInvalidDecl(); 6988 return; 6989 } 6990 6991 switch (Var->isThisDeclarationADefinition()) { 6992 case VarDecl::Definition: 6993 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 6994 break; 6995 6996 // We have an out-of-line definition of a static data member 6997 // that has an in-class initializer, so we type-check this like 6998 // a declaration. 6999 // 7000 // Fall through 7001 7002 case VarDecl::DeclarationOnly: 7003 // It's only a declaration. 7004 7005 // Block scope. C99 6.7p7: If an identifier for an object is 7006 // declared with no linkage (C99 6.2.2p6), the type for the 7007 // object shall be complete. 7008 if (!Type->isDependentType() && Var->isLocalVarDecl() && 7009 !Var->getLinkage() && !Var->isInvalidDecl() && 7010 RequireCompleteType(Var->getLocation(), Type, 7011 diag::err_typecheck_decl_incomplete_type)) 7012 Var->setInvalidDecl(); 7013 7014 // Make sure that the type is not abstract. 7015 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7016 RequireNonAbstractType(Var->getLocation(), Type, 7017 diag::err_abstract_type_in_decl, 7018 AbstractVariableType)) 7019 Var->setInvalidDecl(); 7020 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7021 Var->getStorageClass() == SC_PrivateExtern) { 7022 Diag(Var->getLocation(), diag::warn_private_extern); 7023 Diag(Var->getLocation(), diag::note_private_extern); 7024 } 7025 7026 return; 7027 7028 case VarDecl::TentativeDefinition: 7029 // File scope. C99 6.9.2p2: A declaration of an identifier for an 7030 // object that has file scope without an initializer, and without a 7031 // storage-class specifier or with the storage-class specifier "static", 7032 // constitutes a tentative definition. Note: A tentative definition with 7033 // external linkage is valid (C99 6.2.2p5). 7034 if (!Var->isInvalidDecl()) { 7035 if (const IncompleteArrayType *ArrayT 7036 = Context.getAsIncompleteArrayType(Type)) { 7037 if (RequireCompleteType(Var->getLocation(), 7038 ArrayT->getElementType(), 7039 diag::err_illegal_decl_array_incomplete_type)) 7040 Var->setInvalidDecl(); 7041 } else if (Var->getStorageClass() == SC_Static) { 7042 // C99 6.9.2p3: If the declaration of an identifier for an object is 7043 // a tentative definition and has internal linkage (C99 6.2.2p3), the 7044 // declared type shall not be an incomplete type. 7045 // NOTE: code such as the following 7046 // static struct s; 7047 // struct s { int a; }; 7048 // is accepted by gcc. Hence here we issue a warning instead of 7049 // an error and we do not invalidate the static declaration. 7050 // NOTE: to avoid multiple warnings, only check the first declaration. 7051 if (Var->getPreviousDecl() == 0) 7052 RequireCompleteType(Var->getLocation(), Type, 7053 diag::ext_typecheck_decl_incomplete_type); 7054 } 7055 } 7056 7057 // Record the tentative definition; we're done. 7058 if (!Var->isInvalidDecl()) 7059 TentativeDefinitions.push_back(Var); 7060 return; 7061 } 7062 7063 // Provide a specific diagnostic for uninitialized variable 7064 // definitions with incomplete array type. 7065 if (Type->isIncompleteArrayType()) { 7066 Diag(Var->getLocation(), 7067 diag::err_typecheck_incomplete_array_needs_initializer); 7068 Var->setInvalidDecl(); 7069 return; 7070 } 7071 7072 // Provide a specific diagnostic for uninitialized variable 7073 // definitions with reference type. 7074 if (Type->isReferenceType()) { 7075 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 7076 << Var->getDeclName() 7077 << SourceRange(Var->getLocation(), Var->getLocation()); 7078 Var->setInvalidDecl(); 7079 return; 7080 } 7081 7082 // Do not attempt to type-check the default initializer for a 7083 // variable with dependent type. 7084 if (Type->isDependentType()) 7085 return; 7086 7087 if (Var->isInvalidDecl()) 7088 return; 7089 7090 if (RequireCompleteType(Var->getLocation(), 7091 Context.getBaseElementType(Type), 7092 diag::err_typecheck_decl_incomplete_type)) { 7093 Var->setInvalidDecl(); 7094 return; 7095 } 7096 7097 // The variable can not have an abstract class type. 7098 if (RequireNonAbstractType(Var->getLocation(), Type, 7099 diag::err_abstract_type_in_decl, 7100 AbstractVariableType)) { 7101 Var->setInvalidDecl(); 7102 return; 7103 } 7104 7105 // Check for jumps past the implicit initializer. C++0x 7106 // clarifies that this applies to a "variable with automatic 7107 // storage duration", not a "local variable". 7108 // C++11 [stmt.dcl]p3 7109 // A program that jumps from a point where a variable with automatic 7110 // storage duration is not in scope to a point where it is in scope is 7111 // ill-formed unless the variable has scalar type, class type with a 7112 // trivial default constructor and a trivial destructor, a cv-qualified 7113 // version of one of these types, or an array of one of the preceding 7114 // types and is declared without an initializer. 7115 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 7116 if (const RecordType *Record 7117 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 7118 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 7119 // Mark the function for further checking even if the looser rules of 7120 // C++11 do not require such checks, so that we can diagnose 7121 // incompatibilities with C++98. 7122 if (!CXXRecord->isPOD()) 7123 getCurFunction()->setHasBranchProtectedScope(); 7124 } 7125 } 7126 7127 // C++03 [dcl.init]p9: 7128 // If no initializer is specified for an object, and the 7129 // object is of (possibly cv-qualified) non-POD class type (or 7130 // array thereof), the object shall be default-initialized; if 7131 // the object is of const-qualified type, the underlying class 7132 // type shall have a user-declared default 7133 // constructor. Otherwise, if no initializer is specified for 7134 // a non- static object, the object and its subobjects, if 7135 // any, have an indeterminate initial value); if the object 7136 // or any of its subobjects are of const-qualified type, the 7137 // program is ill-formed. 7138 // C++0x [dcl.init]p11: 7139 // If no initializer is specified for an object, the object is 7140 // default-initialized; [...]. 7141 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 7142 InitializationKind Kind 7143 = InitializationKind::CreateDefault(Var->getLocation()); 7144 7145 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 7146 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg()); 7147 if (Init.isInvalid()) 7148 Var->setInvalidDecl(); 7149 else if (Init.get()) { 7150 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 7151 // This is important for template substitution. 7152 Var->setInitStyle(VarDecl::CallInit); 7153 } 7154 7155 CheckCompleteVariableDeclaration(Var); 7156 } 7157} 7158 7159void Sema::ActOnCXXForRangeDecl(Decl *D) { 7160 VarDecl *VD = dyn_cast<VarDecl>(D); 7161 if (!VD) { 7162 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 7163 D->setInvalidDecl(); 7164 return; 7165 } 7166 7167 VD->setCXXForRangeDecl(true); 7168 7169 // for-range-declaration cannot be given a storage class specifier. 7170 int Error = -1; 7171 switch (VD->getStorageClassAsWritten()) { 7172 case SC_None: 7173 break; 7174 case SC_Extern: 7175 Error = 0; 7176 break; 7177 case SC_Static: 7178 Error = 1; 7179 break; 7180 case SC_PrivateExtern: 7181 Error = 2; 7182 break; 7183 case SC_Auto: 7184 Error = 3; 7185 break; 7186 case SC_Register: 7187 Error = 4; 7188 break; 7189 case SC_OpenCLWorkGroupLocal: 7190 llvm_unreachable("Unexpected storage class"); 7191 } 7192 if (VD->isConstexpr()) 7193 Error = 5; 7194 if (Error != -1) { 7195 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 7196 << VD->getDeclName() << Error; 7197 D->setInvalidDecl(); 7198 } 7199} 7200 7201void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 7202 if (var->isInvalidDecl()) return; 7203 7204 // In ARC, don't allow jumps past the implicit initialization of a 7205 // local retaining variable. 7206 if (getLangOpts().ObjCAutoRefCount && 7207 var->hasLocalStorage()) { 7208 switch (var->getType().getObjCLifetime()) { 7209 case Qualifiers::OCL_None: 7210 case Qualifiers::OCL_ExplicitNone: 7211 case Qualifiers::OCL_Autoreleasing: 7212 break; 7213 7214 case Qualifiers::OCL_Weak: 7215 case Qualifiers::OCL_Strong: 7216 getCurFunction()->setHasBranchProtectedScope(); 7217 break; 7218 } 7219 } 7220 7221 if (var->isThisDeclarationADefinition() && 7222 var->getLinkage() == ExternalLinkage) { 7223 // Find a previous declaration that's not a definition. 7224 VarDecl *prev = var->getPreviousDecl(); 7225 while (prev && prev->isThisDeclarationADefinition()) 7226 prev = prev->getPreviousDecl(); 7227 7228 if (!prev) 7229 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 7230 } 7231 7232 // All the following checks are C++ only. 7233 if (!getLangOpts().CPlusPlus) return; 7234 7235 QualType type = var->getType(); 7236 if (type->isDependentType()) return; 7237 7238 // __block variables might require us to capture a copy-initializer. 7239 if (var->hasAttr<BlocksAttr>()) { 7240 // It's currently invalid to ever have a __block variable with an 7241 // array type; should we diagnose that here? 7242 7243 // Regardless, we don't want to ignore array nesting when 7244 // constructing this copy. 7245 if (type->isStructureOrClassType()) { 7246 SourceLocation poi = var->getLocation(); 7247 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 7248 ExprResult result = 7249 PerformCopyInitialization( 7250 InitializedEntity::InitializeBlock(poi, type, false), 7251 poi, Owned(varRef)); 7252 if (!result.isInvalid()) { 7253 result = MaybeCreateExprWithCleanups(result); 7254 Expr *init = result.takeAs<Expr>(); 7255 Context.setBlockVarCopyInits(var, init); 7256 } 7257 } 7258 } 7259 7260 Expr *Init = var->getInit(); 7261 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7262 QualType baseType = Context.getBaseElementType(type); 7263 7264 if (!var->getDeclContext()->isDependentContext() && 7265 Init && !Init->isValueDependent()) { 7266 if (IsGlobal && !var->isConstexpr() && 7267 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 7268 var->getLocation()) 7269 != DiagnosticsEngine::Ignored && 7270 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 7271 Diag(var->getLocation(), diag::warn_global_constructor) 7272 << Init->getSourceRange(); 7273 7274 if (var->isConstexpr()) { 7275 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 7276 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 7277 SourceLocation DiagLoc = var->getLocation(); 7278 // If the note doesn't add any useful information other than a source 7279 // location, fold it into the primary diagnostic. 7280 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 7281 diag::note_invalid_subexpr_in_const_expr) { 7282 DiagLoc = Notes[0].first; 7283 Notes.clear(); 7284 } 7285 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 7286 << var << Init->getSourceRange(); 7287 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 7288 Diag(Notes[I].first, Notes[I].second); 7289 } 7290 } else if (var->isUsableInConstantExpressions(Context)) { 7291 // Check whether the initializer of a const variable of integral or 7292 // enumeration type is an ICE now, since we can't tell whether it was 7293 // initialized by a constant expression if we check later. 7294 var->checkInitIsICE(); 7295 } 7296 } 7297 7298 // Require the destructor. 7299 if (const RecordType *recordType = baseType->getAs<RecordType>()) 7300 FinalizeVarWithDestructor(var, recordType); 7301} 7302 7303/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 7304/// any semantic actions necessary after any initializer has been attached. 7305void 7306Sema::FinalizeDeclaration(Decl *ThisDecl) { 7307 // Note that we are no longer parsing the initializer for this declaration. 7308 ParsingInitForAutoVars.erase(ThisDecl); 7309 7310 // Now we have parsed the initializer and can update the table of magic 7311 // tag values. 7312 if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) { 7313 const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl); 7314 if (VD && VD->getType()->isIntegralOrEnumerationType()) { 7315 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7316 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 7317 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 7318 I != E; ++I) { 7319 const Expr *MagicValueExpr = VD->getInit(); 7320 if (!MagicValueExpr) { 7321 continue; 7322 } 7323 llvm::APSInt MagicValueInt; 7324 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 7325 Diag(I->getRange().getBegin(), 7326 diag::err_type_tag_for_datatype_not_ice) 7327 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7328 continue; 7329 } 7330 if (MagicValueInt.getActiveBits() > 64) { 7331 Diag(I->getRange().getBegin(), 7332 diag::err_type_tag_for_datatype_too_large) 7333 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7334 continue; 7335 } 7336 uint64_t MagicValue = MagicValueInt.getZExtValue(); 7337 RegisterTypeTagForDatatype(I->getArgumentKind(), 7338 MagicValue, 7339 I->getMatchingCType(), 7340 I->getLayoutCompatible(), 7341 I->getMustBeNull()); 7342 } 7343 } 7344 } 7345} 7346 7347Sema::DeclGroupPtrTy 7348Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 7349 Decl **Group, unsigned NumDecls) { 7350 SmallVector<Decl*, 8> Decls; 7351 7352 if (DS.isTypeSpecOwned()) 7353 Decls.push_back(DS.getRepAsDecl()); 7354 7355 for (unsigned i = 0; i != NumDecls; ++i) 7356 if (Decl *D = Group[i]) 7357 Decls.push_back(D); 7358 7359 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) 7360 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) 7361 getASTContext().addUnnamedTag(Tag); 7362 7363 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 7364 DS.getTypeSpecType() == DeclSpec::TST_auto); 7365} 7366 7367/// BuildDeclaratorGroup - convert a list of declarations into a declaration 7368/// group, performing any necessary semantic checking. 7369Sema::DeclGroupPtrTy 7370Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 7371 bool TypeMayContainAuto) { 7372 // C++0x [dcl.spec.auto]p7: 7373 // If the type deduced for the template parameter U is not the same in each 7374 // deduction, the program is ill-formed. 7375 // FIXME: When initializer-list support is added, a distinction is needed 7376 // between the deduced type U and the deduced type which 'auto' stands for. 7377 // auto a = 0, b = { 1, 2, 3 }; 7378 // is legal because the deduced type U is 'int' in both cases. 7379 if (TypeMayContainAuto && NumDecls > 1) { 7380 QualType Deduced; 7381 CanQualType DeducedCanon; 7382 VarDecl *DeducedDecl = 0; 7383 for (unsigned i = 0; i != NumDecls; ++i) { 7384 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 7385 AutoType *AT = D->getType()->getContainedAutoType(); 7386 // Don't reissue diagnostics when instantiating a template. 7387 if (AT && D->isInvalidDecl()) 7388 break; 7389 if (AT && AT->isDeduced()) { 7390 QualType U = AT->getDeducedType(); 7391 CanQualType UCanon = Context.getCanonicalType(U); 7392 if (Deduced.isNull()) { 7393 Deduced = U; 7394 DeducedCanon = UCanon; 7395 DeducedDecl = D; 7396 } else if (DeducedCanon != UCanon) { 7397 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 7398 diag::err_auto_different_deductions) 7399 << Deduced << DeducedDecl->getDeclName() 7400 << U << D->getDeclName() 7401 << DeducedDecl->getInit()->getSourceRange() 7402 << D->getInit()->getSourceRange(); 7403 D->setInvalidDecl(); 7404 break; 7405 } 7406 } 7407 } 7408 } 7409 } 7410 7411 ActOnDocumentableDecls(Group, NumDecls); 7412 7413 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 7414} 7415 7416void Sema::ActOnDocumentableDecl(Decl *D) { 7417 ActOnDocumentableDecls(&D, 1); 7418} 7419 7420void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 7421 // Don't parse the comment if Doxygen diagnostics are ignored. 7422 if (NumDecls == 0 || !Group[0]) 7423 return; 7424 7425 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 7426 Group[0]->getLocation()) 7427 == DiagnosticsEngine::Ignored) 7428 return; 7429 7430 if (NumDecls >= 2) { 7431 // This is a decl group. Normally it will contain only declarations 7432 // procuded from declarator list. But in case we have any definitions or 7433 // additional declaration references: 7434 // 'typedef struct S {} S;' 7435 // 'typedef struct S *S;' 7436 // 'struct S *pS;' 7437 // FinalizeDeclaratorGroup adds these as separate declarations. 7438 Decl *MaybeTagDecl = Group[0]; 7439 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 7440 Group++; 7441 NumDecls--; 7442 } 7443 } 7444 7445 // See if there are any new comments that are not attached to a decl. 7446 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 7447 if (!Comments.empty() && 7448 !Comments.back()->isAttached()) { 7449 // There is at least one comment that not attached to a decl. 7450 // Maybe it should be attached to one of these decls? 7451 // 7452 // Note that this way we pick up not only comments that precede the 7453 // declaration, but also comments that *follow* the declaration -- thanks to 7454 // the lookahead in the lexer: we've consumed the semicolon and looked 7455 // ahead through comments. 7456 for (unsigned i = 0; i != NumDecls; ++i) 7457 Context.getCommentForDecl(Group[i], &PP); 7458 } 7459} 7460 7461/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 7462/// to introduce parameters into function prototype scope. 7463Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 7464 const DeclSpec &DS = D.getDeclSpec(); 7465 7466 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 7467 // C++03 [dcl.stc]p2 also permits 'auto'. 7468 VarDecl::StorageClass StorageClass = SC_None; 7469 VarDecl::StorageClass StorageClassAsWritten = SC_None; 7470 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 7471 StorageClass = SC_Register; 7472 StorageClassAsWritten = SC_Register; 7473 } else if (getLangOpts().CPlusPlus && 7474 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 7475 StorageClass = SC_Auto; 7476 StorageClassAsWritten = SC_Auto; 7477 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 7478 Diag(DS.getStorageClassSpecLoc(), 7479 diag::err_invalid_storage_class_in_func_decl); 7480 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7481 } 7482 7483 if (D.getDeclSpec().isThreadSpecified()) 7484 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7485 if (D.getDeclSpec().isConstexprSpecified()) 7486 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 7487 << 0; 7488 7489 DiagnoseFunctionSpecifiers(D); 7490 7491 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7492 QualType parmDeclType = TInfo->getType(); 7493 7494 if (getLangOpts().CPlusPlus) { 7495 // Check that there are no default arguments inside the type of this 7496 // parameter. 7497 CheckExtraCXXDefaultArguments(D); 7498 7499 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 7500 if (D.getCXXScopeSpec().isSet()) { 7501 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 7502 << D.getCXXScopeSpec().getRange(); 7503 D.getCXXScopeSpec().clear(); 7504 } 7505 } 7506 7507 // Ensure we have a valid name 7508 IdentifierInfo *II = 0; 7509 if (D.hasName()) { 7510 II = D.getIdentifier(); 7511 if (!II) { 7512 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 7513 << GetNameForDeclarator(D).getName().getAsString(); 7514 D.setInvalidType(true); 7515 } 7516 } 7517 7518 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 7519 if (II) { 7520 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 7521 ForRedeclaration); 7522 LookupName(R, S); 7523 if (R.isSingleResult()) { 7524 NamedDecl *PrevDecl = R.getFoundDecl(); 7525 if (PrevDecl->isTemplateParameter()) { 7526 // Maybe we will complain about the shadowed template parameter. 7527 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7528 // Just pretend that we didn't see the previous declaration. 7529 PrevDecl = 0; 7530 } else if (S->isDeclScope(PrevDecl)) { 7531 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 7532 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 7533 7534 // Recover by removing the name 7535 II = 0; 7536 D.SetIdentifier(0, D.getIdentifierLoc()); 7537 D.setInvalidType(true); 7538 } 7539 } 7540 } 7541 7542 // Temporarily put parameter variables in the translation unit, not 7543 // the enclosing context. This prevents them from accidentally 7544 // looking like class members in C++. 7545 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 7546 D.getLocStart(), 7547 D.getIdentifierLoc(), II, 7548 parmDeclType, TInfo, 7549 StorageClass, StorageClassAsWritten); 7550 7551 if (D.isInvalidType()) 7552 New->setInvalidDecl(); 7553 7554 assert(S->isFunctionPrototypeScope()); 7555 assert(S->getFunctionPrototypeDepth() >= 1); 7556 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 7557 S->getNextFunctionPrototypeIndex()); 7558 7559 // Add the parameter declaration into this scope. 7560 S->AddDecl(New); 7561 if (II) 7562 IdResolver.AddDecl(New); 7563 7564 ProcessDeclAttributes(S, New, D); 7565 7566 if (D.getDeclSpec().isModulePrivateSpecified()) 7567 Diag(New->getLocation(), diag::err_module_private_local) 7568 << 1 << New->getDeclName() 7569 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7570 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7571 7572 if (New->hasAttr<BlocksAttr>()) { 7573 Diag(New->getLocation(), diag::err_block_on_nonlocal); 7574 } 7575 return New; 7576} 7577 7578/// \brief Synthesizes a variable for a parameter arising from a 7579/// typedef. 7580ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 7581 SourceLocation Loc, 7582 QualType T) { 7583 /* FIXME: setting StartLoc == Loc. 7584 Would it be worth to modify callers so as to provide proper source 7585 location for the unnamed parameters, embedding the parameter's type? */ 7586 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 7587 T, Context.getTrivialTypeSourceInfo(T, Loc), 7588 SC_None, SC_None, 0); 7589 Param->setImplicit(); 7590 return Param; 7591} 7592 7593void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 7594 ParmVarDecl * const *ParamEnd) { 7595 // Don't diagnose unused-parameter errors in template instantiations; we 7596 // will already have done so in the template itself. 7597 if (!ActiveTemplateInstantiations.empty()) 7598 return; 7599 7600 for (; Param != ParamEnd; ++Param) { 7601 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 7602 !(*Param)->hasAttr<UnusedAttr>()) { 7603 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 7604 << (*Param)->getDeclName(); 7605 } 7606 } 7607} 7608 7609void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 7610 ParmVarDecl * const *ParamEnd, 7611 QualType ReturnTy, 7612 NamedDecl *D) { 7613 if (LangOpts.NumLargeByValueCopy == 0) // No check. 7614 return; 7615 7616 // Warn if the return value is pass-by-value and larger than the specified 7617 // threshold. 7618 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 7619 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 7620 if (Size > LangOpts.NumLargeByValueCopy) 7621 Diag(D->getLocation(), diag::warn_return_value_size) 7622 << D->getDeclName() << Size; 7623 } 7624 7625 // Warn if any parameter is pass-by-value and larger than the specified 7626 // threshold. 7627 for (; Param != ParamEnd; ++Param) { 7628 QualType T = (*Param)->getType(); 7629 if (T->isDependentType() || !T.isPODType(Context)) 7630 continue; 7631 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 7632 if (Size > LangOpts.NumLargeByValueCopy) 7633 Diag((*Param)->getLocation(), diag::warn_parameter_size) 7634 << (*Param)->getDeclName() << Size; 7635 } 7636} 7637 7638ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 7639 SourceLocation NameLoc, IdentifierInfo *Name, 7640 QualType T, TypeSourceInfo *TSInfo, 7641 VarDecl::StorageClass StorageClass, 7642 VarDecl::StorageClass StorageClassAsWritten) { 7643 // In ARC, infer a lifetime qualifier for appropriate parameter types. 7644 if (getLangOpts().ObjCAutoRefCount && 7645 T.getObjCLifetime() == Qualifiers::OCL_None && 7646 T->isObjCLifetimeType()) { 7647 7648 Qualifiers::ObjCLifetime lifetime; 7649 7650 // Special cases for arrays: 7651 // - if it's const, use __unsafe_unretained 7652 // - otherwise, it's an error 7653 if (T->isArrayType()) { 7654 if (!T.isConstQualified()) { 7655 DelayedDiagnostics.add( 7656 sema::DelayedDiagnostic::makeForbiddenType( 7657 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 7658 } 7659 lifetime = Qualifiers::OCL_ExplicitNone; 7660 } else { 7661 lifetime = T->getObjCARCImplicitLifetime(); 7662 } 7663 T = Context.getLifetimeQualifiedType(T, lifetime); 7664 } 7665 7666 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 7667 Context.getAdjustedParameterType(T), 7668 TSInfo, 7669 StorageClass, StorageClassAsWritten, 7670 0); 7671 7672 // Parameters can not be abstract class types. 7673 // For record types, this is done by the AbstractClassUsageDiagnoser once 7674 // the class has been completely parsed. 7675 if (!CurContext->isRecord() && 7676 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 7677 AbstractParamType)) 7678 New->setInvalidDecl(); 7679 7680 // Parameter declarators cannot be interface types. All ObjC objects are 7681 // passed by reference. 7682 if (T->isObjCObjectType()) { 7683 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 7684 Diag(NameLoc, 7685 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 7686 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 7687 T = Context.getObjCObjectPointerType(T); 7688 New->setType(T); 7689 } 7690 7691 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 7692 // duration shall not be qualified by an address-space qualifier." 7693 // Since all parameters have automatic store duration, they can not have 7694 // an address space. 7695 if (T.getAddressSpace() != 0) { 7696 Diag(NameLoc, diag::err_arg_with_address_space); 7697 New->setInvalidDecl(); 7698 } 7699 7700 return New; 7701} 7702 7703void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 7704 SourceLocation LocAfterDecls) { 7705 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7706 7707 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 7708 // for a K&R function. 7709 if (!FTI.hasPrototype) { 7710 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 7711 --i; 7712 if (FTI.ArgInfo[i].Param == 0) { 7713 SmallString<256> Code; 7714 llvm::raw_svector_ostream(Code) << " int " 7715 << FTI.ArgInfo[i].Ident->getName() 7716 << ";\n"; 7717 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 7718 << FTI.ArgInfo[i].Ident 7719 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 7720 7721 // Implicitly declare the argument as type 'int' for lack of a better 7722 // type. 7723 AttributeFactory attrs; 7724 DeclSpec DS(attrs); 7725 const char* PrevSpec; // unused 7726 unsigned DiagID; // unused 7727 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 7728 PrevSpec, DiagID); 7729 // Use the identifier location for the type source range. 7730 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 7731 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 7732 Declarator ParamD(DS, Declarator::KNRTypeListContext); 7733 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 7734 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 7735 } 7736 } 7737 } 7738} 7739 7740Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 7741 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 7742 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 7743 Scope *ParentScope = FnBodyScope->getParent(); 7744 7745 D.setFunctionDefinitionKind(FDK_Definition); 7746 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 7747 return ActOnStartOfFunctionDef(FnBodyScope, DP); 7748} 7749 7750static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 7751 // Don't warn about invalid declarations. 7752 if (FD->isInvalidDecl()) 7753 return false; 7754 7755 // Or declarations that aren't global. 7756 if (!FD->isGlobal()) 7757 return false; 7758 7759 // Don't warn about C++ member functions. 7760 if (isa<CXXMethodDecl>(FD)) 7761 return false; 7762 7763 // Don't warn about 'main'. 7764 if (FD->isMain()) 7765 return false; 7766 7767 // Don't warn about inline functions. 7768 if (FD->isInlined()) 7769 return false; 7770 7771 // Don't warn about function templates. 7772 if (FD->getDescribedFunctionTemplate()) 7773 return false; 7774 7775 // Don't warn about function template specializations. 7776 if (FD->isFunctionTemplateSpecialization()) 7777 return false; 7778 7779 // Don't warn for OpenCL kernels. 7780 if (FD->hasAttr<OpenCLKernelAttr>()) 7781 return false; 7782 7783 bool MissingPrototype = true; 7784 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 7785 Prev; Prev = Prev->getPreviousDecl()) { 7786 // Ignore any declarations that occur in function or method 7787 // scope, because they aren't visible from the header. 7788 if (Prev->getDeclContext()->isFunctionOrMethod()) 7789 continue; 7790 7791 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 7792 break; 7793 } 7794 7795 return MissingPrototype; 7796} 7797 7798void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 7799 // Don't complain if we're in GNU89 mode and the previous definition 7800 // was an extern inline function. 7801 const FunctionDecl *Definition; 7802 if (FD->isDefined(Definition) && 7803 !canRedefineFunction(Definition, getLangOpts())) { 7804 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 7805 Definition->getStorageClass() == SC_Extern) 7806 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 7807 << FD->getDeclName() << getLangOpts().CPlusPlus; 7808 else 7809 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 7810 Diag(Definition->getLocation(), diag::note_previous_definition); 7811 FD->setInvalidDecl(); 7812 } 7813} 7814 7815Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 7816 // Clear the last template instantiation error context. 7817 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 7818 7819 if (!D) 7820 return D; 7821 FunctionDecl *FD = 0; 7822 7823 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 7824 FD = FunTmpl->getTemplatedDecl(); 7825 else 7826 FD = cast<FunctionDecl>(D); 7827 7828 // Enter a new function scope 7829 PushFunctionScope(); 7830 7831 // See if this is a redefinition. 7832 if (!FD->isLateTemplateParsed()) 7833 CheckForFunctionRedefinition(FD); 7834 7835 // Builtin functions cannot be defined. 7836 if (unsigned BuiltinID = FD->getBuiltinID()) { 7837 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 7838 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 7839 FD->setInvalidDecl(); 7840 } 7841 } 7842 7843 // The return type of a function definition must be complete 7844 // (C99 6.9.1p3, C++ [dcl.fct]p6). 7845 QualType ResultType = FD->getResultType(); 7846 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 7847 !FD->isInvalidDecl() && 7848 RequireCompleteType(FD->getLocation(), ResultType, 7849 diag::err_func_def_incomplete_result)) 7850 FD->setInvalidDecl(); 7851 7852 // GNU warning -Wmissing-prototypes: 7853 // Warn if a global function is defined without a previous 7854 // prototype declaration. This warning is issued even if the 7855 // definition itself provides a prototype. The aim is to detect 7856 // global functions that fail to be declared in header files. 7857 if (ShouldWarnAboutMissingPrototype(FD)) 7858 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 7859 7860 if (FnBodyScope) 7861 PushDeclContext(FnBodyScope, FD); 7862 7863 // Check the validity of our function parameters 7864 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 7865 /*CheckParameterNames=*/true); 7866 7867 // Introduce our parameters into the function scope 7868 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 7869 ParmVarDecl *Param = FD->getParamDecl(p); 7870 Param->setOwningFunction(FD); 7871 7872 // If this has an identifier, add it to the scope stack. 7873 if (Param->getIdentifier() && FnBodyScope) { 7874 CheckShadow(FnBodyScope, Param); 7875 7876 PushOnScopeChains(Param, FnBodyScope); 7877 } 7878 } 7879 7880 // If we had any tags defined in the function prototype, 7881 // introduce them into the function scope. 7882 if (FnBodyScope) { 7883 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 7884 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 7885 NamedDecl *D = *I; 7886 7887 // Some of these decls (like enums) may have been pinned to the translation unit 7888 // for lack of a real context earlier. If so, remove from the translation unit 7889 // and reattach to the current context. 7890 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 7891 // Is the decl actually in the context? 7892 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 7893 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 7894 if (*DI == D) { 7895 Context.getTranslationUnitDecl()->removeDecl(D); 7896 break; 7897 } 7898 } 7899 // Either way, reassign the lexical decl context to our FunctionDecl. 7900 D->setLexicalDeclContext(CurContext); 7901 } 7902 7903 // If the decl has a non-null name, make accessible in the current scope. 7904 if (!D->getName().empty()) 7905 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 7906 7907 // Similarly, dive into enums and fish their constants out, making them 7908 // accessible in this scope. 7909 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 7910 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 7911 EE = ED->enumerator_end(); EI != EE; ++EI) 7912 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 7913 } 7914 } 7915 } 7916 7917 // Ensure that the function's exception specification is instantiated. 7918 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 7919 ResolveExceptionSpec(D->getLocation(), FPT); 7920 7921 // Checking attributes of current function definition 7922 // dllimport attribute. 7923 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 7924 if (DA && (!FD->getAttr<DLLExportAttr>())) { 7925 // dllimport attribute cannot be directly applied to definition. 7926 // Microsoft accepts dllimport for functions defined within class scope. 7927 if (!DA->isInherited() && 7928 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 7929 Diag(FD->getLocation(), 7930 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 7931 << "dllimport"; 7932 FD->setInvalidDecl(); 7933 return FD; 7934 } 7935 7936 // Visual C++ appears to not think this is an issue, so only issue 7937 // a warning when Microsoft extensions are disabled. 7938 if (!LangOpts.MicrosoftExt) { 7939 // If a symbol previously declared dllimport is later defined, the 7940 // attribute is ignored in subsequent references, and a warning is 7941 // emitted. 7942 Diag(FD->getLocation(), 7943 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7944 << FD->getName() << "dllimport"; 7945 } 7946 } 7947 // We want to attach documentation to original Decl (which might be 7948 // a function template). 7949 ActOnDocumentableDecl(D); 7950 return FD; 7951} 7952 7953/// \brief Given the set of return statements within a function body, 7954/// compute the variables that are subject to the named return value 7955/// optimization. 7956/// 7957/// Each of the variables that is subject to the named return value 7958/// optimization will be marked as NRVO variables in the AST, and any 7959/// return statement that has a marked NRVO variable as its NRVO candidate can 7960/// use the named return value optimization. 7961/// 7962/// This function applies a very simplistic algorithm for NRVO: if every return 7963/// statement in the function has the same NRVO candidate, that candidate is 7964/// the NRVO variable. 7965/// 7966/// FIXME: Employ a smarter algorithm that accounts for multiple return 7967/// statements and the lifetimes of the NRVO candidates. We should be able to 7968/// find a maximal set of NRVO variables. 7969void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 7970 ReturnStmt **Returns = Scope->Returns.data(); 7971 7972 const VarDecl *NRVOCandidate = 0; 7973 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 7974 if (!Returns[I]->getNRVOCandidate()) 7975 return; 7976 7977 if (!NRVOCandidate) 7978 NRVOCandidate = Returns[I]->getNRVOCandidate(); 7979 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 7980 return; 7981 } 7982 7983 if (NRVOCandidate) 7984 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 7985} 7986 7987bool Sema::canSkipFunctionBody(Decl *D) { 7988 if (isa<ObjCMethodDecl>(D)) 7989 return true; 7990 7991 FunctionDecl *FD = 0; 7992 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 7993 FD = FTD->getTemplatedDecl(); 7994 else 7995 FD = cast<FunctionDecl>(D); 7996 7997 // We cannot skip the body of a function (or function template) which is 7998 // constexpr, since we may need to evaluate its body in order to parse the 7999 // rest of the file. 8000 return !FD->isConstexpr(); 8001} 8002 8003Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 8004 return ActOnFinishFunctionBody(D, BodyArg, false); 8005} 8006 8007Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 8008 bool IsInstantiation) { 8009 FunctionDecl *FD = 0; 8010 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 8011 if (FunTmpl) 8012 FD = FunTmpl->getTemplatedDecl(); 8013 else 8014 FD = dyn_cast_or_null<FunctionDecl>(dcl); 8015 8016 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 8017 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 8018 8019 if (FD) { 8020 FD->setBody(Body); 8021 8022 // If the function implicitly returns zero (like 'main') or is naked, 8023 // don't complain about missing return statements. 8024 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 8025 WP.disableCheckFallThrough(); 8026 8027 // MSVC permits the use of pure specifier (=0) on function definition, 8028 // defined at class scope, warn about this non standard construct. 8029 if (getLangOpts().MicrosoftExt && FD->isPure()) 8030 Diag(FD->getLocation(), diag::warn_pure_function_definition); 8031 8032 if (!FD->isInvalidDecl()) { 8033 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 8034 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 8035 FD->getResultType(), FD); 8036 8037 // If this is a constructor, we need a vtable. 8038 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 8039 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 8040 8041 // Try to apply the named return value optimization. We have to check 8042 // if we can do this here because lambdas keep return statements around 8043 // to deduce an implicit return type. 8044 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 8045 !FD->isDependentContext()) 8046 computeNRVO(Body, getCurFunction()); 8047 } 8048 8049 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 8050 "Function parsing confused"); 8051 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 8052 assert(MD == getCurMethodDecl() && "Method parsing confused"); 8053 MD->setBody(Body); 8054 if (!MD->isInvalidDecl()) { 8055 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 8056 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 8057 MD->getResultType(), MD); 8058 8059 if (Body) 8060 computeNRVO(Body, getCurFunction()); 8061 } 8062 if (getCurFunction()->ObjCShouldCallSuper) { 8063 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 8064 << MD->getSelector().getAsString(); 8065 getCurFunction()->ObjCShouldCallSuper = false; 8066 } 8067 } else { 8068 return 0; 8069 } 8070 8071 assert(!getCurFunction()->ObjCShouldCallSuper && 8072 "This should only be set for ObjC methods, which should have been " 8073 "handled in the block above."); 8074 8075 // Verify and clean out per-function state. 8076 if (Body) { 8077 // C++ constructors that have function-try-blocks can't have return 8078 // statements in the handlers of that block. (C++ [except.handle]p14) 8079 // Verify this. 8080 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 8081 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 8082 8083 // Verify that gotos and switch cases don't jump into scopes illegally. 8084 if (getCurFunction()->NeedsScopeChecking() && 8085 !dcl->isInvalidDecl() && 8086 !hasAnyUnrecoverableErrorsInThisFunction() && 8087 !PP.isCodeCompletionEnabled()) 8088 DiagnoseInvalidJumps(Body); 8089 8090 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 8091 if (!Destructor->getParent()->isDependentType()) 8092 CheckDestructor(Destructor); 8093 8094 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8095 Destructor->getParent()); 8096 } 8097 8098 // If any errors have occurred, clear out any temporaries that may have 8099 // been leftover. This ensures that these temporaries won't be picked up for 8100 // deletion in some later function. 8101 if (PP.getDiagnostics().hasErrorOccurred() || 8102 PP.getDiagnostics().getSuppressAllDiagnostics()) { 8103 DiscardCleanupsInEvaluationContext(); 8104 } else if (!isa<FunctionTemplateDecl>(dcl)) { 8105 // Since the body is valid, issue any analysis-based warnings that are 8106 // enabled. 8107 ActivePolicy = &WP; 8108 } 8109 8110 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 8111 (!CheckConstexprFunctionDecl(FD) || 8112 !CheckConstexprFunctionBody(FD, Body))) 8113 FD->setInvalidDecl(); 8114 8115 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 8116 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 8117 assert(MaybeODRUseExprs.empty() && 8118 "Leftover expressions for odr-use checking"); 8119 } 8120 8121 if (!IsInstantiation) 8122 PopDeclContext(); 8123 8124 PopFunctionScopeInfo(ActivePolicy, dcl); 8125 8126 // If any errors have occurred, clear out any temporaries that may have 8127 // been leftover. This ensures that these temporaries won't be picked up for 8128 // deletion in some later function. 8129 if (getDiagnostics().hasErrorOccurred()) { 8130 DiscardCleanupsInEvaluationContext(); 8131 } 8132 8133 return dcl; 8134} 8135 8136 8137/// When we finish delayed parsing of an attribute, we must attach it to the 8138/// relevant Decl. 8139void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 8140 ParsedAttributes &Attrs) { 8141 // Always attach attributes to the underlying decl. 8142 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8143 D = TD->getTemplatedDecl(); 8144 ProcessDeclAttributeList(S, D, Attrs.getList()); 8145 8146 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 8147 if (Method->isStatic()) 8148 checkThisInStaticMemberFunctionAttributes(Method); 8149} 8150 8151 8152/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 8153/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 8154NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 8155 IdentifierInfo &II, Scope *S) { 8156 // Before we produce a declaration for an implicitly defined 8157 // function, see whether there was a locally-scoped declaration of 8158 // this name as a function or variable. If so, use that 8159 // (non-visible) declaration, and complain about it. 8160 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 8161 = findLocallyScopedExternalDecl(&II); 8162 if (Pos != LocallyScopedExternalDecls.end()) { 8163 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 8164 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 8165 return Pos->second; 8166 } 8167 8168 // Extension in C99. Legal in C90, but warn about it. 8169 unsigned diag_id; 8170 if (II.getName().startswith("__builtin_")) 8171 diag_id = diag::warn_builtin_unknown; 8172 else if (getLangOpts().C99) 8173 diag_id = diag::ext_implicit_function_decl; 8174 else 8175 diag_id = diag::warn_implicit_function_decl; 8176 Diag(Loc, diag_id) << &II; 8177 8178 // Because typo correction is expensive, only do it if the implicit 8179 // function declaration is going to be treated as an error. 8180 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 8181 TypoCorrection Corrected; 8182 DeclFilterCCC<FunctionDecl> Validator; 8183 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 8184 LookupOrdinaryName, S, 0, Validator))) { 8185 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 8186 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 8187 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 8188 8189 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 8190 << FixItHint::CreateReplacement(Loc, CorrectedStr); 8191 8192 if (Func->getLocation().isValid() 8193 && !II.getName().startswith("__builtin_")) 8194 Diag(Func->getLocation(), diag::note_previous_decl) 8195 << CorrectedQuotedStr; 8196 } 8197 } 8198 8199 // Set a Declarator for the implicit definition: int foo(); 8200 const char *Dummy; 8201 AttributeFactory attrFactory; 8202 DeclSpec DS(attrFactory); 8203 unsigned DiagID; 8204 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 8205 (void)Error; // Silence warning. 8206 assert(!Error && "Error setting up implicit decl!"); 8207 SourceLocation NoLoc; 8208 Declarator D(DS, Declarator::BlockContext); 8209 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 8210 /*IsAmbiguous=*/false, 8211 /*RParenLoc=*/NoLoc, 8212 /*ArgInfo=*/0, 8213 /*NumArgs=*/0, 8214 /*EllipsisLoc=*/NoLoc, 8215 /*RParenLoc=*/NoLoc, 8216 /*TypeQuals=*/0, 8217 /*RefQualifierIsLvalueRef=*/true, 8218 /*RefQualifierLoc=*/NoLoc, 8219 /*ConstQualifierLoc=*/NoLoc, 8220 /*VolatileQualifierLoc=*/NoLoc, 8221 /*MutableLoc=*/NoLoc, 8222 EST_None, 8223 /*ESpecLoc=*/NoLoc, 8224 /*Exceptions=*/0, 8225 /*ExceptionRanges=*/0, 8226 /*NumExceptions=*/0, 8227 /*NoexceptExpr=*/0, 8228 Loc, Loc, D), 8229 DS.getAttributes(), 8230 SourceLocation()); 8231 D.SetIdentifier(&II, Loc); 8232 8233 // Insert this function into translation-unit scope. 8234 8235 DeclContext *PrevDC = CurContext; 8236 CurContext = Context.getTranslationUnitDecl(); 8237 8238 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 8239 FD->setImplicit(); 8240 8241 CurContext = PrevDC; 8242 8243 AddKnownFunctionAttributes(FD); 8244 8245 return FD; 8246} 8247 8248/// \brief Adds any function attributes that we know a priori based on 8249/// the declaration of this function. 8250/// 8251/// These attributes can apply both to implicitly-declared builtins 8252/// (like __builtin___printf_chk) or to library-declared functions 8253/// like NSLog or printf. 8254/// 8255/// We need to check for duplicate attributes both here and where user-written 8256/// attributes are applied to declarations. 8257void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 8258 if (FD->isInvalidDecl()) 8259 return; 8260 8261 // If this is a built-in function, map its builtin attributes to 8262 // actual attributes. 8263 if (unsigned BuiltinID = FD->getBuiltinID()) { 8264 // Handle printf-formatting attributes. 8265 unsigned FormatIdx; 8266 bool HasVAListArg; 8267 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 8268 if (!FD->getAttr<FormatAttr>()) { 8269 const char *fmt = "printf"; 8270 unsigned int NumParams = FD->getNumParams(); 8271 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 8272 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 8273 fmt = "NSString"; 8274 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8275 fmt, FormatIdx+1, 8276 HasVAListArg ? 0 : FormatIdx+2)); 8277 } 8278 } 8279 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 8280 HasVAListArg)) { 8281 if (!FD->getAttr<FormatAttr>()) 8282 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8283 "scanf", FormatIdx+1, 8284 HasVAListArg ? 0 : FormatIdx+2)); 8285 } 8286 8287 // Mark const if we don't care about errno and that is the only 8288 // thing preventing the function from being const. This allows 8289 // IRgen to use LLVM intrinsics for such functions. 8290 if (!getLangOpts().MathErrno && 8291 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 8292 if (!FD->getAttr<ConstAttr>()) 8293 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8294 } 8295 8296 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 8297 !FD->getAttr<ReturnsTwiceAttr>()) 8298 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 8299 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 8300 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 8301 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 8302 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8303 } 8304 8305 IdentifierInfo *Name = FD->getIdentifier(); 8306 if (!Name) 8307 return; 8308 if ((!getLangOpts().CPlusPlus && 8309 FD->getDeclContext()->isTranslationUnit()) || 8310 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 8311 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 8312 LinkageSpecDecl::lang_c)) { 8313 // Okay: this could be a libc/libm/Objective-C function we know 8314 // about. 8315 } else 8316 return; 8317 8318 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 8319 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 8320 // target-specific builtins, perhaps? 8321 if (!FD->getAttr<FormatAttr>()) 8322 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8323 "printf", 2, 8324 Name->isStr("vasprintf") ? 0 : 3)); 8325 } 8326 8327 if (Name->isStr("__CFStringMakeConstantString")) { 8328 // We already have a __builtin___CFStringMakeConstantString, 8329 // but builds that use -fno-constant-cfstrings don't go through that. 8330 if (!FD->getAttr<FormatArgAttr>()) 8331 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 8332 } 8333} 8334 8335TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 8336 TypeSourceInfo *TInfo) { 8337 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 8338 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 8339 8340 if (!TInfo) { 8341 assert(D.isInvalidType() && "no declarator info for valid type"); 8342 TInfo = Context.getTrivialTypeSourceInfo(T); 8343 } 8344 8345 // Scope manipulation handled by caller. 8346 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 8347 D.getLocStart(), 8348 D.getIdentifierLoc(), 8349 D.getIdentifier(), 8350 TInfo); 8351 8352 // Bail out immediately if we have an invalid declaration. 8353 if (D.isInvalidType()) { 8354 NewTD->setInvalidDecl(); 8355 return NewTD; 8356 } 8357 8358 if (D.getDeclSpec().isModulePrivateSpecified()) { 8359 if (CurContext->isFunctionOrMethod()) 8360 Diag(NewTD->getLocation(), diag::err_module_private_local) 8361 << 2 << NewTD->getDeclName() 8362 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8363 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8364 else 8365 NewTD->setModulePrivate(); 8366 } 8367 8368 // C++ [dcl.typedef]p8: 8369 // If the typedef declaration defines an unnamed class (or 8370 // enum), the first typedef-name declared by the declaration 8371 // to be that class type (or enum type) is used to denote the 8372 // class type (or enum type) for linkage purposes only. 8373 // We need to check whether the type was declared in the declaration. 8374 switch (D.getDeclSpec().getTypeSpecType()) { 8375 case TST_enum: 8376 case TST_struct: 8377 case TST_interface: 8378 case TST_union: 8379 case TST_class: { 8380 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 8381 8382 // Do nothing if the tag is not anonymous or already has an 8383 // associated typedef (from an earlier typedef in this decl group). 8384 if (tagFromDeclSpec->getIdentifier()) break; 8385 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 8386 8387 // A well-formed anonymous tag must always be a TUK_Definition. 8388 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 8389 8390 // The type must match the tag exactly; no qualifiers allowed. 8391 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 8392 break; 8393 8394 // Otherwise, set this is the anon-decl typedef for the tag. 8395 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 8396 break; 8397 } 8398 8399 default: 8400 break; 8401 } 8402 8403 return NewTD; 8404} 8405 8406 8407/// \brief Check that this is a valid underlying type for an enum declaration. 8408bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 8409 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 8410 QualType T = TI->getType(); 8411 8412 if (T->isDependentType() || T->isIntegralType(Context)) 8413 return false; 8414 8415 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 8416 return true; 8417} 8418 8419/// Check whether this is a valid redeclaration of a previous enumeration. 8420/// \return true if the redeclaration was invalid. 8421bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 8422 QualType EnumUnderlyingTy, 8423 const EnumDecl *Prev) { 8424 bool IsFixed = !EnumUnderlyingTy.isNull(); 8425 8426 if (IsScoped != Prev->isScoped()) { 8427 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 8428 << Prev->isScoped(); 8429 Diag(Prev->getLocation(), diag::note_previous_use); 8430 return true; 8431 } 8432 8433 if (IsFixed && Prev->isFixed()) { 8434 if (!EnumUnderlyingTy->isDependentType() && 8435 !Prev->getIntegerType()->isDependentType() && 8436 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 8437 Prev->getIntegerType())) { 8438 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 8439 << EnumUnderlyingTy << Prev->getIntegerType(); 8440 Diag(Prev->getLocation(), diag::note_previous_use); 8441 return true; 8442 } 8443 } else if (IsFixed != Prev->isFixed()) { 8444 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 8445 << Prev->isFixed(); 8446 Diag(Prev->getLocation(), diag::note_previous_use); 8447 return true; 8448 } 8449 8450 return false; 8451} 8452 8453/// \brief Get diagnostic %select index for tag kind for 8454/// redeclaration diagnostic message. 8455/// WARNING: Indexes apply to particular diagnostics only! 8456/// 8457/// \returns diagnostic %select index. 8458static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 8459 switch (Tag) { 8460 case TTK_Struct: return 0; 8461 case TTK_Interface: return 1; 8462 case TTK_Class: return 2; 8463 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 8464 } 8465} 8466 8467/// \brief Determine if tag kind is a class-key compatible with 8468/// class for redeclaration (class, struct, or __interface). 8469/// 8470/// \returns true iff the tag kind is compatible. 8471static bool isClassCompatTagKind(TagTypeKind Tag) 8472{ 8473 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 8474} 8475 8476/// \brief Determine whether a tag with a given kind is acceptable 8477/// as a redeclaration of the given tag declaration. 8478/// 8479/// \returns true if the new tag kind is acceptable, false otherwise. 8480bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 8481 TagTypeKind NewTag, bool isDefinition, 8482 SourceLocation NewTagLoc, 8483 const IdentifierInfo &Name) { 8484 // C++ [dcl.type.elab]p3: 8485 // The class-key or enum keyword present in the 8486 // elaborated-type-specifier shall agree in kind with the 8487 // declaration to which the name in the elaborated-type-specifier 8488 // refers. This rule also applies to the form of 8489 // elaborated-type-specifier that declares a class-name or 8490 // friend class since it can be construed as referring to the 8491 // definition of the class. Thus, in any 8492 // elaborated-type-specifier, the enum keyword shall be used to 8493 // refer to an enumeration (7.2), the union class-key shall be 8494 // used to refer to a union (clause 9), and either the class or 8495 // struct class-key shall be used to refer to a class (clause 9) 8496 // declared using the class or struct class-key. 8497 TagTypeKind OldTag = Previous->getTagKind(); 8498 if (!isDefinition || !isClassCompatTagKind(NewTag)) 8499 if (OldTag == NewTag) 8500 return true; 8501 8502 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 8503 // Warn about the struct/class tag mismatch. 8504 bool isTemplate = false; 8505 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 8506 isTemplate = Record->getDescribedClassTemplate(); 8507 8508 if (!ActiveTemplateInstantiations.empty()) { 8509 // In a template instantiation, do not offer fix-its for tag mismatches 8510 // since they usually mess up the template instead of fixing the problem. 8511 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8512 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8513 << getRedeclDiagFromTagKind(OldTag); 8514 return true; 8515 } 8516 8517 if (isDefinition) { 8518 // On definitions, check previous tags and issue a fix-it for each 8519 // one that doesn't match the current tag. 8520 if (Previous->getDefinition()) { 8521 // Don't suggest fix-its for redefinitions. 8522 return true; 8523 } 8524 8525 bool previousMismatch = false; 8526 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 8527 E(Previous->redecls_end()); I != E; ++I) { 8528 if (I->getTagKind() != NewTag) { 8529 if (!previousMismatch) { 8530 previousMismatch = true; 8531 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 8532 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8533 << getRedeclDiagFromTagKind(I->getTagKind()); 8534 } 8535 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 8536 << getRedeclDiagFromTagKind(NewTag) 8537 << FixItHint::CreateReplacement(I->getInnerLocStart(), 8538 TypeWithKeyword::getTagTypeKindName(NewTag)); 8539 } 8540 } 8541 return true; 8542 } 8543 8544 // Check for a previous definition. If current tag and definition 8545 // are same type, do nothing. If no definition, but disagree with 8546 // with previous tag type, give a warning, but no fix-it. 8547 const TagDecl *Redecl = Previous->getDefinition() ? 8548 Previous->getDefinition() : Previous; 8549 if (Redecl->getTagKind() == NewTag) { 8550 return true; 8551 } 8552 8553 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8554 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8555 << getRedeclDiagFromTagKind(OldTag); 8556 Diag(Redecl->getLocation(), diag::note_previous_use); 8557 8558 // If there is a previous defintion, suggest a fix-it. 8559 if (Previous->getDefinition()) { 8560 Diag(NewTagLoc, diag::note_struct_class_suggestion) 8561 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 8562 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 8563 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 8564 } 8565 8566 return true; 8567 } 8568 return false; 8569} 8570 8571/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 8572/// former case, Name will be non-null. In the later case, Name will be null. 8573/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 8574/// reference/declaration/definition of a tag. 8575Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 8576 SourceLocation KWLoc, CXXScopeSpec &SS, 8577 IdentifierInfo *Name, SourceLocation NameLoc, 8578 AttributeList *Attr, AccessSpecifier AS, 8579 SourceLocation ModulePrivateLoc, 8580 MultiTemplateParamsArg TemplateParameterLists, 8581 bool &OwnedDecl, bool &IsDependent, 8582 SourceLocation ScopedEnumKWLoc, 8583 bool ScopedEnumUsesClassTag, 8584 TypeResult UnderlyingType) { 8585 // If this is not a definition, it must have a name. 8586 IdentifierInfo *OrigName = Name; 8587 assert((Name != 0 || TUK == TUK_Definition) && 8588 "Nameless record must be a definition!"); 8589 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 8590 8591 OwnedDecl = false; 8592 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8593 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 8594 8595 // FIXME: Check explicit specializations more carefully. 8596 bool isExplicitSpecialization = false; 8597 bool Invalid = false; 8598 8599 // We only need to do this matching if we have template parameters 8600 // or a scope specifier, which also conveniently avoids this work 8601 // for non-C++ cases. 8602 if (TemplateParameterLists.size() > 0 || 8603 (SS.isNotEmpty() && TUK != TUK_Reference)) { 8604 if (TemplateParameterList *TemplateParams 8605 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 8606 TemplateParameterLists.data(), 8607 TemplateParameterLists.size(), 8608 TUK == TUK_Friend, 8609 isExplicitSpecialization, 8610 Invalid)) { 8611 if (TemplateParams->size() > 0) { 8612 // This is a declaration or definition of a class template (which may 8613 // be a member of another template). 8614 8615 if (Invalid) 8616 return 0; 8617 8618 OwnedDecl = false; 8619 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 8620 SS, Name, NameLoc, Attr, 8621 TemplateParams, AS, 8622 ModulePrivateLoc, 8623 TemplateParameterLists.size()-1, 8624 TemplateParameterLists.data()); 8625 return Result.get(); 8626 } else { 8627 // The "template<>" header is extraneous. 8628 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 8629 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 8630 isExplicitSpecialization = true; 8631 } 8632 } 8633 } 8634 8635 // Figure out the underlying type if this a enum declaration. We need to do 8636 // this early, because it's needed to detect if this is an incompatible 8637 // redeclaration. 8638 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 8639 8640 if (Kind == TTK_Enum) { 8641 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 8642 // No underlying type explicitly specified, or we failed to parse the 8643 // type, default to int. 8644 EnumUnderlying = Context.IntTy.getTypePtr(); 8645 else if (UnderlyingType.get()) { 8646 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 8647 // integral type; any cv-qualification is ignored. 8648 TypeSourceInfo *TI = 0; 8649 GetTypeFromParser(UnderlyingType.get(), &TI); 8650 EnumUnderlying = TI; 8651 8652 if (CheckEnumUnderlyingType(TI)) 8653 // Recover by falling back to int. 8654 EnumUnderlying = Context.IntTy.getTypePtr(); 8655 8656 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 8657 UPPC_FixedUnderlyingType)) 8658 EnumUnderlying = Context.IntTy.getTypePtr(); 8659 8660 } else if (getLangOpts().MicrosoftMode) 8661 // Microsoft enums are always of int type. 8662 EnumUnderlying = Context.IntTy.getTypePtr(); 8663 } 8664 8665 DeclContext *SearchDC = CurContext; 8666 DeclContext *DC = CurContext; 8667 bool isStdBadAlloc = false; 8668 8669 RedeclarationKind Redecl = ForRedeclaration; 8670 if (TUK == TUK_Friend || TUK == TUK_Reference) 8671 Redecl = NotForRedeclaration; 8672 8673 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 8674 8675 if (Name && SS.isNotEmpty()) { 8676 // We have a nested-name tag ('struct foo::bar'). 8677 8678 // Check for invalid 'foo::'. 8679 if (SS.isInvalid()) { 8680 Name = 0; 8681 goto CreateNewDecl; 8682 } 8683 8684 // If this is a friend or a reference to a class in a dependent 8685 // context, don't try to make a decl for it. 8686 if (TUK == TUK_Friend || TUK == TUK_Reference) { 8687 DC = computeDeclContext(SS, false); 8688 if (!DC) { 8689 IsDependent = true; 8690 return 0; 8691 } 8692 } else { 8693 DC = computeDeclContext(SS, true); 8694 if (!DC) { 8695 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 8696 << SS.getRange(); 8697 return 0; 8698 } 8699 } 8700 8701 if (RequireCompleteDeclContext(SS, DC)) 8702 return 0; 8703 8704 SearchDC = DC; 8705 // Look-up name inside 'foo::'. 8706 LookupQualifiedName(Previous, DC); 8707 8708 if (Previous.isAmbiguous()) 8709 return 0; 8710 8711 if (Previous.empty()) { 8712 // Name lookup did not find anything. However, if the 8713 // nested-name-specifier refers to the current instantiation, 8714 // and that current instantiation has any dependent base 8715 // classes, we might find something at instantiation time: treat 8716 // this as a dependent elaborated-type-specifier. 8717 // But this only makes any sense for reference-like lookups. 8718 if (Previous.wasNotFoundInCurrentInstantiation() && 8719 (TUK == TUK_Reference || TUK == TUK_Friend)) { 8720 IsDependent = true; 8721 return 0; 8722 } 8723 8724 // A tag 'foo::bar' must already exist. 8725 Diag(NameLoc, diag::err_not_tag_in_scope) 8726 << Kind << Name << DC << SS.getRange(); 8727 Name = 0; 8728 Invalid = true; 8729 goto CreateNewDecl; 8730 } 8731 } else if (Name) { 8732 // If this is a named struct, check to see if there was a previous forward 8733 // declaration or definition. 8734 // FIXME: We're looking into outer scopes here, even when we 8735 // shouldn't be. Doing so can result in ambiguities that we 8736 // shouldn't be diagnosing. 8737 LookupName(Previous, S); 8738 8739 if (Previous.isAmbiguous() && 8740 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 8741 LookupResult::Filter F = Previous.makeFilter(); 8742 while (F.hasNext()) { 8743 NamedDecl *ND = F.next(); 8744 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 8745 F.erase(); 8746 } 8747 F.done(); 8748 } 8749 8750 // Note: there used to be some attempt at recovery here. 8751 if (Previous.isAmbiguous()) 8752 return 0; 8753 8754 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 8755 // FIXME: This makes sure that we ignore the contexts associated 8756 // with C structs, unions, and enums when looking for a matching 8757 // tag declaration or definition. See the similar lookup tweak 8758 // in Sema::LookupName; is there a better way to deal with this? 8759 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 8760 SearchDC = SearchDC->getParent(); 8761 } 8762 } else if (S->isFunctionPrototypeScope()) { 8763 // If this is an enum declaration in function prototype scope, set its 8764 // initial context to the translation unit. 8765 // FIXME: [citation needed] 8766 SearchDC = Context.getTranslationUnitDecl(); 8767 } 8768 8769 if (Previous.isSingleResult() && 8770 Previous.getFoundDecl()->isTemplateParameter()) { 8771 // Maybe we will complain about the shadowed template parameter. 8772 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 8773 // Just pretend that we didn't see the previous declaration. 8774 Previous.clear(); 8775 } 8776 8777 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 8778 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 8779 // This is a declaration of or a reference to "std::bad_alloc". 8780 isStdBadAlloc = true; 8781 8782 if (Previous.empty() && StdBadAlloc) { 8783 // std::bad_alloc has been implicitly declared (but made invisible to 8784 // name lookup). Fill in this implicit declaration as the previous 8785 // declaration, so that the declarations get chained appropriately. 8786 Previous.addDecl(getStdBadAlloc()); 8787 } 8788 } 8789 8790 // If we didn't find a previous declaration, and this is a reference 8791 // (or friend reference), move to the correct scope. In C++, we 8792 // also need to do a redeclaration lookup there, just in case 8793 // there's a shadow friend decl. 8794 if (Name && Previous.empty() && 8795 (TUK == TUK_Reference || TUK == TUK_Friend)) { 8796 if (Invalid) goto CreateNewDecl; 8797 assert(SS.isEmpty()); 8798 8799 if (TUK == TUK_Reference) { 8800 // C++ [basic.scope.pdecl]p5: 8801 // -- for an elaborated-type-specifier of the form 8802 // 8803 // class-key identifier 8804 // 8805 // if the elaborated-type-specifier is used in the 8806 // decl-specifier-seq or parameter-declaration-clause of a 8807 // function defined in namespace scope, the identifier is 8808 // declared as a class-name in the namespace that contains 8809 // the declaration; otherwise, except as a friend 8810 // declaration, the identifier is declared in the smallest 8811 // non-class, non-function-prototype scope that contains the 8812 // declaration. 8813 // 8814 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 8815 // C structs and unions. 8816 // 8817 // It is an error in C++ to declare (rather than define) an enum 8818 // type, including via an elaborated type specifier. We'll 8819 // diagnose that later; for now, declare the enum in the same 8820 // scope as we would have picked for any other tag type. 8821 // 8822 // GNU C also supports this behavior as part of its incomplete 8823 // enum types extension, while GNU C++ does not. 8824 // 8825 // Find the context where we'll be declaring the tag. 8826 // FIXME: We would like to maintain the current DeclContext as the 8827 // lexical context, 8828 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 8829 SearchDC = SearchDC->getParent(); 8830 8831 // Find the scope where we'll be declaring the tag. 8832 while (S->isClassScope() || 8833 (getLangOpts().CPlusPlus && 8834 S->isFunctionPrototypeScope()) || 8835 ((S->getFlags() & Scope::DeclScope) == 0) || 8836 (S->getEntity() && 8837 ((DeclContext *)S->getEntity())->isTransparentContext())) 8838 S = S->getParent(); 8839 } else { 8840 assert(TUK == TUK_Friend); 8841 // C++ [namespace.memdef]p3: 8842 // If a friend declaration in a non-local class first declares a 8843 // class or function, the friend class or function is a member of 8844 // the innermost enclosing namespace. 8845 SearchDC = SearchDC->getEnclosingNamespaceContext(); 8846 } 8847 8848 // In C++, we need to do a redeclaration lookup to properly 8849 // diagnose some problems. 8850 if (getLangOpts().CPlusPlus) { 8851 Previous.setRedeclarationKind(ForRedeclaration); 8852 LookupQualifiedName(Previous, SearchDC); 8853 } 8854 } 8855 8856 if (!Previous.empty()) { 8857 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 8858 8859 // It's okay to have a tag decl in the same scope as a typedef 8860 // which hides a tag decl in the same scope. Finding this 8861 // insanity with a redeclaration lookup can only actually happen 8862 // in C++. 8863 // 8864 // This is also okay for elaborated-type-specifiers, which is 8865 // technically forbidden by the current standard but which is 8866 // okay according to the likely resolution of an open issue; 8867 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 8868 if (getLangOpts().CPlusPlus) { 8869 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 8870 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 8871 TagDecl *Tag = TT->getDecl(); 8872 if (Tag->getDeclName() == Name && 8873 Tag->getDeclContext()->getRedeclContext() 8874 ->Equals(TD->getDeclContext()->getRedeclContext())) { 8875 PrevDecl = Tag; 8876 Previous.clear(); 8877 Previous.addDecl(Tag); 8878 Previous.resolveKind(); 8879 } 8880 } 8881 } 8882 } 8883 8884 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 8885 // If this is a use of a previous tag, or if the tag is already declared 8886 // in the same scope (so that the definition/declaration completes or 8887 // rementions the tag), reuse the decl. 8888 if (TUK == TUK_Reference || TUK == TUK_Friend || 8889 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 8890 // Make sure that this wasn't declared as an enum and now used as a 8891 // struct or something similar. 8892 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 8893 TUK == TUK_Definition, KWLoc, 8894 *Name)) { 8895 bool SafeToContinue 8896 = (PrevTagDecl->getTagKind() != TTK_Enum && 8897 Kind != TTK_Enum); 8898 if (SafeToContinue) 8899 Diag(KWLoc, diag::err_use_with_wrong_tag) 8900 << Name 8901 << FixItHint::CreateReplacement(SourceRange(KWLoc), 8902 PrevTagDecl->getKindName()); 8903 else 8904 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 8905 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 8906 8907 if (SafeToContinue) 8908 Kind = PrevTagDecl->getTagKind(); 8909 else { 8910 // Recover by making this an anonymous redefinition. 8911 Name = 0; 8912 Previous.clear(); 8913 Invalid = true; 8914 } 8915 } 8916 8917 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 8918 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 8919 8920 // If this is an elaborated-type-specifier for a scoped enumeration, 8921 // the 'class' keyword is not necessary and not permitted. 8922 if (TUK == TUK_Reference || TUK == TUK_Friend) { 8923 if (ScopedEnum) 8924 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 8925 << PrevEnum->isScoped() 8926 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 8927 return PrevTagDecl; 8928 } 8929 8930 QualType EnumUnderlyingTy; 8931 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 8932 EnumUnderlyingTy = TI->getType(); 8933 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 8934 EnumUnderlyingTy = QualType(T, 0); 8935 8936 // All conflicts with previous declarations are recovered by 8937 // returning the previous declaration, unless this is a definition, 8938 // in which case we want the caller to bail out. 8939 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 8940 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 8941 return TUK == TUK_Declaration ? PrevTagDecl : 0; 8942 } 8943 8944 if (!Invalid) { 8945 // If this is a use, just return the declaration we found. 8946 8947 // FIXME: In the future, return a variant or some other clue 8948 // for the consumer of this Decl to know it doesn't own it. 8949 // For our current ASTs this shouldn't be a problem, but will 8950 // need to be changed with DeclGroups. 8951 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 8952 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 8953 return PrevTagDecl; 8954 8955 // Diagnose attempts to redefine a tag. 8956 if (TUK == TUK_Definition) { 8957 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 8958 // If we're defining a specialization and the previous definition 8959 // is from an implicit instantiation, don't emit an error 8960 // here; we'll catch this in the general case below. 8961 bool IsExplicitSpecializationAfterInstantiation = false; 8962 if (isExplicitSpecialization) { 8963 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 8964 IsExplicitSpecializationAfterInstantiation = 8965 RD->getTemplateSpecializationKind() != 8966 TSK_ExplicitSpecialization; 8967 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 8968 IsExplicitSpecializationAfterInstantiation = 8969 ED->getTemplateSpecializationKind() != 8970 TSK_ExplicitSpecialization; 8971 } 8972 8973 if (!IsExplicitSpecializationAfterInstantiation) { 8974 // A redeclaration in function prototype scope in C isn't 8975 // visible elsewhere, so merely issue a warning. 8976 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 8977 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 8978 else 8979 Diag(NameLoc, diag::err_redefinition) << Name; 8980 Diag(Def->getLocation(), diag::note_previous_definition); 8981 // If this is a redefinition, recover by making this 8982 // struct be anonymous, which will make any later 8983 // references get the previous definition. 8984 Name = 0; 8985 Previous.clear(); 8986 Invalid = true; 8987 } 8988 } else { 8989 // If the type is currently being defined, complain 8990 // about a nested redefinition. 8991 const TagType *Tag 8992 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 8993 if (Tag->isBeingDefined()) { 8994 Diag(NameLoc, diag::err_nested_redefinition) << Name; 8995 Diag(PrevTagDecl->getLocation(), 8996 diag::note_previous_definition); 8997 Name = 0; 8998 Previous.clear(); 8999 Invalid = true; 9000 } 9001 } 9002 9003 // Okay, this is definition of a previously declared or referenced 9004 // tag PrevDecl. We're going to create a new Decl for it. 9005 } 9006 } 9007 // If we get here we have (another) forward declaration or we 9008 // have a definition. Just create a new decl. 9009 9010 } else { 9011 // If we get here, this is a definition of a new tag type in a nested 9012 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 9013 // new decl/type. We set PrevDecl to NULL so that the entities 9014 // have distinct types. 9015 Previous.clear(); 9016 } 9017 // If we get here, we're going to create a new Decl. If PrevDecl 9018 // is non-NULL, it's a definition of the tag declared by 9019 // PrevDecl. If it's NULL, we have a new definition. 9020 9021 9022 // Otherwise, PrevDecl is not a tag, but was found with tag 9023 // lookup. This is only actually possible in C++, where a few 9024 // things like templates still live in the tag namespace. 9025 } else { 9026 // Use a better diagnostic if an elaborated-type-specifier 9027 // found the wrong kind of type on the first 9028 // (non-redeclaration) lookup. 9029 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 9030 !Previous.isForRedeclaration()) { 9031 unsigned Kind = 0; 9032 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9033 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9034 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9035 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 9036 Diag(PrevDecl->getLocation(), diag::note_declared_at); 9037 Invalid = true; 9038 9039 // Otherwise, only diagnose if the declaration is in scope. 9040 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 9041 isExplicitSpecialization)) { 9042 // do nothing 9043 9044 // Diagnose implicit declarations introduced by elaborated types. 9045 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 9046 unsigned Kind = 0; 9047 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9048 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9049 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9050 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 9051 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9052 Invalid = true; 9053 9054 // Otherwise it's a declaration. Call out a particularly common 9055 // case here. 9056 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9057 unsigned Kind = 0; 9058 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 9059 Diag(NameLoc, diag::err_tag_definition_of_typedef) 9060 << Name << Kind << TND->getUnderlyingType(); 9061 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9062 Invalid = true; 9063 9064 // Otherwise, diagnose. 9065 } else { 9066 // The tag name clashes with something else in the target scope, 9067 // issue an error and recover by making this tag be anonymous. 9068 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 9069 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9070 Name = 0; 9071 Invalid = true; 9072 } 9073 9074 // The existing declaration isn't relevant to us; we're in a 9075 // new scope, so clear out the previous declaration. 9076 Previous.clear(); 9077 } 9078 } 9079 9080CreateNewDecl: 9081 9082 TagDecl *PrevDecl = 0; 9083 if (Previous.isSingleResult()) 9084 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 9085 9086 // If there is an identifier, use the location of the identifier as the 9087 // location of the decl, otherwise use the location of the struct/union 9088 // keyword. 9089 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 9090 9091 // Otherwise, create a new declaration. If there is a previous 9092 // declaration of the same entity, the two will be linked via 9093 // PrevDecl. 9094 TagDecl *New; 9095 9096 bool IsForwardReference = false; 9097 if (Kind == TTK_Enum) { 9098 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9099 // enum X { A, B, C } D; D should chain to X. 9100 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 9101 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 9102 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 9103 // If this is an undefined enum, warn. 9104 if (TUK != TUK_Definition && !Invalid) { 9105 TagDecl *Def; 9106 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 9107 // C++0x: 7.2p2: opaque-enum-declaration. 9108 // Conflicts are diagnosed above. Do nothing. 9109 } 9110 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 9111 Diag(Loc, diag::ext_forward_ref_enum_def) 9112 << New; 9113 Diag(Def->getLocation(), diag::note_previous_definition); 9114 } else { 9115 unsigned DiagID = diag::ext_forward_ref_enum; 9116 if (getLangOpts().MicrosoftMode) 9117 DiagID = diag::ext_ms_forward_ref_enum; 9118 else if (getLangOpts().CPlusPlus) 9119 DiagID = diag::err_forward_ref_enum; 9120 Diag(Loc, DiagID); 9121 9122 // If this is a forward-declared reference to an enumeration, make a 9123 // note of it; we won't actually be introducing the declaration into 9124 // the declaration context. 9125 if (TUK == TUK_Reference) 9126 IsForwardReference = true; 9127 } 9128 } 9129 9130 if (EnumUnderlying) { 9131 EnumDecl *ED = cast<EnumDecl>(New); 9132 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9133 ED->setIntegerTypeSourceInfo(TI); 9134 else 9135 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 9136 ED->setPromotionType(ED->getIntegerType()); 9137 } 9138 9139 } else { 9140 // struct/union/class 9141 9142 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9143 // struct X { int A; } D; D should chain to X. 9144 if (getLangOpts().CPlusPlus) { 9145 // FIXME: Look for a way to use RecordDecl for simple structs. 9146 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9147 cast_or_null<CXXRecordDecl>(PrevDecl)); 9148 9149 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 9150 StdBadAlloc = cast<CXXRecordDecl>(New); 9151 } else 9152 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9153 cast_or_null<RecordDecl>(PrevDecl)); 9154 } 9155 9156 // Maybe add qualifier info. 9157 if (SS.isNotEmpty()) { 9158 if (SS.isSet()) { 9159 // If this is either a declaration or a definition, check the 9160 // nested-name-specifier against the current context. We don't do this 9161 // for explicit specializations, because they have similar checking 9162 // (with more specific diagnostics) in the call to 9163 // CheckMemberSpecialization, below. 9164 if (!isExplicitSpecialization && 9165 (TUK == TUK_Definition || TUK == TUK_Declaration) && 9166 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 9167 Invalid = true; 9168 9169 New->setQualifierInfo(SS.getWithLocInContext(Context)); 9170 if (TemplateParameterLists.size() > 0) { 9171 New->setTemplateParameterListsInfo(Context, 9172 TemplateParameterLists.size(), 9173 TemplateParameterLists.data()); 9174 } 9175 } 9176 else 9177 Invalid = true; 9178 } 9179 9180 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 9181 // Add alignment attributes if necessary; these attributes are checked when 9182 // the ASTContext lays out the structure. 9183 // 9184 // It is important for implementing the correct semantics that this 9185 // happen here (in act on tag decl). The #pragma pack stack is 9186 // maintained as a result of parser callbacks which can occur at 9187 // many points during the parsing of a struct declaration (because 9188 // the #pragma tokens are effectively skipped over during the 9189 // parsing of the struct). 9190 if (TUK == TUK_Definition) { 9191 AddAlignmentAttributesForRecord(RD); 9192 AddMsStructLayoutForRecord(RD); 9193 } 9194 } 9195 9196 if (ModulePrivateLoc.isValid()) { 9197 if (isExplicitSpecialization) 9198 Diag(New->getLocation(), diag::err_module_private_specialization) 9199 << 2 9200 << FixItHint::CreateRemoval(ModulePrivateLoc); 9201 // __module_private__ does not apply to local classes. However, we only 9202 // diagnose this as an error when the declaration specifiers are 9203 // freestanding. Here, we just ignore the __module_private__. 9204 else if (!SearchDC->isFunctionOrMethod()) 9205 New->setModulePrivate(); 9206 } 9207 9208 // If this is a specialization of a member class (of a class template), 9209 // check the specialization. 9210 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 9211 Invalid = true; 9212 9213 if (Invalid) 9214 New->setInvalidDecl(); 9215 9216 if (Attr) 9217 ProcessDeclAttributeList(S, New, Attr); 9218 9219 // If we're declaring or defining a tag in function prototype scope 9220 // in C, note that this type can only be used within the function. 9221 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 9222 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 9223 9224 // Set the lexical context. If the tag has a C++ scope specifier, the 9225 // lexical context will be different from the semantic context. 9226 New->setLexicalDeclContext(CurContext); 9227 9228 // Mark this as a friend decl if applicable. 9229 // In Microsoft mode, a friend declaration also acts as a forward 9230 // declaration so we always pass true to setObjectOfFriendDecl to make 9231 // the tag name visible. 9232 if (TUK == TUK_Friend) 9233 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 9234 getLangOpts().MicrosoftExt); 9235 9236 // Set the access specifier. 9237 if (!Invalid && SearchDC->isRecord()) 9238 SetMemberAccessSpecifier(New, PrevDecl, AS); 9239 9240 if (TUK == TUK_Definition) 9241 New->startDefinition(); 9242 9243 // If this has an identifier, add it to the scope stack. 9244 if (TUK == TUK_Friend) { 9245 // We might be replacing an existing declaration in the lookup tables; 9246 // if so, borrow its access specifier. 9247 if (PrevDecl) 9248 New->setAccess(PrevDecl->getAccess()); 9249 9250 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 9251 DC->makeDeclVisibleInContext(New); 9252 if (Name) // can be null along some error paths 9253 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 9254 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 9255 } else if (Name) { 9256 S = getNonFieldDeclScope(S); 9257 PushOnScopeChains(New, S, !IsForwardReference); 9258 if (IsForwardReference) 9259 SearchDC->makeDeclVisibleInContext(New); 9260 9261 } else { 9262 CurContext->addDecl(New); 9263 } 9264 9265 // If this is the C FILE type, notify the AST context. 9266 if (IdentifierInfo *II = New->getIdentifier()) 9267 if (!New->isInvalidDecl() && 9268 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 9269 II->isStr("FILE")) 9270 Context.setFILEDecl(New); 9271 9272 // If we were in function prototype scope (and not in C++ mode), add this 9273 // tag to the list of decls to inject into the function definition scope. 9274 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 9275 InFunctionDeclarator && Name) 9276 DeclsInPrototypeScope.push_back(New); 9277 9278 if (PrevDecl) 9279 mergeDeclAttributes(New, PrevDecl); 9280 9281 // If there's a #pragma GCC visibility in scope, set the visibility of this 9282 // record. 9283 AddPushedVisibilityAttribute(New); 9284 9285 OwnedDecl = true; 9286 return New; 9287} 9288 9289void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 9290 AdjustDeclIfTemplate(TagD); 9291 TagDecl *Tag = cast<TagDecl>(TagD); 9292 9293 // Enter the tag context. 9294 PushDeclContext(S, Tag); 9295 9296 ActOnDocumentableDecl(TagD); 9297 9298 // If there's a #pragma GCC visibility in scope, set the visibility of this 9299 // record. 9300 AddPushedVisibilityAttribute(Tag); 9301} 9302 9303Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 9304 assert(isa<ObjCContainerDecl>(IDecl) && 9305 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 9306 DeclContext *OCD = cast<DeclContext>(IDecl); 9307 assert(getContainingDC(OCD) == CurContext && 9308 "The next DeclContext should be lexically contained in the current one."); 9309 CurContext = OCD; 9310 return IDecl; 9311} 9312 9313void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 9314 SourceLocation FinalLoc, 9315 SourceLocation LBraceLoc) { 9316 AdjustDeclIfTemplate(TagD); 9317 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 9318 9319 FieldCollector->StartClass(); 9320 9321 if (!Record->getIdentifier()) 9322 return; 9323 9324 if (FinalLoc.isValid()) 9325 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 9326 9327 // C++ [class]p2: 9328 // [...] The class-name is also inserted into the scope of the 9329 // class itself; this is known as the injected-class-name. For 9330 // purposes of access checking, the injected-class-name is treated 9331 // as if it were a public member name. 9332 CXXRecordDecl *InjectedClassName 9333 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 9334 Record->getLocStart(), Record->getLocation(), 9335 Record->getIdentifier(), 9336 /*PrevDecl=*/0, 9337 /*DelayTypeCreation=*/true); 9338 Context.getTypeDeclType(InjectedClassName, Record); 9339 InjectedClassName->setImplicit(); 9340 InjectedClassName->setAccess(AS_public); 9341 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 9342 InjectedClassName->setDescribedClassTemplate(Template); 9343 PushOnScopeChains(InjectedClassName, S); 9344 assert(InjectedClassName->isInjectedClassName() && 9345 "Broken injected-class-name"); 9346} 9347 9348void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 9349 SourceLocation RBraceLoc) { 9350 AdjustDeclIfTemplate(TagD); 9351 TagDecl *Tag = cast<TagDecl>(TagD); 9352 Tag->setRBraceLoc(RBraceLoc); 9353 9354 // Make sure we "complete" the definition even it is invalid. 9355 if (Tag->isBeingDefined()) { 9356 assert(Tag->isInvalidDecl() && "We should already have completed it"); 9357 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9358 RD->completeDefinition(); 9359 } 9360 9361 if (isa<CXXRecordDecl>(Tag)) 9362 FieldCollector->FinishClass(); 9363 9364 // Exit this scope of this tag's definition. 9365 PopDeclContext(); 9366 9367 // Notify the consumer that we've defined a tag. 9368 Consumer.HandleTagDeclDefinition(Tag); 9369} 9370 9371void Sema::ActOnObjCContainerFinishDefinition() { 9372 // Exit this scope of this interface definition. 9373 PopDeclContext(); 9374} 9375 9376void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 9377 assert(DC == CurContext && "Mismatch of container contexts"); 9378 OriginalLexicalContext = DC; 9379 ActOnObjCContainerFinishDefinition(); 9380} 9381 9382void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 9383 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 9384 OriginalLexicalContext = 0; 9385} 9386 9387void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 9388 AdjustDeclIfTemplate(TagD); 9389 TagDecl *Tag = cast<TagDecl>(TagD); 9390 Tag->setInvalidDecl(); 9391 9392 // Make sure we "complete" the definition even it is invalid. 9393 if (Tag->isBeingDefined()) { 9394 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9395 RD->completeDefinition(); 9396 } 9397 9398 // We're undoing ActOnTagStartDefinition here, not 9399 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 9400 // the FieldCollector. 9401 9402 PopDeclContext(); 9403} 9404 9405// Note that FieldName may be null for anonymous bitfields. 9406ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 9407 IdentifierInfo *FieldName, 9408 QualType FieldTy, Expr *BitWidth, 9409 bool *ZeroWidth) { 9410 // Default to true; that shouldn't confuse checks for emptiness 9411 if (ZeroWidth) 9412 *ZeroWidth = true; 9413 9414 // C99 6.7.2.1p4 - verify the field type. 9415 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 9416 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 9417 // Handle incomplete types with specific error. 9418 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 9419 return ExprError(); 9420 if (FieldName) 9421 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 9422 << FieldName << FieldTy << BitWidth->getSourceRange(); 9423 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 9424 << FieldTy << BitWidth->getSourceRange(); 9425 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 9426 UPPC_BitFieldWidth)) 9427 return ExprError(); 9428 9429 // If the bit-width is type- or value-dependent, don't try to check 9430 // it now. 9431 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 9432 return Owned(BitWidth); 9433 9434 llvm::APSInt Value; 9435 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 9436 if (ICE.isInvalid()) 9437 return ICE; 9438 BitWidth = ICE.take(); 9439 9440 if (Value != 0 && ZeroWidth) 9441 *ZeroWidth = false; 9442 9443 // Zero-width bitfield is ok for anonymous field. 9444 if (Value == 0 && FieldName) 9445 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 9446 9447 if (Value.isSigned() && Value.isNegative()) { 9448 if (FieldName) 9449 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 9450 << FieldName << Value.toString(10); 9451 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 9452 << Value.toString(10); 9453 } 9454 9455 if (!FieldTy->isDependentType()) { 9456 uint64_t TypeSize = Context.getTypeSize(FieldTy); 9457 if (Value.getZExtValue() > TypeSize) { 9458 if (!getLangOpts().CPlusPlus) { 9459 if (FieldName) 9460 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 9461 << FieldName << (unsigned)Value.getZExtValue() 9462 << (unsigned)TypeSize; 9463 9464 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 9465 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9466 } 9467 9468 if (FieldName) 9469 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 9470 << FieldName << (unsigned)Value.getZExtValue() 9471 << (unsigned)TypeSize; 9472 else 9473 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 9474 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9475 } 9476 } 9477 9478 return Owned(BitWidth); 9479} 9480 9481/// ActOnField - Each field of a C struct/union is passed into this in order 9482/// to create a FieldDecl object for it. 9483Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 9484 Declarator &D, Expr *BitfieldWidth) { 9485 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 9486 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 9487 /*InitStyle=*/ICIS_NoInit, AS_public); 9488 return Res; 9489} 9490 9491/// HandleField - Analyze a field of a C struct or a C++ data member. 9492/// 9493FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 9494 SourceLocation DeclStart, 9495 Declarator &D, Expr *BitWidth, 9496 InClassInitStyle InitStyle, 9497 AccessSpecifier AS) { 9498 IdentifierInfo *II = D.getIdentifier(); 9499 SourceLocation Loc = DeclStart; 9500 if (II) Loc = D.getIdentifierLoc(); 9501 9502 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9503 QualType T = TInfo->getType(); 9504 if (getLangOpts().CPlusPlus) { 9505 CheckExtraCXXDefaultArguments(D); 9506 9507 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9508 UPPC_DataMemberType)) { 9509 D.setInvalidType(); 9510 T = Context.IntTy; 9511 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 9512 } 9513 } 9514 9515 DiagnoseFunctionSpecifiers(D); 9516 9517 if (D.getDeclSpec().isThreadSpecified()) 9518 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 9519 if (D.getDeclSpec().isConstexprSpecified()) 9520 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 9521 << 2; 9522 9523 // Check to see if this name was declared as a member previously 9524 NamedDecl *PrevDecl = 0; 9525 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 9526 LookupName(Previous, S); 9527 switch (Previous.getResultKind()) { 9528 case LookupResult::Found: 9529 case LookupResult::FoundUnresolvedValue: 9530 PrevDecl = Previous.getAsSingle<NamedDecl>(); 9531 break; 9532 9533 case LookupResult::FoundOverloaded: 9534 PrevDecl = Previous.getRepresentativeDecl(); 9535 break; 9536 9537 case LookupResult::NotFound: 9538 case LookupResult::NotFoundInCurrentInstantiation: 9539 case LookupResult::Ambiguous: 9540 break; 9541 } 9542 Previous.suppressDiagnostics(); 9543 9544 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9545 // Maybe we will complain about the shadowed template parameter. 9546 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9547 // Just pretend that we didn't see the previous declaration. 9548 PrevDecl = 0; 9549 } 9550 9551 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 9552 PrevDecl = 0; 9553 9554 bool Mutable 9555 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 9556 SourceLocation TSSL = D.getLocStart(); 9557 FieldDecl *NewFD 9558 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 9559 TSSL, AS, PrevDecl, &D); 9560 9561 if (NewFD->isInvalidDecl()) 9562 Record->setInvalidDecl(); 9563 9564 if (D.getDeclSpec().isModulePrivateSpecified()) 9565 NewFD->setModulePrivate(); 9566 9567 if (NewFD->isInvalidDecl() && PrevDecl) { 9568 // Don't introduce NewFD into scope; there's already something 9569 // with the same name in the same scope. 9570 } else if (II) { 9571 PushOnScopeChains(NewFD, S); 9572 } else 9573 Record->addDecl(NewFD); 9574 9575 return NewFD; 9576} 9577 9578/// \brief Build a new FieldDecl and check its well-formedness. 9579/// 9580/// This routine builds a new FieldDecl given the fields name, type, 9581/// record, etc. \p PrevDecl should refer to any previous declaration 9582/// with the same name and in the same scope as the field to be 9583/// created. 9584/// 9585/// \returns a new FieldDecl. 9586/// 9587/// \todo The Declarator argument is a hack. It will be removed once 9588FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 9589 TypeSourceInfo *TInfo, 9590 RecordDecl *Record, SourceLocation Loc, 9591 bool Mutable, Expr *BitWidth, 9592 InClassInitStyle InitStyle, 9593 SourceLocation TSSL, 9594 AccessSpecifier AS, NamedDecl *PrevDecl, 9595 Declarator *D) { 9596 IdentifierInfo *II = Name.getAsIdentifierInfo(); 9597 bool InvalidDecl = false; 9598 if (D) InvalidDecl = D->isInvalidType(); 9599 9600 // If we receive a broken type, recover by assuming 'int' and 9601 // marking this declaration as invalid. 9602 if (T.isNull()) { 9603 InvalidDecl = true; 9604 T = Context.IntTy; 9605 } 9606 9607 QualType EltTy = Context.getBaseElementType(T); 9608 if (!EltTy->isDependentType()) { 9609 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 9610 // Fields of incomplete type force their record to be invalid. 9611 Record->setInvalidDecl(); 9612 InvalidDecl = true; 9613 } else { 9614 NamedDecl *Def; 9615 EltTy->isIncompleteType(&Def); 9616 if (Def && Def->isInvalidDecl()) { 9617 Record->setInvalidDecl(); 9618 InvalidDecl = true; 9619 } 9620 } 9621 } 9622 9623 // C99 6.7.2.1p8: A member of a structure or union may have any type other 9624 // than a variably modified type. 9625 if (!InvalidDecl && T->isVariablyModifiedType()) { 9626 bool SizeIsNegative; 9627 llvm::APSInt Oversized; 9628 9629 TypeSourceInfo *FixedTInfo = 9630 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 9631 SizeIsNegative, 9632 Oversized); 9633 if (FixedTInfo) { 9634 Diag(Loc, diag::warn_illegal_constant_array_size); 9635 TInfo = FixedTInfo; 9636 T = FixedTInfo->getType(); 9637 } else { 9638 if (SizeIsNegative) 9639 Diag(Loc, diag::err_typecheck_negative_array_size); 9640 else if (Oversized.getBoolValue()) 9641 Diag(Loc, diag::err_array_too_large) 9642 << Oversized.toString(10); 9643 else 9644 Diag(Loc, diag::err_typecheck_field_variable_size); 9645 InvalidDecl = true; 9646 } 9647 } 9648 9649 // Fields can not have abstract class types 9650 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 9651 diag::err_abstract_type_in_decl, 9652 AbstractFieldType)) 9653 InvalidDecl = true; 9654 9655 bool ZeroWidth = false; 9656 // If this is declared as a bit-field, check the bit-field. 9657 if (!InvalidDecl && BitWidth) { 9658 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 9659 if (!BitWidth) { 9660 InvalidDecl = true; 9661 BitWidth = 0; 9662 ZeroWidth = false; 9663 } 9664 } 9665 9666 // Check that 'mutable' is consistent with the type of the declaration. 9667 if (!InvalidDecl && Mutable) { 9668 unsigned DiagID = 0; 9669 if (T->isReferenceType()) 9670 DiagID = diag::err_mutable_reference; 9671 else if (T.isConstQualified()) 9672 DiagID = diag::err_mutable_const; 9673 9674 if (DiagID) { 9675 SourceLocation ErrLoc = Loc; 9676 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 9677 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 9678 Diag(ErrLoc, DiagID); 9679 Mutable = false; 9680 InvalidDecl = true; 9681 } 9682 } 9683 9684 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 9685 BitWidth, Mutable, InitStyle); 9686 if (InvalidDecl) 9687 NewFD->setInvalidDecl(); 9688 9689 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 9690 Diag(Loc, diag::err_duplicate_member) << II; 9691 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9692 NewFD->setInvalidDecl(); 9693 } 9694 9695 if (!InvalidDecl && getLangOpts().CPlusPlus) { 9696 if (Record->isUnion()) { 9697 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 9698 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 9699 if (RDecl->getDefinition()) { 9700 // C++ [class.union]p1: An object of a class with a non-trivial 9701 // constructor, a non-trivial copy constructor, a non-trivial 9702 // destructor, or a non-trivial copy assignment operator 9703 // cannot be a member of a union, nor can an array of such 9704 // objects. 9705 if (CheckNontrivialField(NewFD)) 9706 NewFD->setInvalidDecl(); 9707 } 9708 } 9709 9710 // C++ [class.union]p1: If a union contains a member of reference type, 9711 // the program is ill-formed. 9712 if (EltTy->isReferenceType()) { 9713 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 9714 << NewFD->getDeclName() << EltTy; 9715 NewFD->setInvalidDecl(); 9716 } 9717 } 9718 } 9719 9720 // FIXME: We need to pass in the attributes given an AST 9721 // representation, not a parser representation. 9722 if (D) 9723 // FIXME: What to pass instead of TUScope? 9724 ProcessDeclAttributes(TUScope, NewFD, *D); 9725 9726 // In auto-retain/release, infer strong retension for fields of 9727 // retainable type. 9728 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 9729 NewFD->setInvalidDecl(); 9730 9731 if (T.isObjCGCWeak()) 9732 Diag(Loc, diag::warn_attribute_weak_on_field); 9733 9734 NewFD->setAccess(AS); 9735 return NewFD; 9736} 9737 9738bool Sema::CheckNontrivialField(FieldDecl *FD) { 9739 assert(FD); 9740 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 9741 9742 if (FD->isInvalidDecl()) 9743 return true; 9744 9745 QualType EltTy = Context.getBaseElementType(FD->getType()); 9746 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 9747 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 9748 if (RDecl->getDefinition()) { 9749 // We check for copy constructors before constructors 9750 // because otherwise we'll never get complaints about 9751 // copy constructors. 9752 9753 CXXSpecialMember member = CXXInvalid; 9754 // We're required to check for any non-trivial constructors. Since the 9755 // implicit default constructor is suppressed if there are any 9756 // user-declared constructors, we just need to check that there is a 9757 // trivial default constructor and a trivial copy constructor. (We don't 9758 // worry about move constructors here, since this is a C++98 check.) 9759 if (RDecl->hasNonTrivialCopyConstructor()) 9760 member = CXXCopyConstructor; 9761 else if (!RDecl->hasTrivialDefaultConstructor()) 9762 member = CXXDefaultConstructor; 9763 else if (RDecl->hasNonTrivialCopyAssignment()) 9764 member = CXXCopyAssignment; 9765 else if (RDecl->hasNonTrivialDestructor()) 9766 member = CXXDestructor; 9767 9768 if (member != CXXInvalid) { 9769 if (!getLangOpts().CPlusPlus0x && 9770 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 9771 // Objective-C++ ARC: it is an error to have a non-trivial field of 9772 // a union. However, system headers in Objective-C programs 9773 // occasionally have Objective-C lifetime objects within unions, 9774 // and rather than cause the program to fail, we make those 9775 // members unavailable. 9776 SourceLocation Loc = FD->getLocation(); 9777 if (getSourceManager().isInSystemHeader(Loc)) { 9778 if (!FD->hasAttr<UnavailableAttr>()) 9779 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 9780 "this system field has retaining ownership")); 9781 return false; 9782 } 9783 } 9784 9785 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ? 9786 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 9787 diag::err_illegal_union_or_anon_struct_member) 9788 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 9789 DiagnoseNontrivial(RT, member); 9790 return !getLangOpts().CPlusPlus0x; 9791 } 9792 } 9793 } 9794 9795 return false; 9796} 9797 9798/// If the given constructor is user-declared, produce a diagnostic explaining 9799/// that it makes the class non-trivial. 9800static bool diagnoseNonTrivialUserDeclaredCtor(Sema &S, QualType QT, 9801 CXXConstructorDecl *CD, 9802 Sema::CXXSpecialMember CSM) { 9803 if (CD->isImplicit()) 9804 return false; 9805 9806 SourceLocation CtorLoc = CD->getLocation(); 9807 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM; 9808 return true; 9809} 9810 9811/// DiagnoseNontrivial - Given that a class has a non-trivial 9812/// special member, figure out why. 9813/// FIXME: These checks are not correct in C++11 mode. Currently, this is OK 9814/// since we only use this in C++11 for a -Wc++98-compat warning. 9815void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 9816 QualType QT(T, 0U); 9817 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 9818 9819 // Check whether the member was user-declared. 9820 switch (member) { 9821 case CXXInvalid: 9822 break; 9823 9824 case CXXDefaultConstructor: 9825 if (RD->hasUserDeclaredConstructor()) { 9826 typedef CXXRecordDecl::ctor_iterator ctor_iter; 9827 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI) 9828 if (diagnoseNonTrivialUserDeclaredCtor(*this, QT, *CI, member)) 9829 return; 9830 9831 // No user-delcared constructors; look for constructor templates. 9832 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9833 tmpl_iter; 9834 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); 9835 TI != TE; ++TI) { 9836 CXXConstructorDecl *CD = 9837 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()); 9838 if (CD && diagnoseNonTrivialUserDeclaredCtor(*this, QT, CD, member)) 9839 return; 9840 } 9841 } 9842 break; 9843 9844 case CXXCopyConstructor: 9845 if (RD->hasUserDeclaredCopyConstructor()) { 9846 SourceLocation CtorLoc = 9847 RD->getCopyConstructor(0)->getLocation(); 9848 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9849 return; 9850 } 9851 break; 9852 9853 case CXXMoveConstructor: 9854 if (RD->hasUserDeclaredMoveConstructor()) { 9855 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 9856 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9857 return; 9858 } 9859 break; 9860 9861 case CXXCopyAssignment: 9862 if (RD->hasUserDeclaredCopyAssignment()) { 9863 SourceLocation AssignLoc = 9864 RD->getCopyAssignmentOperator(0)->getLocation(); 9865 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 9866 return; 9867 } 9868 break; 9869 9870 case CXXMoveAssignment: 9871 if (RD->hasUserDeclaredMoveAssignment()) { 9872 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 9873 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 9874 return; 9875 } 9876 break; 9877 9878 case CXXDestructor: 9879 if (RD->hasUserDeclaredDestructor()) { 9880 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 9881 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9882 return; 9883 } 9884 break; 9885 } 9886 9887 typedef CXXRecordDecl::base_class_iterator base_iter; 9888 9889 // Virtual bases and members inhibit trivial copying/construction, 9890 // but not trivial destruction. 9891 if (member != CXXDestructor) { 9892 // Check for virtual bases. vbases includes indirect virtual bases, 9893 // so we just iterate through the direct bases. 9894 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 9895 if (bi->isVirtual()) { 9896 SourceLocation BaseLoc = bi->getLocStart(); 9897 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 9898 return; 9899 } 9900 9901 // Check for virtual methods. 9902 typedef CXXRecordDecl::method_iterator meth_iter; 9903 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 9904 ++mi) { 9905 if (mi->isVirtual()) { 9906 SourceLocation MLoc = mi->getLocStart(); 9907 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 9908 return; 9909 } 9910 } 9911 } 9912 9913 bool (CXXRecordDecl::*hasNonTrivial)() const; 9914 switch (member) { 9915 case CXXDefaultConstructor: 9916 hasNonTrivial = &CXXRecordDecl::hasNonTrivialDefaultConstructor; break; 9917 case CXXCopyConstructor: 9918 hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyConstructor; break; 9919 case CXXCopyAssignment: 9920 hasNonTrivial = &CXXRecordDecl::hasNonTrivialCopyAssignment; break; 9921 case CXXMoveConstructor: 9922 hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveConstructor; break; 9923 case CXXMoveAssignment: 9924 hasNonTrivial = &CXXRecordDecl::hasNonTrivialMoveAssignment; break; 9925 case CXXDestructor: 9926 hasNonTrivial = &CXXRecordDecl::hasNonTrivialDestructor; break; 9927 case CXXInvalid: 9928 llvm_unreachable("unexpected special member"); 9929 } 9930 9931 // Check for nontrivial bases (and recurse). 9932 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 9933 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 9934 assert(BaseRT && "Don't know how to handle dependent bases"); 9935 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 9936 if ((BaseRecTy->*hasNonTrivial)()) { 9937 SourceLocation BaseLoc = bi->getLocStart(); 9938 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 9939 DiagnoseNontrivial(BaseRT, member); 9940 return; 9941 } 9942 } 9943 9944 // Check for nontrivial members (and recurse). 9945 typedef RecordDecl::field_iterator field_iter; 9946 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 9947 ++fi) { 9948 QualType EltTy = Context.getBaseElementType(fi->getType()); 9949 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 9950 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 9951 9952 if ((EltRD->*hasNonTrivial)()) { 9953 SourceLocation FLoc = fi->getLocation(); 9954 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 9955 DiagnoseNontrivial(EltRT, member); 9956 return; 9957 } 9958 } 9959 9960 if (EltTy->isObjCLifetimeType()) { 9961 switch (EltTy.getObjCLifetime()) { 9962 case Qualifiers::OCL_None: 9963 case Qualifiers::OCL_ExplicitNone: 9964 break; 9965 9966 case Qualifiers::OCL_Autoreleasing: 9967 case Qualifiers::OCL_Weak: 9968 case Qualifiers::OCL_Strong: 9969 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership) 9970 << QT << EltTy.getObjCLifetime(); 9971 return; 9972 } 9973 } 9974 } 9975} 9976 9977/// TranslateIvarVisibility - Translate visibility from a token ID to an 9978/// AST enum value. 9979static ObjCIvarDecl::AccessControl 9980TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 9981 switch (ivarVisibility) { 9982 default: llvm_unreachable("Unknown visitibility kind"); 9983 case tok::objc_private: return ObjCIvarDecl::Private; 9984 case tok::objc_public: return ObjCIvarDecl::Public; 9985 case tok::objc_protected: return ObjCIvarDecl::Protected; 9986 case tok::objc_package: return ObjCIvarDecl::Package; 9987 } 9988} 9989 9990/// ActOnIvar - Each ivar field of an objective-c class is passed into this 9991/// in order to create an IvarDecl object for it. 9992Decl *Sema::ActOnIvar(Scope *S, 9993 SourceLocation DeclStart, 9994 Declarator &D, Expr *BitfieldWidth, 9995 tok::ObjCKeywordKind Visibility) { 9996 9997 IdentifierInfo *II = D.getIdentifier(); 9998 Expr *BitWidth = (Expr*)BitfieldWidth; 9999 SourceLocation Loc = DeclStart; 10000 if (II) Loc = D.getIdentifierLoc(); 10001 10002 // FIXME: Unnamed fields can be handled in various different ways, for 10003 // example, unnamed unions inject all members into the struct namespace! 10004 10005 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10006 QualType T = TInfo->getType(); 10007 10008 if (BitWidth) { 10009 // 6.7.2.1p3, 6.7.2.1p4 10010 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 10011 if (!BitWidth) 10012 D.setInvalidType(); 10013 } else { 10014 // Not a bitfield. 10015 10016 // validate II. 10017 10018 } 10019 if (T->isReferenceType()) { 10020 Diag(Loc, diag::err_ivar_reference_type); 10021 D.setInvalidType(); 10022 } 10023 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10024 // than a variably modified type. 10025 else if (T->isVariablyModifiedType()) { 10026 Diag(Loc, diag::err_typecheck_ivar_variable_size); 10027 D.setInvalidType(); 10028 } 10029 10030 // Get the visibility (access control) for this ivar. 10031 ObjCIvarDecl::AccessControl ac = 10032 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 10033 : ObjCIvarDecl::None; 10034 // Must set ivar's DeclContext to its enclosing interface. 10035 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 10036 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 10037 return 0; 10038 ObjCContainerDecl *EnclosingContext; 10039 if (ObjCImplementationDecl *IMPDecl = 10040 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10041 if (LangOpts.ObjCRuntime.isFragile()) { 10042 // Case of ivar declared in an implementation. Context is that of its class. 10043 EnclosingContext = IMPDecl->getClassInterface(); 10044 assert(EnclosingContext && "Implementation has no class interface!"); 10045 } 10046 else 10047 EnclosingContext = EnclosingDecl; 10048 } else { 10049 if (ObjCCategoryDecl *CDecl = 10050 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10051 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 10052 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 10053 return 0; 10054 } 10055 } 10056 EnclosingContext = EnclosingDecl; 10057 } 10058 10059 // Construct the decl. 10060 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 10061 DeclStart, Loc, II, T, 10062 TInfo, ac, (Expr *)BitfieldWidth); 10063 10064 if (II) { 10065 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 10066 ForRedeclaration); 10067 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 10068 && !isa<TagDecl>(PrevDecl)) { 10069 Diag(Loc, diag::err_duplicate_member) << II; 10070 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10071 NewID->setInvalidDecl(); 10072 } 10073 } 10074 10075 // Process attributes attached to the ivar. 10076 ProcessDeclAttributes(S, NewID, D); 10077 10078 if (D.isInvalidType()) 10079 NewID->setInvalidDecl(); 10080 10081 // In ARC, infer 'retaining' for ivars of retainable type. 10082 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 10083 NewID->setInvalidDecl(); 10084 10085 if (D.getDeclSpec().isModulePrivateSpecified()) 10086 NewID->setModulePrivate(); 10087 10088 if (II) { 10089 // FIXME: When interfaces are DeclContexts, we'll need to add 10090 // these to the interface. 10091 S->AddDecl(NewID); 10092 IdResolver.AddDecl(NewID); 10093 } 10094 10095 if (LangOpts.ObjCRuntime.isNonFragile() && 10096 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 10097 Diag(Loc, diag::warn_ivars_in_interface); 10098 10099 return NewID; 10100} 10101 10102/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 10103/// class and class extensions. For every class @interface and class 10104/// extension @interface, if the last ivar is a bitfield of any type, 10105/// then add an implicit `char :0` ivar to the end of that interface. 10106void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 10107 SmallVectorImpl<Decl *> &AllIvarDecls) { 10108 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 10109 return; 10110 10111 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 10112 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 10113 10114 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 10115 return; 10116 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 10117 if (!ID) { 10118 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 10119 if (!CD->IsClassExtension()) 10120 return; 10121 } 10122 // No need to add this to end of @implementation. 10123 else 10124 return; 10125 } 10126 // All conditions are met. Add a new bitfield to the tail end of ivars. 10127 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 10128 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 10129 10130 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 10131 DeclLoc, DeclLoc, 0, 10132 Context.CharTy, 10133 Context.getTrivialTypeSourceInfo(Context.CharTy, 10134 DeclLoc), 10135 ObjCIvarDecl::Private, BW, 10136 true); 10137 AllIvarDecls.push_back(Ivar); 10138} 10139 10140void Sema::ActOnFields(Scope* S, 10141 SourceLocation RecLoc, Decl *EnclosingDecl, 10142 llvm::ArrayRef<Decl *> Fields, 10143 SourceLocation LBrac, SourceLocation RBrac, 10144 AttributeList *Attr) { 10145 assert(EnclosingDecl && "missing record or interface decl"); 10146 10147 // If this is an Objective-C @implementation or category and we have 10148 // new fields here we should reset the layout of the interface since 10149 // it will now change. 10150 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 10151 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 10152 switch (DC->getKind()) { 10153 default: break; 10154 case Decl::ObjCCategory: 10155 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 10156 break; 10157 case Decl::ObjCImplementation: 10158 Context. 10159 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 10160 break; 10161 } 10162 } 10163 10164 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 10165 10166 // Start counting up the number of named members; make sure to include 10167 // members of anonymous structs and unions in the total. 10168 unsigned NumNamedMembers = 0; 10169 if (Record) { 10170 for (RecordDecl::decl_iterator i = Record->decls_begin(), 10171 e = Record->decls_end(); i != e; i++) { 10172 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 10173 if (IFD->getDeclName()) 10174 ++NumNamedMembers; 10175 } 10176 } 10177 10178 // Verify that all the fields are okay. 10179 SmallVector<FieldDecl*, 32> RecFields; 10180 10181 bool ARCErrReported = false; 10182 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 10183 i != end; ++i) { 10184 FieldDecl *FD = cast<FieldDecl>(*i); 10185 10186 // Get the type for the field. 10187 const Type *FDTy = FD->getType().getTypePtr(); 10188 10189 if (!FD->isAnonymousStructOrUnion()) { 10190 // Remember all fields written by the user. 10191 RecFields.push_back(FD); 10192 } 10193 10194 // If the field is already invalid for some reason, don't emit more 10195 // diagnostics about it. 10196 if (FD->isInvalidDecl()) { 10197 EnclosingDecl->setInvalidDecl(); 10198 continue; 10199 } 10200 10201 // C99 6.7.2.1p2: 10202 // A structure or union shall not contain a member with 10203 // incomplete or function type (hence, a structure shall not 10204 // contain an instance of itself, but may contain a pointer to 10205 // an instance of itself), except that the last member of a 10206 // structure with more than one named member may have incomplete 10207 // array type; such a structure (and any union containing, 10208 // possibly recursively, a member that is such a structure) 10209 // shall not be a member of a structure or an element of an 10210 // array. 10211 if (FDTy->isFunctionType()) { 10212 // Field declared as a function. 10213 Diag(FD->getLocation(), diag::err_field_declared_as_function) 10214 << FD->getDeclName(); 10215 FD->setInvalidDecl(); 10216 EnclosingDecl->setInvalidDecl(); 10217 continue; 10218 } else if (FDTy->isIncompleteArrayType() && Record && 10219 ((i + 1 == Fields.end() && !Record->isUnion()) || 10220 ((getLangOpts().MicrosoftExt || 10221 getLangOpts().CPlusPlus) && 10222 (i + 1 == Fields.end() || Record->isUnion())))) { 10223 // Flexible array member. 10224 // Microsoft and g++ is more permissive regarding flexible array. 10225 // It will accept flexible array in union and also 10226 // as the sole element of a struct/class. 10227 if (getLangOpts().MicrosoftExt) { 10228 if (Record->isUnion()) 10229 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 10230 << FD->getDeclName(); 10231 else if (Fields.size() == 1) 10232 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 10233 << FD->getDeclName() << Record->getTagKind(); 10234 } else if (getLangOpts().CPlusPlus) { 10235 if (Record->isUnion()) 10236 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10237 << FD->getDeclName(); 10238 else if (Fields.size() == 1) 10239 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 10240 << FD->getDeclName() << Record->getTagKind(); 10241 } else if (!getLangOpts().C99) { 10242 if (Record->isUnion()) 10243 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10244 << FD->getDeclName(); 10245 else 10246 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 10247 << FD->getDeclName() << Record->getTagKind(); 10248 } else if (NumNamedMembers < 1) { 10249 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 10250 << FD->getDeclName(); 10251 FD->setInvalidDecl(); 10252 EnclosingDecl->setInvalidDecl(); 10253 continue; 10254 } 10255 if (!FD->getType()->isDependentType() && 10256 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 10257 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 10258 << FD->getDeclName() << FD->getType(); 10259 FD->setInvalidDecl(); 10260 EnclosingDecl->setInvalidDecl(); 10261 continue; 10262 } 10263 // Okay, we have a legal flexible array member at the end of the struct. 10264 if (Record) 10265 Record->setHasFlexibleArrayMember(true); 10266 } else if (!FDTy->isDependentType() && 10267 RequireCompleteType(FD->getLocation(), FD->getType(), 10268 diag::err_field_incomplete)) { 10269 // Incomplete type 10270 FD->setInvalidDecl(); 10271 EnclosingDecl->setInvalidDecl(); 10272 continue; 10273 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 10274 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 10275 // If this is a member of a union, then entire union becomes "flexible". 10276 if (Record && Record->isUnion()) { 10277 Record->setHasFlexibleArrayMember(true); 10278 } else { 10279 // If this is a struct/class and this is not the last element, reject 10280 // it. Note that GCC supports variable sized arrays in the middle of 10281 // structures. 10282 if (i + 1 != Fields.end()) 10283 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 10284 << FD->getDeclName() << FD->getType(); 10285 else { 10286 // We support flexible arrays at the end of structs in 10287 // other structs as an extension. 10288 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 10289 << FD->getDeclName(); 10290 if (Record) 10291 Record->setHasFlexibleArrayMember(true); 10292 } 10293 } 10294 } 10295 if (isa<ObjCContainerDecl>(EnclosingDecl) && 10296 RequireNonAbstractType(FD->getLocation(), FD->getType(), 10297 diag::err_abstract_type_in_decl, 10298 AbstractIvarType)) { 10299 // Ivars can not have abstract class types 10300 FD->setInvalidDecl(); 10301 } 10302 if (Record && FDTTy->getDecl()->hasObjectMember()) 10303 Record->setHasObjectMember(true); 10304 } else if (FDTy->isObjCObjectType()) { 10305 /// A field cannot be an Objective-c object 10306 Diag(FD->getLocation(), diag::err_statically_allocated_object) 10307 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 10308 QualType T = Context.getObjCObjectPointerType(FD->getType()); 10309 FD->setType(T); 10310 } else if (!getLangOpts().CPlusPlus) { 10311 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) { 10312 // It's an error in ARC if a field has lifetime. 10313 // We don't want to report this in a system header, though, 10314 // so we just make the field unavailable. 10315 // FIXME: that's really not sufficient; we need to make the type 10316 // itself invalid to, say, initialize or copy. 10317 QualType T = FD->getType(); 10318 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 10319 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 10320 SourceLocation loc = FD->getLocation(); 10321 if (getSourceManager().isInSystemHeader(loc)) { 10322 if (!FD->hasAttr<UnavailableAttr>()) { 10323 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10324 "this system field has retaining ownership")); 10325 } 10326 } else { 10327 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 10328 << T->isBlockPointerType(); 10329 } 10330 ARCErrReported = true; 10331 } 10332 } 10333 else if (getLangOpts().ObjC1 && 10334 getLangOpts().getGC() != LangOptions::NonGC && 10335 Record && !Record->hasObjectMember()) { 10336 if (FD->getType()->isObjCObjectPointerType() || 10337 FD->getType().isObjCGCStrong()) 10338 Record->setHasObjectMember(true); 10339 else if (Context.getAsArrayType(FD->getType())) { 10340 QualType BaseType = Context.getBaseElementType(FD->getType()); 10341 if (BaseType->isRecordType() && 10342 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 10343 Record->setHasObjectMember(true); 10344 else if (BaseType->isObjCObjectPointerType() || 10345 BaseType.isObjCGCStrong()) 10346 Record->setHasObjectMember(true); 10347 } 10348 } 10349 } 10350 // Keep track of the number of named members. 10351 if (FD->getIdentifier()) 10352 ++NumNamedMembers; 10353 } 10354 10355 // Okay, we successfully defined 'Record'. 10356 if (Record) { 10357 bool Completed = false; 10358 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 10359 if (!CXXRecord->isInvalidDecl()) { 10360 // Set access bits correctly on the directly-declared conversions. 10361 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 10362 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 10363 I != E; ++I) 10364 Convs->setAccess(I, (*I)->getAccess()); 10365 10366 if (!CXXRecord->isDependentType()) { 10367 // Adjust user-defined destructor exception spec. 10368 if (getLangOpts().CPlusPlus0x && 10369 CXXRecord->hasUserDeclaredDestructor()) 10370 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 10371 10372 // Add any implicitly-declared members to this class. 10373 AddImplicitlyDeclaredMembersToClass(CXXRecord); 10374 10375 // If we have virtual base classes, we may end up finding multiple 10376 // final overriders for a given virtual function. Check for this 10377 // problem now. 10378 if (CXXRecord->getNumVBases()) { 10379 CXXFinalOverriderMap FinalOverriders; 10380 CXXRecord->getFinalOverriders(FinalOverriders); 10381 10382 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 10383 MEnd = FinalOverriders.end(); 10384 M != MEnd; ++M) { 10385 for (OverridingMethods::iterator SO = M->second.begin(), 10386 SOEnd = M->second.end(); 10387 SO != SOEnd; ++SO) { 10388 assert(SO->second.size() > 0 && 10389 "Virtual function without overridding functions?"); 10390 if (SO->second.size() == 1) 10391 continue; 10392 10393 // C++ [class.virtual]p2: 10394 // In a derived class, if a virtual member function of a base 10395 // class subobject has more than one final overrider the 10396 // program is ill-formed. 10397 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 10398 << (const NamedDecl *)M->first << Record; 10399 Diag(M->first->getLocation(), 10400 diag::note_overridden_virtual_function); 10401 for (OverridingMethods::overriding_iterator 10402 OM = SO->second.begin(), 10403 OMEnd = SO->second.end(); 10404 OM != OMEnd; ++OM) 10405 Diag(OM->Method->getLocation(), diag::note_final_overrider) 10406 << (const NamedDecl *)M->first << OM->Method->getParent(); 10407 10408 Record->setInvalidDecl(); 10409 } 10410 } 10411 CXXRecord->completeDefinition(&FinalOverriders); 10412 Completed = true; 10413 } 10414 } 10415 } 10416 } 10417 10418 if (!Completed) 10419 Record->completeDefinition(); 10420 10421 } else { 10422 ObjCIvarDecl **ClsFields = 10423 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 10424 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 10425 ID->setEndOfDefinitionLoc(RBrac); 10426 // Add ivar's to class's DeclContext. 10427 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10428 ClsFields[i]->setLexicalDeclContext(ID); 10429 ID->addDecl(ClsFields[i]); 10430 } 10431 // Must enforce the rule that ivars in the base classes may not be 10432 // duplicates. 10433 if (ID->getSuperClass()) 10434 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 10435 } else if (ObjCImplementationDecl *IMPDecl = 10436 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10437 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 10438 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 10439 // Ivar declared in @implementation never belongs to the implementation. 10440 // Only it is in implementation's lexical context. 10441 ClsFields[I]->setLexicalDeclContext(IMPDecl); 10442 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 10443 IMPDecl->setIvarLBraceLoc(LBrac); 10444 IMPDecl->setIvarRBraceLoc(RBrac); 10445 } else if (ObjCCategoryDecl *CDecl = 10446 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10447 // case of ivars in class extension; all other cases have been 10448 // reported as errors elsewhere. 10449 // FIXME. Class extension does not have a LocEnd field. 10450 // CDecl->setLocEnd(RBrac); 10451 // Add ivar's to class extension's DeclContext. 10452 // Diagnose redeclaration of private ivars. 10453 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 10454 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10455 if (IDecl) { 10456 if (const ObjCIvarDecl *ClsIvar = 10457 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 10458 Diag(ClsFields[i]->getLocation(), 10459 diag::err_duplicate_ivar_declaration); 10460 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 10461 continue; 10462 } 10463 for (const ObjCCategoryDecl *ClsExtDecl = 10464 IDecl->getFirstClassExtension(); 10465 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) { 10466 if (const ObjCIvarDecl *ClsExtIvar = 10467 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 10468 Diag(ClsFields[i]->getLocation(), 10469 diag::err_duplicate_ivar_declaration); 10470 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 10471 continue; 10472 } 10473 } 10474 } 10475 ClsFields[i]->setLexicalDeclContext(CDecl); 10476 CDecl->addDecl(ClsFields[i]); 10477 } 10478 CDecl->setIvarLBraceLoc(LBrac); 10479 CDecl->setIvarRBraceLoc(RBrac); 10480 } 10481 } 10482 10483 if (Attr) 10484 ProcessDeclAttributeList(S, Record, Attr); 10485} 10486 10487/// \brief Determine whether the given integral value is representable within 10488/// the given type T. 10489static bool isRepresentableIntegerValue(ASTContext &Context, 10490 llvm::APSInt &Value, 10491 QualType T) { 10492 assert(T->isIntegralType(Context) && "Integral type required!"); 10493 unsigned BitWidth = Context.getIntWidth(T); 10494 10495 if (Value.isUnsigned() || Value.isNonNegative()) { 10496 if (T->isSignedIntegerOrEnumerationType()) 10497 --BitWidth; 10498 return Value.getActiveBits() <= BitWidth; 10499 } 10500 return Value.getMinSignedBits() <= BitWidth; 10501} 10502 10503// \brief Given an integral type, return the next larger integral type 10504// (or a NULL type of no such type exists). 10505static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 10506 // FIXME: Int128/UInt128 support, which also needs to be introduced into 10507 // enum checking below. 10508 assert(T->isIntegralType(Context) && "Integral type required!"); 10509 const unsigned NumTypes = 4; 10510 QualType SignedIntegralTypes[NumTypes] = { 10511 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 10512 }; 10513 QualType UnsignedIntegralTypes[NumTypes] = { 10514 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 10515 Context.UnsignedLongLongTy 10516 }; 10517 10518 unsigned BitWidth = Context.getTypeSize(T); 10519 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 10520 : UnsignedIntegralTypes; 10521 for (unsigned I = 0; I != NumTypes; ++I) 10522 if (Context.getTypeSize(Types[I]) > BitWidth) 10523 return Types[I]; 10524 10525 return QualType(); 10526} 10527 10528EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 10529 EnumConstantDecl *LastEnumConst, 10530 SourceLocation IdLoc, 10531 IdentifierInfo *Id, 10532 Expr *Val) { 10533 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10534 llvm::APSInt EnumVal(IntWidth); 10535 QualType EltTy; 10536 10537 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 10538 Val = 0; 10539 10540 if (Val) 10541 Val = DefaultLvalueConversion(Val).take(); 10542 10543 if (Val) { 10544 if (Enum->isDependentType() || Val->isTypeDependent()) 10545 EltTy = Context.DependentTy; 10546 else { 10547 SourceLocation ExpLoc; 10548 if (getLangOpts().CPlusPlus0x && Enum->isFixed() && 10549 !getLangOpts().MicrosoftMode) { 10550 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 10551 // constant-expression in the enumerator-definition shall be a converted 10552 // constant expression of the underlying type. 10553 EltTy = Enum->getIntegerType(); 10554 ExprResult Converted = 10555 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 10556 CCEK_Enumerator); 10557 if (Converted.isInvalid()) 10558 Val = 0; 10559 else 10560 Val = Converted.take(); 10561 } else if (!Val->isValueDependent() && 10562 !(Val = VerifyIntegerConstantExpression(Val, 10563 &EnumVal).take())) { 10564 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 10565 } else { 10566 if (Enum->isFixed()) { 10567 EltTy = Enum->getIntegerType(); 10568 10569 // In Obj-C and Microsoft mode, require the enumeration value to be 10570 // representable in the underlying type of the enumeration. In C++11, 10571 // we perform a non-narrowing conversion as part of converted constant 10572 // expression checking. 10573 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10574 if (getLangOpts().MicrosoftMode) { 10575 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 10576 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10577 } else 10578 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 10579 } else 10580 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10581 } else if (getLangOpts().CPlusPlus) { 10582 // C++11 [dcl.enum]p5: 10583 // If the underlying type is not fixed, the type of each enumerator 10584 // is the type of its initializing value: 10585 // - If an initializer is specified for an enumerator, the 10586 // initializing value has the same type as the expression. 10587 EltTy = Val->getType(); 10588 } else { 10589 // C99 6.7.2.2p2: 10590 // The expression that defines the value of an enumeration constant 10591 // shall be an integer constant expression that has a value 10592 // representable as an int. 10593 10594 // Complain if the value is not representable in an int. 10595 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 10596 Diag(IdLoc, diag::ext_enum_value_not_int) 10597 << EnumVal.toString(10) << Val->getSourceRange() 10598 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 10599 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 10600 // Force the type of the expression to 'int'. 10601 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 10602 } 10603 EltTy = Val->getType(); 10604 } 10605 } 10606 } 10607 } 10608 10609 if (!Val) { 10610 if (Enum->isDependentType()) 10611 EltTy = Context.DependentTy; 10612 else if (!LastEnumConst) { 10613 // C++0x [dcl.enum]p5: 10614 // If the underlying type is not fixed, the type of each enumerator 10615 // is the type of its initializing value: 10616 // - If no initializer is specified for the first enumerator, the 10617 // initializing value has an unspecified integral type. 10618 // 10619 // GCC uses 'int' for its unspecified integral type, as does 10620 // C99 6.7.2.2p3. 10621 if (Enum->isFixed()) { 10622 EltTy = Enum->getIntegerType(); 10623 } 10624 else { 10625 EltTy = Context.IntTy; 10626 } 10627 } else { 10628 // Assign the last value + 1. 10629 EnumVal = LastEnumConst->getInitVal(); 10630 ++EnumVal; 10631 EltTy = LastEnumConst->getType(); 10632 10633 // Check for overflow on increment. 10634 if (EnumVal < LastEnumConst->getInitVal()) { 10635 // C++0x [dcl.enum]p5: 10636 // If the underlying type is not fixed, the type of each enumerator 10637 // is the type of its initializing value: 10638 // 10639 // - Otherwise the type of the initializing value is the same as 10640 // the type of the initializing value of the preceding enumerator 10641 // unless the incremented value is not representable in that type, 10642 // in which case the type is an unspecified integral type 10643 // sufficient to contain the incremented value. If no such type 10644 // exists, the program is ill-formed. 10645 QualType T = getNextLargerIntegralType(Context, EltTy); 10646 if (T.isNull() || Enum->isFixed()) { 10647 // There is no integral type larger enough to represent this 10648 // value. Complain, then allow the value to wrap around. 10649 EnumVal = LastEnumConst->getInitVal(); 10650 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 10651 ++EnumVal; 10652 if (Enum->isFixed()) 10653 // When the underlying type is fixed, this is ill-formed. 10654 Diag(IdLoc, diag::err_enumerator_wrapped) 10655 << EnumVal.toString(10) 10656 << EltTy; 10657 else 10658 Diag(IdLoc, diag::warn_enumerator_too_large) 10659 << EnumVal.toString(10); 10660 } else { 10661 EltTy = T; 10662 } 10663 10664 // Retrieve the last enumerator's value, extent that type to the 10665 // type that is supposed to be large enough to represent the incremented 10666 // value, then increment. 10667 EnumVal = LastEnumConst->getInitVal(); 10668 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10669 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 10670 ++EnumVal; 10671 10672 // If we're not in C++, diagnose the overflow of enumerator values, 10673 // which in C99 means that the enumerator value is not representable in 10674 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 10675 // permits enumerator values that are representable in some larger 10676 // integral type. 10677 if (!getLangOpts().CPlusPlus && !T.isNull()) 10678 Diag(IdLoc, diag::warn_enum_value_overflow); 10679 } else if (!getLangOpts().CPlusPlus && 10680 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10681 // Enforce C99 6.7.2.2p2 even when we compute the next value. 10682 Diag(IdLoc, diag::ext_enum_value_not_int) 10683 << EnumVal.toString(10) << 1; 10684 } 10685 } 10686 } 10687 10688 if (!EltTy->isDependentType()) { 10689 // Make the enumerator value match the signedness and size of the 10690 // enumerator's type. 10691 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 10692 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10693 } 10694 10695 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 10696 Val, EnumVal); 10697} 10698 10699 10700Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 10701 SourceLocation IdLoc, IdentifierInfo *Id, 10702 AttributeList *Attr, 10703 SourceLocation EqualLoc, Expr *Val) { 10704 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 10705 EnumConstantDecl *LastEnumConst = 10706 cast_or_null<EnumConstantDecl>(lastEnumConst); 10707 10708 // The scope passed in may not be a decl scope. Zip up the scope tree until 10709 // we find one that is. 10710 S = getNonFieldDeclScope(S); 10711 10712 // Verify that there isn't already something declared with this name in this 10713 // scope. 10714 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 10715 ForRedeclaration); 10716 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10717 // Maybe we will complain about the shadowed template parameter. 10718 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 10719 // Just pretend that we didn't see the previous declaration. 10720 PrevDecl = 0; 10721 } 10722 10723 if (PrevDecl) { 10724 // When in C++, we may get a TagDecl with the same name; in this case the 10725 // enum constant will 'hide' the tag. 10726 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 10727 "Received TagDecl when not in C++!"); 10728 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 10729 if (isa<EnumConstantDecl>(PrevDecl)) 10730 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 10731 else 10732 Diag(IdLoc, diag::err_redefinition) << Id; 10733 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10734 return 0; 10735 } 10736 } 10737 10738 // C++ [class.mem]p15: 10739 // If T is the name of a class, then each of the following shall have a name 10740 // different from T: 10741 // - every enumerator of every member of class T that is an unscoped 10742 // enumerated type 10743 if (CXXRecordDecl *Record 10744 = dyn_cast<CXXRecordDecl>( 10745 TheEnumDecl->getDeclContext()->getRedeclContext())) 10746 if (!TheEnumDecl->isScoped() && 10747 Record->getIdentifier() && Record->getIdentifier() == Id) 10748 Diag(IdLoc, diag::err_member_name_of_class) << Id; 10749 10750 EnumConstantDecl *New = 10751 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 10752 10753 if (New) { 10754 // Process attributes. 10755 if (Attr) ProcessDeclAttributeList(S, New, Attr); 10756 10757 // Register this decl in the current scope stack. 10758 New->setAccess(TheEnumDecl->getAccess()); 10759 PushOnScopeChains(New, S); 10760 } 10761 10762 ActOnDocumentableDecl(New); 10763 10764 return New; 10765} 10766 10767void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 10768 SourceLocation RBraceLoc, Decl *EnumDeclX, 10769 Decl **Elements, unsigned NumElements, 10770 Scope *S, AttributeList *Attr) { 10771 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 10772 QualType EnumType = Context.getTypeDeclType(Enum); 10773 10774 if (Attr) 10775 ProcessDeclAttributeList(S, Enum, Attr); 10776 10777 if (Enum->isDependentType()) { 10778 for (unsigned i = 0; i != NumElements; ++i) { 10779 EnumConstantDecl *ECD = 10780 cast_or_null<EnumConstantDecl>(Elements[i]); 10781 if (!ECD) continue; 10782 10783 ECD->setType(EnumType); 10784 } 10785 10786 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 10787 return; 10788 } 10789 10790 // TODO: If the result value doesn't fit in an int, it must be a long or long 10791 // long value. ISO C does not support this, but GCC does as an extension, 10792 // emit a warning. 10793 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10794 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 10795 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 10796 10797 // Verify that all the values are okay, compute the size of the values, and 10798 // reverse the list. 10799 unsigned NumNegativeBits = 0; 10800 unsigned NumPositiveBits = 0; 10801 10802 // Keep track of whether all elements have type int. 10803 bool AllElementsInt = true; 10804 10805 for (unsigned i = 0; i != NumElements; ++i) { 10806 EnumConstantDecl *ECD = 10807 cast_or_null<EnumConstantDecl>(Elements[i]); 10808 if (!ECD) continue; // Already issued a diagnostic. 10809 10810 const llvm::APSInt &InitVal = ECD->getInitVal(); 10811 10812 // Keep track of the size of positive and negative values. 10813 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 10814 NumPositiveBits = std::max(NumPositiveBits, 10815 (unsigned)InitVal.getActiveBits()); 10816 else 10817 NumNegativeBits = std::max(NumNegativeBits, 10818 (unsigned)InitVal.getMinSignedBits()); 10819 10820 // Keep track of whether every enum element has type int (very commmon). 10821 if (AllElementsInt) 10822 AllElementsInt = ECD->getType() == Context.IntTy; 10823 } 10824 10825 // Figure out the type that should be used for this enum. 10826 QualType BestType; 10827 unsigned BestWidth; 10828 10829 // C++0x N3000 [conv.prom]p3: 10830 // An rvalue of an unscoped enumeration type whose underlying 10831 // type is not fixed can be converted to an rvalue of the first 10832 // of the following types that can represent all the values of 10833 // the enumeration: int, unsigned int, long int, unsigned long 10834 // int, long long int, or unsigned long long int. 10835 // C99 6.4.4.3p2: 10836 // An identifier declared as an enumeration constant has type int. 10837 // The C99 rule is modified by a gcc extension 10838 QualType BestPromotionType; 10839 10840 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 10841 // -fshort-enums is the equivalent to specifying the packed attribute on all 10842 // enum definitions. 10843 if (LangOpts.ShortEnums) 10844 Packed = true; 10845 10846 if (Enum->isFixed()) { 10847 BestType = Enum->getIntegerType(); 10848 if (BestType->isPromotableIntegerType()) 10849 BestPromotionType = Context.getPromotedIntegerType(BestType); 10850 else 10851 BestPromotionType = BestType; 10852 // We don't need to set BestWidth, because BestType is going to be the type 10853 // of the enumerators, but we do anyway because otherwise some compilers 10854 // warn that it might be used uninitialized. 10855 BestWidth = CharWidth; 10856 } 10857 else if (NumNegativeBits) { 10858 // If there is a negative value, figure out the smallest integer type (of 10859 // int/long/longlong) that fits. 10860 // If it's packed, check also if it fits a char or a short. 10861 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 10862 BestType = Context.SignedCharTy; 10863 BestWidth = CharWidth; 10864 } else if (Packed && NumNegativeBits <= ShortWidth && 10865 NumPositiveBits < ShortWidth) { 10866 BestType = Context.ShortTy; 10867 BestWidth = ShortWidth; 10868 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 10869 BestType = Context.IntTy; 10870 BestWidth = IntWidth; 10871 } else { 10872 BestWidth = Context.getTargetInfo().getLongWidth(); 10873 10874 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 10875 BestType = Context.LongTy; 10876 } else { 10877 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10878 10879 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 10880 Diag(Enum->getLocation(), diag::warn_enum_too_large); 10881 BestType = Context.LongLongTy; 10882 } 10883 } 10884 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 10885 } else { 10886 // If there is no negative value, figure out the smallest type that fits 10887 // all of the enumerator values. 10888 // If it's packed, check also if it fits a char or a short. 10889 if (Packed && NumPositiveBits <= CharWidth) { 10890 BestType = Context.UnsignedCharTy; 10891 BestPromotionType = Context.IntTy; 10892 BestWidth = CharWidth; 10893 } else if (Packed && NumPositiveBits <= ShortWidth) { 10894 BestType = Context.UnsignedShortTy; 10895 BestPromotionType = Context.IntTy; 10896 BestWidth = ShortWidth; 10897 } else if (NumPositiveBits <= IntWidth) { 10898 BestType = Context.UnsignedIntTy; 10899 BestWidth = IntWidth; 10900 BestPromotionType 10901 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10902 ? Context.UnsignedIntTy : Context.IntTy; 10903 } else if (NumPositiveBits <= 10904 (BestWidth = Context.getTargetInfo().getLongWidth())) { 10905 BestType = Context.UnsignedLongTy; 10906 BestPromotionType 10907 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10908 ? Context.UnsignedLongTy : Context.LongTy; 10909 } else { 10910 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10911 assert(NumPositiveBits <= BestWidth && 10912 "How could an initializer get larger than ULL?"); 10913 BestType = Context.UnsignedLongLongTy; 10914 BestPromotionType 10915 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10916 ? Context.UnsignedLongLongTy : Context.LongLongTy; 10917 } 10918 } 10919 10920 // Loop over all of the enumerator constants, changing their types to match 10921 // the type of the enum if needed. 10922 for (unsigned i = 0; i != NumElements; ++i) { 10923 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 10924 if (!ECD) continue; // Already issued a diagnostic. 10925 10926 // Standard C says the enumerators have int type, but we allow, as an 10927 // extension, the enumerators to be larger than int size. If each 10928 // enumerator value fits in an int, type it as an int, otherwise type it the 10929 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 10930 // that X has type 'int', not 'unsigned'. 10931 10932 // Determine whether the value fits into an int. 10933 llvm::APSInt InitVal = ECD->getInitVal(); 10934 10935 // If it fits into an integer type, force it. Otherwise force it to match 10936 // the enum decl type. 10937 QualType NewTy; 10938 unsigned NewWidth; 10939 bool NewSign; 10940 if (!getLangOpts().CPlusPlus && 10941 !Enum->isFixed() && 10942 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 10943 NewTy = Context.IntTy; 10944 NewWidth = IntWidth; 10945 NewSign = true; 10946 } else if (ECD->getType() == BestType) { 10947 // Already the right type! 10948 if (getLangOpts().CPlusPlus) 10949 // C++ [dcl.enum]p4: Following the closing brace of an 10950 // enum-specifier, each enumerator has the type of its 10951 // enumeration. 10952 ECD->setType(EnumType); 10953 continue; 10954 } else { 10955 NewTy = BestType; 10956 NewWidth = BestWidth; 10957 NewSign = BestType->isSignedIntegerOrEnumerationType(); 10958 } 10959 10960 // Adjust the APSInt value. 10961 InitVal = InitVal.extOrTrunc(NewWidth); 10962 InitVal.setIsSigned(NewSign); 10963 ECD->setInitVal(InitVal); 10964 10965 // Adjust the Expr initializer and type. 10966 if (ECD->getInitExpr() && 10967 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 10968 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 10969 CK_IntegralCast, 10970 ECD->getInitExpr(), 10971 /*base paths*/ 0, 10972 VK_RValue)); 10973 if (getLangOpts().CPlusPlus) 10974 // C++ [dcl.enum]p4: Following the closing brace of an 10975 // enum-specifier, each enumerator has the type of its 10976 // enumeration. 10977 ECD->setType(EnumType); 10978 else 10979 ECD->setType(NewTy); 10980 } 10981 10982 Enum->completeDefinition(BestType, BestPromotionType, 10983 NumPositiveBits, NumNegativeBits); 10984 10985 // If we're declaring a function, ensure this decl isn't forgotten about - 10986 // it needs to go into the function scope. 10987 if (InFunctionDeclarator) 10988 DeclsInPrototypeScope.push_back(Enum); 10989} 10990 10991Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 10992 SourceLocation StartLoc, 10993 SourceLocation EndLoc) { 10994 StringLiteral *AsmString = cast<StringLiteral>(expr); 10995 10996 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 10997 AsmString, StartLoc, 10998 EndLoc); 10999 CurContext->addDecl(New); 11000 return New; 11001} 11002 11003DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 11004 SourceLocation ImportLoc, 11005 ModuleIdPath Path) { 11006 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 11007 Module::AllVisible, 11008 /*IsIncludeDirective=*/false); 11009 if (!Mod) 11010 return true; 11011 11012 llvm::SmallVector<SourceLocation, 2> IdentifierLocs; 11013 Module *ModCheck = Mod; 11014 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 11015 // If we've run out of module parents, just drop the remaining identifiers. 11016 // We need the length to be consistent. 11017 if (!ModCheck) 11018 break; 11019 ModCheck = ModCheck->Parent; 11020 11021 IdentifierLocs.push_back(Path[I].second); 11022 } 11023 11024 ImportDecl *Import = ImportDecl::Create(Context, 11025 Context.getTranslationUnitDecl(), 11026 AtLoc.isValid()? AtLoc : ImportLoc, 11027 Mod, IdentifierLocs); 11028 Context.getTranslationUnitDecl()->addDecl(Import); 11029 return Import; 11030} 11031 11032void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 11033 IdentifierInfo* AliasName, 11034 SourceLocation PragmaLoc, 11035 SourceLocation NameLoc, 11036 SourceLocation AliasNameLoc) { 11037 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 11038 LookupOrdinaryName); 11039 AsmLabelAttr *Attr = 11040 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 11041 11042 if (PrevDecl) 11043 PrevDecl->addAttr(Attr); 11044 else 11045 (void)ExtnameUndeclaredIdentifiers.insert( 11046 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 11047} 11048 11049void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 11050 SourceLocation PragmaLoc, 11051 SourceLocation NameLoc) { 11052 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 11053 11054 if (PrevDecl) { 11055 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 11056 } else { 11057 (void)WeakUndeclaredIdentifiers.insert( 11058 std::pair<IdentifierInfo*,WeakInfo> 11059 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 11060 } 11061} 11062 11063void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 11064 IdentifierInfo* AliasName, 11065 SourceLocation PragmaLoc, 11066 SourceLocation NameLoc, 11067 SourceLocation AliasNameLoc) { 11068 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 11069 LookupOrdinaryName); 11070 WeakInfo W = WeakInfo(Name, NameLoc); 11071 11072 if (PrevDecl) { 11073 if (!PrevDecl->hasAttr<AliasAttr>()) 11074 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 11075 DeclApplyPragmaWeak(TUScope, ND, W); 11076 } else { 11077 (void)WeakUndeclaredIdentifiers.insert( 11078 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 11079 } 11080} 11081 11082Decl *Sema::getObjCDeclContext() const { 11083 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 11084} 11085 11086AvailabilityResult Sema::getCurContextAvailability() const { 11087 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 11088 return D->getAvailability(); 11089} 11090